diff --git a/packages/core/src/vault-routing.ts b/packages/core/src/vault-routing.ts index 95ca2b40..e747b734 100644 --- a/packages/core/src/vault-routing.ts +++ b/packages/core/src/vault-routing.ts @@ -110,7 +110,7 @@ export function startVaultRoutingWait(input: { /** * Placement offers every eligible vault login that passes the user's floors. * A continue still uses the local plan to find alternatives to the exhausted account. - * The Pi host adapter is not wired because its provider stream gives no reliable request purpose. + * Pi asks only on continuation; its stream has no marker for a new user turn. */ export async function chooseVaultRouting(input: { vaultMode: boolean diff --git a/packages/pi/src/pool-request.ts b/packages/pi/src/pool-request.ts index a7a72d17..63efdbd6 100644 --- a/packages/pi/src/pool-request.ts +++ b/packages/pi/src/pool-request.ts @@ -60,6 +60,7 @@ import { type RoutingMode, type StickyPinPlacement, startVaultRoutingWait, + type VaultRoutingFeedback, } from '@cortexkit/openai-auth-core/internal' import { windowsFromQuotaMap } from '@cortexkit/openai-auth-core/pool-quota' @@ -112,6 +113,8 @@ export interface RouteAttempt { signal?: LimitSignal /** Response headers may arrive before the vault updates its quota reading. */ reading?: OAuthQuotaSnapshot + /** Only an unpublished terminal failure may hand control to vault routing. */ + vaultFeedback?: VaultRoutingFeedback } /** Internal policy interface used before Pi publishes the first stream event. */ @@ -133,6 +136,17 @@ export interface PiWake { signal?: LimitSignal } +export interface PiVaultRetry { + id: string + credentialId: string + identity: string | undefined + accountKey: AccountKey | undefined +} + +type PiVaultDecision = + | { kind: 'vault-refused' } + | { kind: 'vault-retry'; target: PiVaultRetry; delayMs?: number } + export type PiWaitDecision = Extract< LimitDecision, { action: 'hold' | 'wait-then-reselect' } @@ -164,6 +178,11 @@ export interface PiRouteContext { * vault refused to serve a vault account. */ send(account: RouteAccount, tier?: AdmissionTier): Promise + afterVaultLimit?( + account: RouteAccount, + feedback: VaultRoutingFeedback, + routing: PoolRoutingInput, + ): Promise /** The session pin ledger: decides (and, when asked, records) a session's pin. */ placePin(input: StickyPinPlacement): { accountId: string } | undefined /** @@ -185,6 +204,7 @@ export type PiRouteResult = decision: PiWaitDecision | Extract wake?: PiWake } + | PiVaultDecision /** * Pool rows that may serve beside Pi's login: enabled OAuth rows holding a @@ -487,10 +507,60 @@ function routingInput( } } +export function admitPiVaultRetry( + ctx: PiRouteContext, + target: PiVaultRetry, +): { account: RouteAccount; tier: AdmissionTier } | undefined { + const account = ctx.accounts().find((value) => value.id === target.id) + if ( + !account?.vault || + account.identity !== target.identity || + (target.accountKey && + (!account.accountKey || + !sameAccount(account.accountKey, target.accountKey))) + ) + return + const plan = planOrdered({ + ...routingInput(ctx, [account]), + placement: 'roster', + mainId: null, + }) + const tier = plan.kind === 'send' && !plan.lastPath && plan.tiers[account.id] + if (tier) return { account, tier } +} + +async function afterVaultLimit( + ctx: PiRouteContext, + account: RouteAccount, + attempt: A, +): Promise { + if (attempt.vaultFeedback && ctx.afterVaultLimit) + return ctx.afterVaultLimit( + account, + attempt.vaultFeedback, + routingInput(ctx, ctx.accounts()), + ) +} + /** Routes one request and sends it with the chosen account(s). */ export async function routePiRequest( ctx: PiRouteContext, + vaultRetry?: PiVaultRetry, ): Promise> { + if (vaultRetry) { + const admitted = admitPiVaultRetry(ctx, vaultRetry) + if (!admitted) return { kind: 'vault-refused' } + const { account, tier } = admitted + const attempt = await ctx.send(account, tier) + if (!attempt) return { kind: 'vault-refused' } + return ( + (await afterVaultLimit(ctx, account, attempt)) ?? { + kind: 'sent', + attempt, + accountId: account.id, + } + ) + } let accounts = ctx.accounts() const firstReading = waitForFirstQuotaReading( routingInput(ctx, accounts), @@ -560,6 +630,8 @@ export async function routePiRequest( ) { const attempt = await ctx.send(account) if (attempt) { + const routed = await afterVaultLimit(ctx, account, attempt) + if (routed) return routed const after = afterLimit( ctx, account, @@ -672,6 +744,8 @@ async function routeOrdered( unsent.add(id) continue } + const routed = await afterVaultLimit(ctx, account, attempt) + if (routed) return routed last = { attempt, accountId: account.id } attempts.push({ id: account.id, @@ -808,6 +882,8 @@ async function routeSticky( if (!sendable(account)) return undefined let attempt = await ctx.send(account, tiers?.get(id)) if (!attempt) return undefined + const routed = await afterVaultLimit(ctx, account, attempt) + if (routed) return routed let decision: LimitDecision | undefined if ( @@ -854,6 +930,8 @@ async function routeSticky( ? await ctx.send(replacement, tiers?.get(id)) : undefined if (replacement && replaced) { + const routed = await afterVaultLimit(ctx, replacement, replaced) + if (routed) return routed attempt = replaced account = replacement decision = undefined diff --git a/packages/pi/src/runtime.ts b/packages/pi/src/runtime.ts index b3b4c434..6d64d195 100644 --- a/packages/pi/src/runtime.ts +++ b/packages/pi/src/runtime.ts @@ -33,7 +33,10 @@ import type { LimitSignal, PolicyFacts, } from '@cortexkit/common-auth/limits' -import { waitForPi } from '@cortexkit/common-auth/limits' +import { + MAX_SAME_ACCOUNT_HOLD_MS, + waitForPi, +} from '@cortexkit/common-auth/limits' import type { PiSlot } from '@cortexkit/common-auth/pi-slot' import type { PoolRow, PoolStore } from '@cortexkit/common-auth/store' import { @@ -42,10 +45,12 @@ import { applyMidConversationEffort, buildOpenAiQuotaRefusal, type CodexEffortState, + chooseVaultRouting, classifyOpenAiLimitBody, codexRefreshFn, createLogger, createSessionActivityStore, + deferSessionCacheResponseTouch, extractAccountId, hasVaultRoutingAccessor, isCompleteQuotaHeaderFrame, @@ -66,14 +71,17 @@ import { redactCredentialError, redactCredentialResponse, redactCredentialText, + reportVaultRouting, reportVaultRoutingLimit, type SessionDispatch, sessionCacheKeepPlan, startVaultRoutingWait, ttlForModel, VAULT_REQUEST_ROSTER_WAIT_MS, + VAULT_ROUTING_REFUSAL_MESSAGE, VaultBillingAttempt, type VaultModeRefusal, + type VaultRoutingFeedback, vaultLimitsNamespace, vaultModeNoRouteCause, vaultModeRefusalText, @@ -85,6 +93,7 @@ import { windowsFromQuotaMap, } from '@cortexkit/openai-auth-core/pool-quota' import { + type AdmissionTier, CreditsServing, FIRST_QUOTA_READING_WAIT_MS, FORMER_MAIN_ID, @@ -114,6 +123,10 @@ import { import { PiMainAccount } from './main-account.ts' import { getPiAccountPaths } from './paths.ts' import { + admitPiVaultRetry, + type PiRouteContext, + type PiRouteResult, + type PiVaultRetry, type PiWake, type RouteAccount, type RouteAttempt, @@ -187,6 +200,18 @@ interface StreamAttempt extends RouteAttempt { rest: AsyncIterator | undefined } +interface PiRouteExecution { + canWait: boolean + wake?: PiWake + vaultRetry?: PiVaultRetry + attemptedVaultIds: Set + billingAttempt?: number +} + +function piRequestKind(options: SimpleStreamOptions | undefined) { + return options?.cacheRetention === 'none' ? 'generate' : 'primary' +} + function isPiOutput(event: AssistantMessageEvent): boolean { // pi-ai mutates partial in place. Use the event's own text instead of reading // later content through an earlier lifecycle event. @@ -710,11 +735,15 @@ export class PiOpenAIRuntime { let endWait: ReturnType try { let waited = false - let wake: PiWake | undefined + const execution: PiRouteExecution = { + canWait: false, + attemptedVaultIds: new Set(), + } for (;;) { if (options?.signal?.aborted) return const authority = await this.readAuthority() if ( + !execution.vaultRetry && authority !== 'host' && authority !== 'local' && options?.apiKey !== VAULT_PLACEHOLDER_KEY @@ -722,11 +751,14 @@ export class PiOpenAIRuntime { outer.push(errorEvent(model, VAULT_SLOT_REFUSAL)) return } - const attempt = await this.route(model, context, options, { - canWait: !!setWorkingMessage && !waited, - wake, - }) + execution.canWait = !!setWorkingMessage && !waited + const attempt = await this.route(model, context, options, execution) if (options?.signal?.aborted) return + if (attempt.kind === 'vault-refused') { + outer.push(errorEvent(model, VAULT_ROUTING_REFUSAL_MESSAGE)) + return + } + let delayMs: number | undefined if (attempt.kind === 'policy') { const decision = attempt.decision if ( @@ -749,23 +781,30 @@ export class PiOpenAIRuntime { ) return } + execution.wake = attempt.wake + delayMs = decision.delayMs + } + if (attempt.kind === 'vault-retry') { + execution.vaultRetry = attempt.target + execution.wake = undefined + delayMs = attempt.delayMs + } + if (delayMs !== undefined) { + endWait?.('resumed') waited = true const at = this.now() endWait = startVaultRoutingWait({ sessionId: options?.sessionId, reason: 'account_limit', now: at, - nextMs: at + decision.delayMs, + nextMs: at + delayMs, }) let result: 'elapsed' | 'aborted' try { - result = await (this.deps.waitForPi ?? waitForPi)( - decision.delayMs, - { - signal: options?.signal, - setWorkingMessage: setWorkingMessage ?? (() => {}), - }, - ) + result = await (this.deps.waitForPi ?? waitForPi)(delayMs, { + signal: options?.signal, + setWorkingMessage: setWorkingMessage ?? (() => {}), + }) } finally { // A failed wait helper must not leave Pi's working indicator behind. try { @@ -777,9 +816,10 @@ export class PiOpenAIRuntime { endWait = undefined return } - wake = attempt.wake continue } + if (attempt.kind === 'policy' || attempt.kind === 'vault-retry') + continue if (attempt.kind === 'blocked') { outer.push( errorEvent( @@ -793,10 +833,11 @@ export class PiOpenAIRuntime { } endWait?.('resumed') endWait = undefined - for (const event of attempt.buffered) outer.push(event) - if (attempt.rest) { + const { buffered, rest } = attempt.attempt + for (const event of buffered) outer.push(event) + if (rest) { for (;;) { - const next = await attempt.rest.next() + const next = await rest.next() if (next.done) break outer.push(next.value) } @@ -823,18 +864,22 @@ export class PiOpenAIRuntime { model: Model, context: Context, options: SimpleStreamOptions | undefined, - execution: { canWait: boolean; wake?: PiWake; billingAttempt?: number }, + execution: PiRouteExecution, ): Promise< - | ({ kind: 'sent'; decision?: LimitDecision } & StreamAttempt) + | Exclude, { kind: 'blocked' }> | { kind: 'blocked'; block: PiBlock; refusal?: VaultModeRefusal } - | Extract< - Awaited>>, - { kind: 'policy' } - > > { const storage = await this.storage() const settings = this.settings(storage) - const vaultMode = (await this.readAuthority()) !== 'local' + const authority = await this.readAuthority() + const vaultMode = authority !== 'local' + const vaultRetry = execution.vaultRetry + if ( + vaultRetry && + ((authority !== 'host' && authority !== 'vault') || + !hasVaultRoutingAccessor()) + ) + return { kind: 'vault-refused' } if (vaultMode) { // Vault mode: Pi's login (the key Pi hands over) and the pool are not // used. Before the vault's first account list there is nothing to @@ -853,84 +898,167 @@ export class PiOpenAIRuntime { let vaultRefused = false let candidates = 0 let quotaFiltered = false - const run = () => - routePiRequest({ - accounts: () => { - const accounts = this.accounts(settings) - candidates = accounts.length - 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, - mainId: vaultMode ? vaultMainRouteId(this.vault.routes()) : undefined, - sessionId: options?.sessionId, - requestBytes: Buffer.byteLength(JSON.stringify(context), 'utf8'), - now: this.now, - refreshBackoff: (accounts) => - this.pool.refreshBackoffFor( - accounts - .map((account) => this.poolRowById(account.id)) - .filter((row): row is PoolRow => row !== undefined), - ), - requestPull: (id) => this.requestPull(id), - firstReadingWaitMs: - this.deps.firstReadingWaitMs ?? FIRST_READING_WAIT_MS, - captureAdmissionTier: hasVaultRoutingAccessor(), - limitPolicy: { - execute: true, - canWait: execution.canWait, - waitForReset: settings?.waitForReset, - wake: execution.wake, - effectiveModel: model.id, - activity: () => - options?.sessionId - ? this.activity.get(options.sessionId) - : undefined, - onDecision: (decision, facts) => - this.deps.onLimitDecision?.(decision, facts), - }, - send: (account, tier) => - options?.signal?.aborted - ? Promise.resolve(undefined) - : account.vault - ? this.vaultAttempt( - model, - context, - options, - account.id, - execution, - tier === 'free', - ).then((attempt) => { - if (!attempt) vaultRefused = true - return attempt - }) - : account.token - ? this.attempt( - model, - context, - options, - account.id, - account.token, - ) - : Promise.resolve(undefined), - placePin: placePiStickyPin, - creditsServing: this.creditsServing, - // Only the credits info line: this router's debug lines stay off. - log: { - debug: () => {}, - info: (message, data) => routingLog.info(message, data), - }, - }) - const result = await run() - if (result.kind === 'policy') return result + const route: PiRouteContext = { + accounts: () => { + const accounts = this.accounts(settings).filter( + (account) => !vaultMode || account.vault, + ) + candidates = accounts.length + 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, + mainId: vaultMode ? vaultMainRouteId(this.vault.routes()) : undefined, + sessionId: options?.sessionId, + requestBytes: Buffer.byteLength(JSON.stringify(context), 'utf8'), + now: this.now, + refreshBackoff: (accounts) => + this.pool.refreshBackoffFor( + accounts + .map((account) => this.poolRowById(account.id)) + .filter((row): row is PoolRow => row !== undefined), + ), + requestPull: (id) => this.requestPull(id), + firstReadingWaitMs: this.deps.firstReadingWaitMs ?? FIRST_READING_WAIT_MS, + captureAdmissionTier: hasVaultRoutingAccessor(), + limitPolicy: { + execute: true, + canWait: execution.canWait, + waitForReset: settings?.waitForReset, + wake: execution.wake, + effectiveModel: model.id, + activity: () => + options?.sessionId ? this.activity.get(options.sessionId) : undefined, + onDecision: (decision, facts) => + this.deps.onLimitDecision?.(decision, facts), + }, + send: (account, tier) => + options?.signal?.aborted + ? Promise.resolve(undefined) + : account.vault + ? this.vaultAttempt( + model, + context, + options, + account.id, + execution, + tier === 'free', + vaultRetry && + (async (receipt) => { + const authority = await this.readAuthority() + return ( + (authority === 'host' || authority === 'vault') && + !options?.signal?.aborted && + receipt.credentialId === vaultRetry.credentialId && + receipt.accountIdentity === vaultRetry.identity && + admitPiVaultRetry(route, vaultRetry)?.tier + ) + }), + ).then((attempt) => { + if (!attempt) vaultRefused = true + else execution.attemptedVaultIds.add(account.id) + return attempt + }) + : account.token + ? this.attempt(model, context, options, account.id, account.token) + : Promise.resolve(undefined), + afterVaultLimit: async (account, feedback, routing) => { + const refused = { kind: 'vault-refused' } as const + if (options?.signal?.aborted) return refused + const retry = (target: PiVaultRetry, delayMs: number) => + execution.canWait && + delayMs >= 0 && + delayMs <= MAX_SAME_ACCOUNT_HOLD_MS + ? { kind: 'vault-retry' as const, target, delayMs } + : refused + if (feedback.kind === 'backoff') + return retry( + { + id: account.id, + identity: feedback.accountIdentity, + credentialId: feedback.credentialId, + accountKey: account.accountKey, + }, + Math.max(0, feedback.retryAtMs - this.now()), + ) + const routes = this.vault.routes() + const accounts = route.accounts() + const sessionId = options?.sessionId + const answer = await chooseVaultRouting({ + vaultMode, + fresh: false, + sessionId, + request: { modelId: model.id, kind: piRequestKind(options) }, + routes, + routing, + eligibleIds: accounts + .filter( + (candidate) => !execution.attemptedVaultIds.has(candidate.id), + ) + .map((candidate) => candidate.id), + continuation: { + previousId: account.id, + exhausted: feedback.exhausted, + }, + wait: { + activity: sessionId ? this.activity.get(sessionId) : undefined, + accountKey: account.accountKey, + maxSameAccountWait: execution.canWait + ? settings?.routing?.maxSameAccountWait + : 0, + }, + }) + if (!answer) { + // Vault mode admits subscription logins, not paid keys. Without a + // routing answer Pi can still use its order for those logins. + const currentAuthority = await this.readAuthority() + if (currentAuthority !== 'host' && currentAuthority !== 'vault') + return refused + return undefined + } + if (typeof answer === 'string') { + const selected = routes.find((candidate) => candidate.id === answer) + if (!selected?.credentialId) return refused + return { + kind: 'vault-retry', + target: { + id: selected.id, + identity: selected.identity, + credentialId: selected.credentialId, + accountKey: accounts.find((candidate) => candidate.id === answer) + ?.accountKey, + }, + } + } + if ('holdMs' in answer) + return retry( + { + id: account.id, + identity: feedback.exhausted.accountId, + credentialId: feedback.exhausted.credentialId, + accountKey: account.accountKey, + }, + answer.holdMs, + ) + return refused + }, + placePin: placePiStickyPin, + creditsServing: this.creditsServing, + // Only the credits info line: this router's debug lines stay off. + log: { + debug: () => {}, + info: (message, data) => routingLog.info(message, data), + }, + } + const result = await routePiRequest(route, vaultRetry) if (result.kind === 'blocked') { // Vault mode never falls back to a local account: a request no vault // account could take is refused with a fixed text naming the cause. @@ -948,7 +1076,7 @@ export class PiOpenAIRuntime { return { ...result, refusal: 'vault-empty' } return result } - return { kind: 'sent', ...result.attempt, decision: result.decision } + return result } private applyEffort(body: Record, sessionId: string) { @@ -977,18 +1105,21 @@ export class PiOpenAIRuntime { execution?: { billingAttempt?: number }, freeQuota = false, ): Promise { + const kind = piRequestKind(options) + const sessionId = options?.sessionId + const cacheSessionId = kind === 'primary' ? sessionId : undefined let billing: VaultBillingAttempt | undefined if ( receipt?.credentialId && - options?.sessionId && + sessionId && execution && hasVaultRoutingAccessor() ) { execution.billingAttempt = (execution.billingAttempt ?? 0) + 1 billing = new VaultBillingAttempt( - options.sessionId, + sessionId, receipt, - 'primary', + kind, model.id, execution.billingAttempt, (sessionId) => { @@ -1010,6 +1141,7 @@ export class PiOpenAIRuntime { let httpBody: string | undefined let headers: Headers | undefined let limit: { signal: LimitSignal; body: unknown } | undefined + let wsCompleted = false const status = () => limit?.signal.status ?? httpStatus const beginSend = () => { // pi-ai can retry a send or switch transports without ending its stream. @@ -1017,6 +1149,7 @@ export class PiOpenAIRuntime { httpBody = undefined headers = undefined limit = undefined + wsCompleted = false reading = initialReading } const mergeReading = (snapshot: OAuthQuotaSnapshot | undefined) => { @@ -1027,30 +1160,50 @@ export class PiOpenAIRuntime { } reading = { ...reading, ...snapshot } } - const reportLimit = () => { + let vaultFeedback: VaultRoutingFeedback | undefined + let failureReported = false + const reportFailure = () => { if ( + failureReported || !receipt || - !hasVaultRoutingAccessor() || - limit?.signal.kind !== 'quota-exhausted' + options?.signal?.aborted || + !hasVaultRoutingAccessor() ) return - const { signal, body } = limit - reportVaultRoutingLimit( - options?.sessionId, - receipt, - { - window: signal.reason, - resetAt: signal.windows.find( - (window) => window.confirmed && window.provenance === 'provider', - )?.resetAt, - }, - { body, headers, quota: account?.quota, now: signal.observedAt }, - ) + failureReported = true + const responseStatus = status() + if (responseStatus !== 429 && responseStatus !== 403) return + if (responseStatus === 429 && limit?.signal.kind === 'quota-exhausted') { + const { signal, body } = limit + const exhausted = reportVaultRoutingLimit( + sessionId, + receipt, + { + window: signal.reason, + resetAt: signal.windows.find( + (window) => window.confirmed && window.provenance === 'provider', + )?.resetAt, + }, + { body, headers, quota: account?.quota, now: signal.observedAt }, + ) + if (exhausted) { + vaultFeedback = { kind: 'exhausted', exhausted } + return + } + } + // The provider body has already gone through the limit classifier. An + // unproved window must not be promoted to exhaustion a second way. + vaultFeedback = reportVaultRouting(sessionId, receipt, { + status: responseStatus, + headers: headers ?? new Headers(), + now: this.now(), + backoff: true, + }) } const dispatch: SessionDispatch | undefined = - accountKey && options?.sessionId + accountKey && cacheSessionId ? { - sessionId: options.sessionId, + sessionId: cacheSessionId, accountKey, dispatchedAt: this.now(), ttlMs: ttlForModel(JSON.stringify({ model: model.id })), @@ -1067,8 +1220,7 @@ export class PiOpenAIRuntime { } // Pi's compaction and summary calls can carry the routing session id, // but disable caching. They must not pin or change conversation effort. - const effortSessionId = - options?.cacheRetention === 'none' ? undefined : options?.sessionId + const effortSessionId = cacheSessionId const useWebSocketShim = this.deps.installWebSocket && options?.transport !== 'sse' const streamOptions: SimpleStreamOptions = { @@ -1145,6 +1297,12 @@ export class PiOpenAIRuntime { await options?.onResponse?.(response, responseModel) }, onProviderStreamEvent: async (event, eventModel) => { + if ( + httpStatus === undefined && + isRecord(event) && + event.type === 'response.completed' + ) + wsCompleted = true // The bound WebSocket records quota before pi-ai dispatches this callback. if (httpStatus !== undefined || !useWebSocketShim) mergeReading(this.recordQuotaEvent(quotaDispatch, event)) @@ -1214,7 +1372,7 @@ export class PiOpenAIRuntime { failed = true // Only pi-ai's terminal result can make the wire observation a // routing outcome. A retry or fallback inside pi-ai may succeed. - if (event.reason !== 'aborted') reportLimit() + if (event.reason !== 'aborted') reportFailure() // Routing may discard an unpublished error without draining the iterator. billing?.end(outputStarted, false, status()) // pi-ai reuses this message in earlier start/delta events; a clone leaves those aliases raw. @@ -1225,20 +1383,37 @@ export class PiOpenAIRuntime { } yield event } - if (dispatch && stopped && !failed) - recordSessionCompletion( - runtime.activity, - dispatch, - runtime - .accounts(runtime.settings(runtime.storageCache?.storage ?? null)) - .find((value) => value.id === accountId)?.accountKey, - { - kind: 'pi', - stop: 'stop', - aborted: options?.signal?.aborted ?? false, - }, - ) + if (stopped && !failed && !options?.signal?.aborted) { + if (dispatch) + recordSessionCompletion( + runtime.activity, + dispatch, + runtime + .accounts( + runtime.settings(runtime.storageCache?.storage ?? null), + ) + .find((value) => value.id === accountId)?.accountKey, + { kind: 'pi', stop: 'stop', aborted: false }, + ) + // Pi's terminal result comes after it finishes consuming the HTTP + // event stream. A socket must have delivered its completion frame. + const completedStatus = httpStatus ?? (wsCompleted ? 200 : undefined) + if ( + completedStatus !== undefined && + completedStatus >= 200 && + completedStatus < 300 + ) { + reportVaultRouting(sessionId, receipt, { + status: completedStatus, + headers: headers ?? new Headers(), + }) + if (cacheSessionId && hasVaultRoutingAccessor()) + deferSessionCacheResponseTouch(cacheSessionId, runtime.now()) + } + } } catch (error) { + failed = true + reportFailure() billing?.end(outputStarted, false, status()) yield errorEvent( model, @@ -1275,6 +1450,7 @@ export class PiOpenAIRuntime { ...(httpStatus !== undefined && !outputStarted ? { httpStatus } : {}), ...(accountKey ? { accountKey } : {}), ...(limit && !outputStarted ? { signal: limit.signal } : {}), + ...(vaultFeedback && !outputStarted ? { vaultFeedback } : {}), ...(reading ? { reading } : {}), buffered, rest, @@ -1294,11 +1470,22 @@ export class PiOpenAIRuntime { accountId: string, execution: { billingAttempt?: number }, freeQuota = false, + revalidate?: ( + receipt: QuotaReceipt, + ) => Promise, ): Promise { let last: StreamAttempt | undefined const response = await this.vault.send( accountId, async (token, attempt) => { + if (revalidate) { + const tier = await revalidate(attempt) + if (!tier) { + last = undefined + return new Response(null, { status: 200 }) + } + freeQuota = tier === 'free' + } // An attempt the vault retries is dropped unread: it ended without // streaming, so nothing of it reached Pi. last = await this.attempt( diff --git a/packages/pi/src/tests/vault.test.ts b/packages/pi/src/tests/vault.test.ts index 0fe6f4b2..470010ea 100644 --- a/packages/pi/src/tests/vault.test.ts +++ b/packages/pi/src/tests/vault.test.ts @@ -24,6 +24,7 @@ import { mutateAccounts, OpenAiVault, type RoutingMode, + VAULT_ROUTING_REFUSAL_MESSAGE, vaultPaths, } from '@cortexkit/openai-auth-core/internal' import { @@ -47,7 +48,7 @@ import { createPiMenu } from '../commands.ts' import { installRawCodexWebSocket } from '../index.ts' import { RawWebSocket } from '../raw-ws-node.ts' import { clearPiStickyRouting } from '../routing.ts' -import { PiOpenAIRuntime } from '../runtime.ts' +import { PiOpenAIRuntime, type PiOpenAIRuntimeDeps } from '../runtime.ts' import { VAULT_PLACEHOLDER_KEY } from '../vault-slot.ts' import { isolatePiAgentDir } from './test-isolation.ts' @@ -167,7 +168,11 @@ function vault(): OpenAiVault { }) } -function runtimeWith(target: OpenAiVault, webSocket = false): PiOpenAIRuntime { +function runtimeWith( + target: OpenAiVault, + webSocket = false, + deps: Partial = {}, +): PiOpenAIRuntime { return new PiOpenAIRuntime({ streamSimple, createStream: createAssistantMessageEventStream, @@ -176,6 +181,7 @@ function runtimeWith(target: OpenAiVault, webSocket = false): PiOpenAIRuntime { fetchImpl: fakeFetch, firstReadingWaitMs: 0, vault: target, + ...deps, }) } @@ -213,7 +219,449 @@ function enroll() { chmodSync(tokenPath, 0o600) } +function observeRouting( + accountFor?: (ask: Record) => unknown, +) { + const reports: Record[] = [] + Reflect.set(globalThis, routingKey, () => ({ + ...(accountFor && { + accountFor: async (ask: Record) => accountFor(ask), + }), + report: (payload: Record) => { + reports.push(payload) + }, + })) + return reports +} + +function errorMessage(events: AssistantMessageEvent[]) { + const event = events.at(-1) + return event?.type === 'error' ? event.error.errorMessage : undefined +} + +function flushCacheTouches() { + // Cache touches use a deferred timer; queue another timer behind them. + return new Promise((resolve) => setTimeout(resolve, 0)) +} + +const provedLimit = { + type: 'usage_limit_reached', + window: '5h', + resets_in_seconds: 60, +} + describe('Pi and the Claustrum vault', () => { + test('Thalamus reports clean HTTP finishes once, bills helpers as generate and only touches the primary cache', async () => { + const reports = observeRouting() + daemon = await startMockDaemon({ + directory: dir, + credentials: { 'oauth:openai:vault': vaultLogin('chatgpt-vault') }, + }) + enroll() + const target = vault() + const now = Date.now() + const runtime = runtimeWith(target, false, { now: () => now }) + try { + await target.refresh() + await target.pollStale(0) + const primary = await send(runtime, { sessionId: 'primary' }) + const helper = await send(runtime, { + sessionId: 'helper', + cacheRetention: 'none', + }) + expect([primary.at(-1)?.type, helper.at(-1)?.type]).toEqual([ + 'done', + 'done', + ]) + expect(runtime.activity.get('primary')).toMatchObject({ + lastAcceptedAt: now, + }) + expect(runtime.activity.get('helper')).toBeUndefined() + await flushCacheTouches() + expect(reports.filter((report) => report.outcome === 'served')).toEqual( + Array.from({ length: 2 }, () => ({ + outcome: 'served', + account_id: 'chatgpt-vault', + credential_id: 'oauth:openai:vault', + headers: {}, + })), + ) + expect( + reports + .filter((report) => report.kind === 'billing') + .map((report) => report.request_kind), + ).toEqual(['primary', 'generate']) + expect(reports.filter((report) => report.kind === 'cache_touch')).toEqual( + [ + { + kind: 'cache_touch', + at: now, + ttl_ms: 'implicit', + source: 'response', + }, + ], + ) + } finally { + await target.dispose() + await runtime.pool.dispose() + } + }) + + test('Thalamus does not report served for a 200 HTTP stream whose body fails', async () => { + const reports = observeRouting() + daemon = await startMockDaemon({ + directory: dir, + credentials: { 'oauth:openai:vault': vaultLogin('chatgpt-vault') }, + }) + enroll() + const target = vault() + const runtime = runtimeWith(target) + let read = false + try { + await target.refresh() + await target.pollStale(0) + const events = await send(runtime, { + sessionId: 'session-1', + maxRetries: 0, + fetch: (async () => + new Response( + new ReadableStream({ + pull(controller) { + if (read) controller.error(new Error('sentinel broken stream')) + else + controller.enqueue(new TextEncoder().encode('data: {}\n\n')) + read = true + }, + }), + { headers: { 'content-type': 'text/event-stream' } }, + )) as unknown as typeof fetch, + }) + expect(errorMessage(events)).toContain('sentinel broken stream') + expect(read).toBe(true) + await flushCacheTouches() + expect(reports.filter((report) => report.kind !== 'billing')).toEqual([]) + expect(runtime.activity.get('session-1')).toBeUndefined() + } finally { + await target.dispose() + await runtime.pool.dispose() + } + }) + + for (const scenario of [ + { + name: '403 holds the same route', + status: 403, + delay: 3000, + ui: true, + sends: 2, + }, + { + name: 'unproven 429 holds the same route', + status: 429, + delay: 3000, + ui: true, + sends: 2, + }, + { name: 'headless refuses', status: 403, delay: 3000, ui: false, sends: 1 }, + { + name: 'over-cap refuses', + status: 429, + delay: 7_200_000, + ui: true, + sends: 1, + }, + { + name: 'changed account identity refuses', + status: 403, + delay: 3000, + ui: true, + sends: 1, + replace: true, + }, + { + name: 'withdrawn vault custody refuses', + status: 403, + delay: 3000, + ui: true, + sends: 1, + withdraw: true, + }, + ]) { + test(`Thalamus transient backoff: ${scenario.name}`, async () => { + const asks: unknown[] = [] + const reports = observeRouting((ask) => asks.push(ask)) + const credential = 'oauth:openai:a' + daemon = await startMockDaemon({ + directory: dir, + credentials: { + [credential]: vaultLogin('chatgpt-a'), + 'oauth:openai:b': vaultLogin('chatgpt-b'), + }, + }) + enroll() + const target = vault() + let now = Date.now() + const start = now + const waits: number[] = [] + const runtime = runtimeWith(target, false, { + now: () => now, + waitForPi: async (delay) => { + waits.push(delay) + expect(codexTokens).toEqual([chatgptAccessToken('chatgpt-a')]) + if (scenario.replace) { + daemon.credentials[credential] = vaultLogin('chatgpt-other') + await target.refresh() + } + if (scenario.withdraw) rmSync(vaultPaths(stateDir, 'pi').tokenPath) + now += delay + return 'elapsed' + }, + }) + if (scenario.ui) runtime.setWorkingMessage = () => {} + try { + await target.refresh() + await target.pollStale(0) + codexStatus = () => (codexTokens.length === 1 ? scenario.status : 200) + codexReplyHeaders = { 'retry-after': String(scenario.delay / 1000) } + codexErrorBody = + '{"error":{"type":"rate_limit_exceeded","window":"5h"}}' + const events = await send(runtime, { + sessionId: 'session-1', + maxRetries: 0, + }) + const done = scenario.sends === 2 + expect(codexTokens).toEqual( + Array(scenario.sends).fill(chatgptAccessToken('chatgpt-a')), + ) + expect(waits).toEqual( + done || scenario.replace || scenario.withdraw ? [scenario.delay] : [], + ) + expect(events.at(-1)?.type).toBe(done ? 'done' : 'error') + if (!done) + expect(errorMessage(events)).toBe(VAULT_ROUTING_REFUSAL_MESSAGE) + expect(asks).toEqual([]) + expect( + reports.filter((report) => report.kind === 'transient_backoff'), + ).toEqual([ + expect.objectContaining({ + kind: 'transient_backoff', + account_id: 'chatgpt-a', + credential_id: credential, + retry_at_ms: start + scenario.delay, + }), + ]) + expect( + reports.filter((report) => report.outcome === 'served'), + ).toHaveLength(done ? 1 : 0) + const waitReports = reports.filter((report) => report.kind === 'wait') + if (waits.length) + expect(waitReports).toEqual([ + expect.objectContaining({ + phase: 'start', + wait_id: expect.any(String), + }), + expect.objectContaining({ + phase: 'end', + wait_id: waitReports[0]?.wait_id, + outcome: done ? 'resumed' : 'abandoned', + }), + ]) + else expect(waitReports).toEqual([]) + } finally { + await target.dispose() + await runtime.pool.dispose() + } + }) + } + + for (const scenario of [ + { + name: 'uses the named alternative', + answer: { account_id: 'chatgpt-c' }, + next: 'chatgpt-c', + }, + { + name: 'missing answer uses subscription order', + answer: undefined, + next: 'chatgpt-b', + }, + { + name: 'denial does not try the next route', + answer: { refused: { code: 'account_selection_refused' } }, + }, + { + name: 'holds the exhausted route when the cache cap fits', + answer: { account_id: 'chatgpt-a', hold: { retry_after_ms: 3000 } }, + next: 'chatgpt-a', + delay: 3000, + }, + { + name: 'refuses an exhausted hold beyond the cache cap', + answer: { account_id: 'chatgpt-a', hold: { retry_after_ms: 301_000 } }, + delay: 301_000, + }, + ]) { + test(`Thalamus continue: ${scenario.name}`, async () => { + const asks: Record[] = [] + const reports = observeRouting((ask) => { + expect(codexTokens).toEqual([chatgptAccessToken('chatgpt-a')]) + expect( + reports.filter((report) => report.outcome === 'exhausted'), + ).toHaveLength(1) + asks.push(ask) + return scenario.answer + }) + daemon = await startMockDaemon({ + directory: dir, + credentials: { + 'oauth:openai:a': vaultLogin('chatgpt-a'), + 'oauth:openai:b': vaultLogin('chatgpt-b'), + 'oauth:openai:c': vaultLogin('chatgpt-c'), + }, + }) + enroll() + let now = Date.now() + const target = vault() + const waits: number[] = [] + const runtime = runtimeWith(target, false, { + now: () => now, + waitForPi: async (delay) => { + waits.push(delay) + now += delay + return 'elapsed' + }, + }) + if (scenario.delay !== undefined) runtime.setWorkingMessage = () => {} + try { + await target.refresh() + await target.pollStale(0) + const options = { sessionId: 'session-1', maxRetries: 0 } + if (scenario.delay !== undefined) { + expect((await send(runtime, options)).at(-1)?.type).toBe('done') + codexTokens = [] + } + codexStatus = () => (codexTokens.length === 1 ? 429 : 200) + codexErrorBody = JSON.stringify({ error: provedLimit }) + const events = await send(runtime, options) + expect(asks).toEqual([ + expect.objectContaining({ + mode: 'continue', + exhausted: expect.objectContaining({ + account: 'chatgpt-a', + credential_id: 'oauth:openai:a', + limit_window: 'five_hour', + }), + candidates: expect.objectContaining({ + accounts: expect.arrayContaining([ + expect.objectContaining({ account_id: 'chatgpt-b' }), + expect.objectContaining({ account_id: 'chatgpt-c' }), + ]), + }), + }), + ]) + expect(codexTokens).toEqual( + ['chatgpt-a', ...(scenario.next ? [scenario.next] : [])].map((id) => + chatgptAccessToken(id), + ), + ) + expect(waits).toEqual(scenario.next === 'chatgpt-a' ? [3000] : []) + if (scenario.next) expect(events.at(-1)?.type).toBe('done') + else expect(errorMessage(events)).toBe(VAULT_ROUTING_REFUSAL_MESSAGE) + } finally { + await target.dispose() + await runtime.pool.dispose() + } + }) + } + + for (const start of ['toolcall_start', 'text_delta'] as const) { + test(`Thalamus reports a limit after ${start} without another routing action`, async () => { + const asks: unknown[] = [] + const reports = observeRouting((ask) => asks.push(ask)) + daemon = await startMockDaemon({ + directory: dir, + credentials: { + 'oauth:openai:a': vaultLogin('chatgpt-a'), + 'oauth:openai:b': vaultLogin('chatgpt-b'), + }, + }) + enroll() + const target = vault() + const waits: number[] = [] + const now = Date.now() + const runtime = runtimeWith(target, false, { + now: () => now, + waitForPi: async (delay) => { + waits.push(delay) + return 'elapsed' + }, + }) + runtime.setWorkingMessage = () => {} + try { + await target.refresh() + await target.pollStale(0) + const tool = start === 'toolcall_start' + const output = tool + ? [ + 'data: {"type":"response.output_item.added","item":{"type":"function_call","id":"fc1","call_id":"c1","name":"helper","arguments":""}}', + ] + : [ + 'data: {"type":"response.output_item.added","item":{"type":"message","id":"m1","role":"assistant","status":"in_progress","content":[]}}', + 'data: {"type":"response.output_text.delta","item_id":"m1","delta":"partial"}', + ] + const error = tool + ? { code: 'rate_limit_exceeded' } + : { ...provedLimit, code: 'usage_limit_reached' } + const events = await send(runtime, { + sessionId: 'session-1', + maxRetries: 0, + fetch: (async (_input: RequestInfo | URL, init?: RequestInit) => { + codexTokens.push( + new Headers(init?.headers).get('authorization') ?? '', + ) + return new Response( + [ + ...output, + `data: ${JSON.stringify({ type: 'response.failed', response: { error } })}`, + '', + ].join('\n\n'), + { headers: { 'content-type': 'text/event-stream' } }, + ) + }) as typeof fetch, + }) + expect(events.map((event) => event.type)).toContain(start) + expect(errorMessage(events)).toContain('already been shown') + expect(codexTokens).toEqual([ + `Bearer ${chatgptAccessToken('chatgpt-a')}`, + ]) + expect(asks).toEqual([]) + expect(waits).toEqual([]) + await flushCacheTouches() + expect(reports.filter((report) => report.kind !== 'billing')).toEqual([ + { + account_id: 'chatgpt-a', + credential_id: 'oauth:openai:a', + ...(tool + ? { + kind: 'transient_backoff', + retry_at_ms: now + 5000, + provider_code: 'http_429', + } + : { + outcome: 'exhausted', + window: '5h', + resets_at: now + 60_000, + }), + }, + ]) + expect(runtime.activity.get('session-1')).toBeUndefined() + } finally { + await target.dispose() + await runtime.pool.dispose() + } + }) + } + test('vault slow and oversized diagnostics are bounded for pi-ai without rewriting an ordinary refusal', async () => { Reflect.set(globalThis, routingKey, () => ({})) daemon = await startMockDaemon({ @@ -343,15 +791,23 @@ describe('Pi and the Claustrum vault', () => { expect(waits).toEqual([]) expect(asks).toBe(0) expect(decisions).toEqual([]) - expect(reports).toEqual([ - expect.objectContaining({ - kind: 'billing', - attempt: 1, - outcome: 'completed', - status: 200, - credential_id: 'oauth:openai:vault', - }), - ]) + expect(reports.filter((report) => report.kind !== 'cache_touch')).toEqual( + [ + { + account_id: 'chatgpt-vault', + credential_id: 'oauth:openai:vault', + outcome: 'served', + headers: { 'retry-after': '0' }, + }, + expect.objectContaining({ + kind: 'billing', + attempt: 1, + outcome: 'completed', + status: 200, + credential_id: 'oauth:openai:vault', + }), + ], + ) } finally { await target.dispose() await runtime.pool.dispose() @@ -434,7 +890,7 @@ describe('Pi and the Claustrum vault', () => { return undefined }, report: (payload: Record) => { - if (!payload.kind) reports.push(payload) + if (payload.outcome === 'exhausted') reports.push(payload) return new Promise(() => {}) }, })) @@ -503,7 +959,7 @@ describe('Pi and the Claustrum vault', () => { expect(waits).toHaveLength(scenario.wait ? 1 : 0) expect(codexTokens).toHaveLength(scenario.wait ? 2 : 1) expect(events.at(-1)?.type).toBe(scenario.wait ? 'done' : 'error') - expect(asks).toBe(0) + expect(asks).toBe(scenario.accessor && scenario.usage ? 1 : 0) if (!scenario.accessor || !scenario.usage) expect(report).not.toHaveBeenCalled() } finally { @@ -1290,9 +1746,11 @@ describe('Pi and the Claustrum vault', () => { const runtime = runtimeWith(target, true) const sessionId = 'pi-vault-reused-socket' const reports: { session: string; payload: Record }[] = [] + const outcomes: Record[] = [] Reflect.set(globalThis, routingKey, (session: string) => ({ report(payload: Record) { if (payload.kind === 'billing') reports.push({ session, payload }) + else outcomes.push(payload) }, })) const rawSend = RawWebSocket.prototype.send @@ -1407,6 +1865,18 @@ describe('Pi and the Claustrum vault', () => { expect(reports[0]!.payload.attempt_id).not.toBe( reports[1]!.payload.attempt_id, ) + await flushCacheTouches() + expect(outcomes.filter((report) => report.outcome === 'served')).toEqual( + Array.from({ length: 2 }, () => ({ + account_id: 'chatgpt-vault', + credential_id: credential, + outcome: 'served', + headers: {}, + })), + ) + expect( + outcomes.filter((report) => report.kind === 'cache_touch'), + ).toHaveLength(2) expect(codexTokens).toEqual([]) } finally { usage.mockRestore()