diff --git a/docs/limit-policy-conformance.md b/docs/limit-policy-conformance.md index 9797c3f8..0c25466c 100644 --- a/docs/limit-policy-conformance.md +++ b/docs/limit-policy-conformance.md @@ -87,7 +87,7 @@ The adoption column includes the deliberate changes to OA-23/32/36/38/49/50/57/5 | OA-10 | R | Future explicit reset beats cached reset; storing a mark has no hold cap. | [`packages/opencode/src/tests/quota-rate-limit.test.ts`](../packages/opencode/src/tests/quota-rate-limit.test.ts) → `prefers an explicit provider reset over cached quota reset math` | [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-10 explicit future reset beats cached primary without a hold cap` | N/A — Pi has no reset-to-mark resolver. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | | OA-11 | R | Only exact primary/secondary may borrow a future cached reset; this resolver has no freshness/headroom check. | [`packages/opencode/src/tests/quota-rate-limit.test.ts`](../packages/opencode/src/tests/quota-rate-limit.test.ts) → `prefers the named window when present and future`; [`packages/opencode/src/tests/quota-rate-limit.test.ts`](../packages/opencode/src/tests/quota-rate-limit.test.ts) → `does not borrow primary for a secondary-named frame` | [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-6/11 exact named cached reset resolves zero header even with stale healthy reading` | N/A — Pi has no reset-to-mark resolver. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | | OA-12 | R | Invalid/past/equal reset falls through and never borrows another window. | [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-12 equal named reset and invalid explicit resets never borrow the sibling` | [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-12 equal primary reset with invalid or nonfuture explicit 0 never borrows secondary`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-12 equal primary reset with invalid or nonfuture explicit -1 never borrows secondary`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-12 equal primary reset with invalid or nonfuture explicit invalid never borrows secondary`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-12 equal primary reset with invalid or nonfuture explicit NaN never borrows secondary`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-12 equal primary reset with invalid or nonfuture explicit Infinity never borrows secondary` | N/A — Pi has no reset-to-mark resolver. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | -| OA-13 | R | Named failed-frame signal belongs to the sending account; the mark is account-wide. | [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `attributes a mid-stream response.failed rate_limit_reached_type to the connection that sent it` | [`packages/opencode/src/tests/opencode2-plugin.test.ts`](../packages/opencode/src/tests/opencode2-plugin.test.ts) → `moves a WebSocket rate-limit refusal before output, and never retries one after output` | N/A — Pi frames are token-attributed readings, not marks. Owning boundary: [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `a codex.rate_limits WebSocket frame lands on the account whose token opened the socket`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | +| OA-13 | R | Named failed-frame signal belongs to the sending account; the mark is account-wide. | [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `attributes a mid-stream response.failed rate_limit_reached_type to the connection that sent it` | [`packages/opencode/src/tests/opencode2-plugin.test.ts`](../packages/opencode/src/tests/opencode2-plugin.test.ts) → `moves a WebSocket rate-limit refusal before output, and never retries one after output` | N/A — Pi frames are token-attributed readings, not marks. Owning boundary: [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `a codex.rate_limits WebSocket frame lands on the account that sent the request`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | | OA-14 | B | OC1 WS admission marks then yields a retryable body error; malformed dropped frame is not output. | [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `marks an admission-time usage limit with the provider reset before rejecting the stream`; [`packages/opencode/src/tests/ws-tool-call-recovery.test.ts`](../packages/opencode/src/tests/ws-tool-call-recovery.test.ts) → `lifecycle and malformed dropped frames are not output and the limit stays retryable` | N/A — OC2 has feedback/retry, not OC1 body-error executor. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-55 failed-event code=usage_limit_reached, status=undefined`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-55 failed-event type=rate_limit_exceeded, status=429`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-55 failed-event allow-list and code precedence reject unrelated errors`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-50/55 lifecycle and quota are not output; function-call envelopes are output` | N/A — Pi has buffered SDK events, not OC1 body errors. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 ordered captured 429 with start head routes before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 synchronous setup throw has no captured status and cannot advance` | | OA-15 | B | Raw upgrade preserves status/headers/body; native API falls back to HTTP; no new raw OC1 Retry-After parser. | [`packages/opencode/src/tests/raw-ws.test.ts`](../packages/opencode/src/tests/raw-ws.test.ts) → `preserves status and structured usage-limit details from a rejected upgrade`; [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `falls back to HTTP when a native WebSocket upgrade fails before open`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-1-9/15 OC1 raw admission does not parse Retry-After headers` | N/A — OC2 installer owns transport, not OC1 raw upgrade. Owning boundary: [`packages/opencode/src/tests/opencode2-plugin.test.ts`](../packages/opencode/src/tests/opencode2-plugin.test.ts) → `moves a WebSocket rate-limit refusal before output, and never retries one after output` | N/A — Pi SDK owns transport, not OC1 raw upgrade. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 ordered captured 429 with start head routes before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 synchronous setup throw has no captured status and cannot advance` | | OA-16 | R | Auth/unrelated failure creates no exhaustion signal or timed mark; status routing remains possible. | [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `does not classify a 503 circuit-open admission error as a rate limit`; [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `auth 401 beats fitting cache, exhausted reading and usage-limit body` | [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-55 failed-event allow-list and code precedence reject unrelated errors` | [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `sticky-balanced 401 parsed usage body never builds hold facts` | @@ -100,7 +100,7 @@ The adoption column includes the deliberate changes to OA-23/32/36/38/49/50/57/5 | OA-23 | D | Registry paths replace the never-released map with schema-safe release/flush/handoff/hydration and durability; legacy exception remains explicit. | [`packages/opencode/src/tests/opencode-limit-source.test.ts`](../packages/opencode/src/tests/opencode-limit-source.test.ts) → `last-owner disposal hands off a pending journal and a new owner hydrates it`; legacy exception: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-21/23 legacy managers are process-local, not a durable registry` | [`packages/opencode/src/tests/opencode2-rate-limits.test.ts`](../packages/opencode/src/tests/opencode2-rate-limits.test.ts) → `persists the account-wide pool mark after the last location releases`; [`packages/opencode/src/tests/opencode2-rate-limits.test.ts`](../packages/opencode/src/tests/opencode2-rate-limits.test.ts) → `pool: LimitsEnvelopeConflictError logs once and never reacquires that store` | N/A — Pi never acquires/releases a registry. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | | OA-24 | R | Healthy quota/success never clears a migrated/OC2 live mark; expired-probe recovery is separately gated. | [`packages/opencode/src/tests/opencode-limit-source.test.ts`](../packages/opencode/src/tests/opencode-limit-source.test.ts) → `shares one core lease with OC1 initialized first and writes nothing on healthy paths`; [`packages/opencode/src/tests/opencode-limit-source.test.ts`](../packages/opencode/src/tests/opencode-limit-source.test.ts) → `shares one core lease with OC2 initialized first and writes nothing on healthy paths`; [`packages/core/src/tests/limit-registry.test.ts`](../packages/core/src/tests/limit-registry.test.ts) → `live escape success, parsed limits and failed probes never earn recovery clears`; [`packages/core/src/tests/limit-recovery.test.ts`](../packages/core/src/tests/limit-recovery.test.ts) → `cold expired hydration and second-owner reload each earn one account-specific clear` | [`packages/opencode/src/tests/opencode2-rate-limits.test.ts`](../packages/opencode/src/tests/opencode2-rate-limits.test.ts) → `vault http: live-mark escape never clears, expired clean probe clears only once` | N/A — Pi healthy responses do not operate on mark journals. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | | OA-25 | R+D | Replacement never inherits old mark; refresh/rotation retains it. Stable account/incarnation fences: same-identity relogin drops the mark; same-identity rows no longer share it. | [`packages/opencode/src/tests/opencode-limit-source.test.ts`](../packages/opencode/src/tests/opencode-limit-source.test.ts) → `projects only live whole-account pool marks matching the current namespace and incarnation`; [`packages/core/src/tests/limit-registry.test.ts`](../packages/core/src/tests/limit-registry.test.ts) → `keys isolate duplicate identities and relogin while refresh and receipt rotation retain them` | [`packages/opencode/src/tests/opencode-limit-source.test.ts`](../packages/opencode/src/tests/opencode-limit-source.test.ts) → `projects only live whole-account pool marks matching the current namespace and incarnation`; [`packages/core/src/tests/limit-registry.test.ts`](../packages/core/src/tests/limit-registry.test.ts) → `keys isolate duplicate identities and relogin while refresh and receipt rotation retain them` | N/A — Pi has no mark inheritance/fence. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change`; [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `activity samples dispatch time, model TTL and verified identity across token refresh` | -| OA-26 | R | Pi frames are token-attributed quota readings; Pi produces/consumes no timed marks. | N/A — OC1 also produces timed marks; no Pi-only prohibition. Owning boundary: [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `attributes a mid-stream response.failed rate_limit_reached_type to the connection that sent it` | N/A — OC2 also produces timed marks; no Pi-only prohibition. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-1 HTTP absolute reset beats both relative reset and Retry-After` | [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `a codex.rate_limits WebSocket frame lands on the account whose token opened the socket`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | +| OA-26 | R | Pi frames are token-attributed quota readings; Pi produces/consumes no timed marks. | N/A — OC1 also produces timed marks; no Pi-only prohibition. Owning boundary: [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `attributes a mid-stream response.failed rate_limit_reached_type to the connection that sent it` | N/A — OC2 also produces timed marks; no Pi-only prohibition. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-1 HTTP absolute reset beats both relative reset and Retry-After` | [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `a codex.rate_limits WebSocket frame lands on the account that sent the request`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-1-26 Pi never acquires a mark registry on first request or projection change` | | OA-27 | R | Ordered OC1 configured statuses advance once per account without requiring exhaustion; only a separate confirmed/cache companion may hold. | [`packages/opencode/src/tests/pool-request.test.ts`](../packages/opencode/src/tests/pool-request.test.ts) → `main-first: a 429 from main is retried on the next row`; [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `confirmed fitting HTTP reset returns pinned hold bytes and never waits or sends B` | N/A — OC2 installer retries, not ordered status loop. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-49 original confirmed HTTP refusal without cache queues B at zero delay`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-49 fitting-cache companion targets A for the maximum fitting blocker`; [`packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc2-conformance.test.ts) → `OA-49 four-day blocker companion vetoes the same-account cache hold` | [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 ordered captured 429 with start head routes before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 synchronous setup throw has no captured status and cannot advance` | | OA-28 | R | Ordered OC1/Pi out-of-list status passes through before reduction. In-list/no-next invokes the decision: confirmed fitting reset holds, otherwise byte-exact provider response. | [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `out-of-list parsed 429 passes byte-exact with no decision at 15`; [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `in-list confirmed no-next response calls the reducer without selection and holds`; [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `in-list unconfirmed no-next response calls the reducer and preserves every provider byte` | N/A — OC2 installer owns retry disposition. Owning boundary: [`packages/opencode/src/tests/opencode2-limit-policy.test.ts`](../packages/opencode/src/tests/opencode2-limit-policy.test.ts) → `single-account confirmed OA-51 preserves host delay at 15` | [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `ordered out-of-list confirmed 429 bypasses the reducer and preserves the provider error`; [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `ordered no-next usage_limit_reached decides once before publication without UI` | | OA-29 | B | Indeterminate possibly-sent throw never authorizes another account send; preserve prior readable response where applicable. | [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `an indeterminate fallback send keeps the prior provider response and never retries another account` | [`packages/opencode/src/tests/opencode2-retry-choice.test.ts`](../packages/opencode/src/tests/opencode2-retry-choice.test.ts) → `after output a witnessed HTTP body read failure continues on the same account` | [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 synchronous setup throw has no captured status and cannot advance` | diff --git a/packages/core/src/quota-refusal.ts b/packages/core/src/quota-refusal.ts index 473d8afa..847548a3 100644 --- a/packages/core/src/quota-refusal.ts +++ b/packages/core/src/quota-refusal.ts @@ -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: diff --git a/packages/core/src/tests/quota-refusal.test.ts b/packages/core/src/tests/quota-refusal.test.ts index e1040946..64833dd6 100644 --- a/packages/core/src/tests/quota-refusal.test.ts +++ b/packages/core/src/tests/quota-refusal.test.ts @@ -13,6 +13,7 @@ import { LimitProvenanceStore } from '../limit-provenance' import { buildOpenAiQuotaRefusal, decideOpenAiTerminal, + OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE, type OpenAiTerminalAccount, openAiLimitMessages, openAiTerminalFacts, @@ -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|(? 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: diff --git a/packages/pi/README.md b/packages/pi/README.md index 91615277..46d27d32 100644 --- a/packages/pi/README.md +++ b/packages/pi/README.md @@ -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 diff --git a/packages/pi/src/index.ts b/packages/pi/src/index.ts index 2f2f30af..edf29106 100644 --- a/packages/pi/src/index.ts +++ b/packages/pi/src/index.ts @@ -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` @@ -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' @@ -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, context, options) => runtime.stream(model, context, options), @@ -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( diff --git a/packages/pi/src/pool-request.ts b/packages/pi/src/pool-request.ts index 6c51b846..576dce30 100644 --- a/packages/pi/src/pool-request.ts +++ b/packages/pi/src/pool-request.ts @@ -620,7 +620,11 @@ async function routeOrdered( 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', { diff --git a/packages/pi/src/pool-source.ts b/packages/pi/src/pool-source.ts index db261412..e6a92ad2 100644 --- a/packages/pi/src/pool-source.ts +++ b/packages/pi/src/pool-source.ts @@ -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 { if (this.setAside()) return Promise.resolve() const now = this.now() @@ -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 { + 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) diff --git a/packages/pi/src/runtime.ts b/packages/pi/src/runtime.ts index d866a6ae..3cc7b275 100644 --- a/packages/pi/src/runtime.ts +++ b/packages/pi/src/runtime.ts @@ -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, @@ -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': @@ -397,7 +404,7 @@ export class PiOpenAIRuntime { syncVaultSlot(refresh?: () => unknown, explicit = false): Promise { return this.withSlot(async () => { await this.reconcileSlot(explicit) - if (this.slotNeedsRefresh && refresh) { + if (!isVaultHosted() && this.slotNeedsRefresh && refresh) { await refresh() this.slotNeedsRefresh = false } @@ -425,13 +432,17 @@ export class PiOpenAIRuntime { } private async reconcileSlot(explicit = false): Promise { - 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 = @@ -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() @@ -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)) @@ -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>>, { kind: 'policy' } @@ -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({ 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, @@ -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 diff --git a/packages/pi/src/tests/hosted-startup.test.ts b/packages/pi/src/tests/hosted-startup.test.ts new file mode 100644 index 00000000..156bdb24 --- /dev/null +++ b/packages/pi/src/tests/hosted-startup.test.ts @@ -0,0 +1,239 @@ +import { expect, spyOn, test } from 'bun:test' +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { VAULT_MODE_REFUSALS } from '@cortexkit/openai-auth-core/internal' +import { + createAgentSession, + DefaultResourceLoader, + SessionManager, + SettingsManager, + VERSION, +} from '@earendil-works/pi-coding-agent' +import { installVaultRelay } from '../../../core/src/tests/fixtures/host-vault.ts' +import { + chatgptAccessToken, + startMockDaemon, + vaultLogin, +} from '../../../core/src/tests/fixtures/mock-claustrum.ts' +import openAIAuth from '../index.ts' +import { PiOpenAIRuntime } from '../runtime.ts' +import { installHostedVaultKey, VAULT_PLACEHOLDER_KEY } from '../vault-slot.ts' +import { isolatePiAgentDir } from './test-isolation.ts' + +const agentDir = isolatePiAgentDir() +const nativeBearer = chatgptAccessToken('native-hosted-test') +const vaultBearer = chatgptAccessToken('vault-hosted-test') + +async function exerciseStart({ + hosted = true, + login, + hasVaultLogin = true, +}: { + hosted?: boolean + login: 'valid' | 'expired' | 'absent' + hasVaultLogin?: boolean +}) { + const dir = agentDir() + const authPath = join(dir, 'auth.json') + const expires = login === 'expired' ? 1 : Date.now() + 3_600_000 + const nativeEntry = + login === 'absent' + ? '' + : `,\n "openai-codex": { "type": "oauth", "access": "${nativeBearer}", "refresh": "native-refresh", "expires": ${expires} }` + const original = `{\n "unrelated": { "type": "api_key", "key": "not-for-codex" }${nativeEntry}\n}\n` + writeFileSync(authPath, original, { mode: 0o600 }) + + const daemon = hosted + ? await startMockDaemon({ + directory: dir, + credentials: hasVaultLogin + ? { 'oauth:openai:hosted': vaultLogin('vault-hosted-test') } + : {}, + }) + : undefined + const relay = daemon + ? await installVaultRelay(daemon.connectionFile) + : undefined + const sends: string[] = [] + const polls: string[] = [] + let refreshes = 0 + const originalFetch = globalThis.fetch + globalThis.fetch = Object.assign( + async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input instanceof Request ? input.url : input) + const token = + new Headers(init?.headers) + .get('authorization') + ?.replace(/^Bearer /, '') ?? '' + if (url.startsWith('https://auth.openai.com/oauth/token')) { + refreshes++ + return new Response('{}', { status: 400 }) + } + if (url.endsWith('/wham/usage')) { + polls.push(token) + const reset = Math.floor(Date.now() / 1000) + 3600 + return Response.json({ + rate_limit: { + primary_window: { + used_percent: 10, + limit_window_seconds: 18000, + reset_at: reset, + }, + secondary_window: { + used_percent: 10, + limit_window_seconds: 604800, + reset_at: reset + 86400, + }, + }, + }) + } + if (!url.endsWith('/codex/responses')) + throw new Error(`Unexpected test request: ${url}`) + sends.push(token) + return new Response( + 'data: {"type":"response.completed","response":{"id":"r1","status":"completed","usage":{"input_tokens":1,"output_tokens":0,"total_tokens":1}}}\n\n', + { headers: { 'content-type': 'text/event-stream' } }, + ) + }, + originalFetch, + ) + + const sync = spyOn(PiOpenAIRuntime.prototype, 'syncVaultSlot') + const interval = globalThis.setInterval + const timers: ReturnType[] = [] + let tick: (() => void) | undefined + globalThis.setInterval = (( + ...[run, ms, ...args]: Parameters + ) => { + const timer = interval(run, ms, ...args) + if (ms === 5000) { + tick = () => run(...args) + timers.push(timer) + } + return timer + }) as typeof setInterval + let session: + | Awaited>['session'] + | undefined + try { + const settingsManager = SettingsManager.inMemory({ + defaultProvider: 'openai-codex', + defaultModel: 'gpt-6.1-sol', + transport: 'sse', + retry: { enabled: false, provider: { maxRetries: 0 } }, + }) + const resourceLoader = new DefaultResourceLoader({ + cwd: dir, + agentDir: dir, + settingsManager, + noExtensions: true, + extensionFactories: [ + async (pi) => { + await openAIAuth(pi) + expect(readFileSync(authPath, 'utf8')).toBe(original) + pi.on('session_start', (_event, ctx) => { + expect( + ctx.modelRegistry.getRegisteredProviderConfig('openai-codex') + ?.apiKey, + ).toBe(hosted ? VAULT_PLACEHOLDER_KEY : undefined) + }) + }, + ], + }) + await resourceLoader.reload() + const created = await createAgentSession({ + cwd: dir, + agentDir: dir, + settingsManager, + resourceLoader, + sessionManager: SessionManager.inMemory(dir), + noTools: 'all', + }) + session = created.session + expect(created.extensionsResult.errors).toEqual([]) + if (login === 'absent') { + // Before session_start installs the override, registration alone can + // resolve a credential for an empty slot. + expect( + (await session.modelRuntime.getAuth('openai-codex'))?.auth.apiKey, + ).toBe(VAULT_PLACEHOLDER_KEY) + } + const extensionErrors: unknown[] = [] + await session.bindExtensions({ + onError: (error) => { + extensionErrors.push(error) + }, + }) + expect(extensionErrors).toEqual([]) + if (login === 'absent') { + // Pi chooses its initial model before the extension provider is ready + // when native auth is absent; select the now-available Codex model. + const model = session.modelRuntime.getModel('openai-codex', 'gpt-6.1-sol') + if (!model) throw new Error('Pi did not offer openai-codex/gpt-6.1-sol') + await session.setModel(model) + } + expect(session.model?.id).toBe('gpt-6.1-sol') + expect(readFileSync(authPath, 'utf8')).toBe(original) + + if (!tick) throw new Error('The periodic provider sync was not scheduled') + const callsBefore = sync.mock.calls.length + tick() + expect(sync.mock.calls).toHaveLength(callsBefore + 1) + await sync.mock.results.at(-1)?.value + expect(readFileSync(authPath, 'utf8')).toBe(original) + + await session.prompt('hello') + const last = session.messages.at(-1) + if (hosted && !hasVaultLogin) { + expect(last).toMatchObject({ + role: 'assistant', + stopReason: 'error', + errorMessage: VAULT_MODE_REFUSALS['vault-empty'], + }) + expect(sends).toEqual([]) + expect(polls).toEqual([]) + } else { + const expected = hosted ? vaultBearer : nativeBearer + expect(last).toMatchObject({ role: 'assistant', stopReason: 'stop' }) + expect(sends).toEqual([expected]) + expect(polls).toContain(expected) + expect(polls.every((token) => token === expected)).toBe(true) + } + expect(refreshes).toBe(0) + expect(readFileSync(authPath, 'utf8')).toBe(original) + } finally { + await session?.extensionRunner.emit({ + type: 'session_shutdown', + reason: 'quit', + }) + session?.dispose() + for (const timer of timers) clearInterval(timer) + globalThis.setInterval = interval + globalThis.fetch = originalFetch + sync.mockRestore() + await relay?.close() + await daemon?.stop() + } +} + +test.each(['valid', 'expired', 'absent'] as const)( + 'a hosted Pi session with %s native login keeps auth.json and serves with the vault', + async (login) => exerciseStart({ login }), +) + +test('a hosted Pi session without a usable vault receipt gets the fixed refusal', async () => { + await exerciseStart({ login: 'expired', hasVaultLogin: false }) +}) + +test('a non-hosted Pi session still uses its native login', async () => { + await exerciseStart({ login: 'valid', hosted: false }) +}) + +test('a missing Pi credential override bridge warns once with the installed version', async () => { + const warnings: string[] = [] + const log = { warn: (message: string) => warnings.push(message) } + await installHostedVaultKey({}, log) + await installHostedVaultKey({ runtime: { setRuntimeApiKey: null } }, log) + expect(warnings).toHaveLength(1) + expect(warnings[0]).toContain(`Pi ${VERSION}`) +}) diff --git a/packages/pi/src/tests/pool-routing.test.ts b/packages/pi/src/tests/pool-routing.test.ts index 3ba9521c..bdb5b2a1 100644 --- a/packages/pi/src/tests/pool-routing.test.ts +++ b/packages/pi/src/tests/pool-routing.test.ts @@ -12,6 +12,7 @@ import { openPoolStore, type PoolStore } from '@cortexkit/common-auth/store' import { type AccountPaths, mutateAccounts, + normalizeQuotaHeaders, type RoutingMode, saveAccounts, } from '@cortexkit/openai-auth-core/internal' @@ -897,56 +898,95 @@ describe('Pi requests on the account pool', () => { expect(getPiStickyRouting('session-1')).toBeDefined() }) - test('an expired pool token is refreshed through the store, and the request never waits for it', async () => { - const expired = jwt('acct-alpha', 'old') - const fresh = jwt('acct-alpha', 'new') - rmSync(paths.configPath) - rmSync(paths.statePath) - await addRow('alpha', expired, 'acct-alpha', Date.now() - 1_000) - await addRow('beta', BETA_TOKEN, 'acct-beta') - let refreshes = 0 - let releaseRefresh!: () => void - const refreshGate = new Promise((resolve) => { - releaseRefresh = resolve - }) - tokenHandler = async () => { - refreshes++ - await refreshGate - return Response.json({ - access_token: fresh, - refresh_token: 'refresh-alpha-2', - expires_in: 864_000, + test.each(['expired', 'missing', 'still-valid'] as const)( + 'a %s fallback token uses the correct refresh timing before routing', + async (state) => { + const old = jwt('acct-alpha', 'old') + const fresh = jwt('acct-alpha', 'new') + rmSync(paths.configPath) + rmSync(paths.statePath) + await addRow( + 'alpha', + state === 'missing' ? '' : old, + 'acct-alpha', + Date.now() + (state === 'expired' ? -1_000 : 5 * 60_000), + ) + await addRow('beta', BETA_TOKEN, 'acct-beta') + await mutateAccounts((current) => { + current.refresh = { refreshBeforeExpiryMinutes: 30 } + return current + }, paths) + let refreshes = 0 + const started = Promise.withResolvers() + let releaseRefresh!: () => void + const refreshGate = new Promise((resolve) => { + releaseRefresh = resolve }) - } - const runtime = makeRuntime() - // Every account's first quota reading lands before the first request; - // that request is what starts alpha's refresh. - await ready(runtime) - await setMode('fallback-first') - - // Alpha's refresh is held at the token endpoint, so this request is - // served by beta without waiting for it. - const first = await send(runtime) - expect(first[0]?.type).toBe('start') - expect(codexTokens()).toEqual([BETA_TOKEN]) + tokenHandler = async () => { + refreshes++ + started.resolve() + await refreshGate + return Response.json({ + access_token: fresh, + refresh_token: 'refresh-alpha-2', + expires_in: 864_000, + }) + } + const runtime = makeRuntime() + await ready(runtime) + await setMode('fallback-first') + if (state === 'missing') { + // The row already has a usage reading from when it held an access token. + runtime.pool.recordSnapshot( + 'alpha', + { + ...normalizeQuotaHeaders( + new Headers({ + 'x-codex-primary-used-percent': '10', + 'x-codex-primary-window-minutes': '300', + }), + ), + }, + old, + true, + ) + await runtime.pool.settled() + } - releaseRefresh() - await runtime.pool.settled() - expect(refreshes).toBe(1) - const load = await store().read() - const alpha = - load.status === 'ready' - ? load.rows.find((row) => row.id === 'alpha') - : undefined - expect(alpha?.credential).toMatchObject({ - type: 'oauth', - access: fresh, - refresh: 'refresh-alpha-2', - }) + const first = send(runtime) + let sentWhileRefreshing: boolean + try { + await started.promise + sentWhileRefreshing = await Promise.race([ + first.then(() => true), + Bun.sleep(50).then(() => false), + ]) + } finally { + releaseRefresh() + } + expect((await first)[0]?.type).toBe('start') + await runtime.pool.settled() + expect(sentWhileRefreshing).toBe(state === 'still-valid') + expect(codexTokens()).toEqual([state === 'still-valid' ? old : fresh]) + expect(refreshes).toBe(1) + const load = await store().read() + const alpha = + load.status === 'ready' + ? load.rows.find((row) => row.id === 'alpha') + : undefined + expect(alpha?.credential).toMatchObject({ + type: 'oauth', + access: fresh, + refresh: 'refresh-alpha-2', + }) - await send(runtime) - expect(codexTokens()).toEqual([BETA_TOKEN, fresh]) - }) + await send(runtime) + expect(codexTokens()).toEqual([ + state === 'still-valid' ? old : fresh, + fresh, + ]) + }, + ) test('quota from a response lands on the row that served it', async () => { const runtime = makeRuntime() diff --git a/packages/pi/src/tests/startup-order.test.ts b/packages/pi/src/tests/startup-order.test.ts index 640140df..e3da4367 100644 --- a/packages/pi/src/tests/startup-order.test.ts +++ b/packages/pi/src/tests/startup-order.test.ts @@ -9,7 +9,10 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { vaultPaths, vaultStateDir } from '@cortexkit/openai-auth-core/internal' +import { + OpenAiVault, + vaultStateDir, +} from '@cortexkit/openai-auth-core/internal' import { createAgentSession, ModelRuntime, @@ -140,13 +143,6 @@ test('Pi 1.4.0 startup swaps the enrolled slot before auth resolution and the fi { mode: 0o600 }, ) writeFileSync(pluginAuthPath, pluginAuthBefore, { mode: 0o600 }) - const stateDir = vaultStateDir(process.env.PI_OPENAI_AUTH_STATE_FILE) - mkdirSync(stateDir, { mode: 0o700 }) - writeFileSync( - vaultPaths(stateDir, 'pi').tokenPath, - JSON.stringify({ token: '01'.repeat(32), token_generation: 1 }), - { mode: 0o600 }, - ) writeFileSync( join(piAgentDir, 'settings.json'), JSON.stringify({ @@ -236,6 +232,21 @@ export default async function(pi) { } return new Response('unexpected', { status: 500 }) }) as typeof fetch + // Complete the approval outside the Pi menu, then start a new session + // against the persisted enrollment. + const enrollment = new OpenAiVault({ + host: 'pi', + stateDir: vaultStateDir(process.env.PI_OPENAI_AUTH_STATE_FILE), + connectionFile: () => daemon.connectionFile, + pollIntervalMs: 0, + }) + try { + expect((await enrollment.connectStep()).state).toBe('pending') + daemon.approve('request-1') + expect((await enrollment.connectStep()).state).toBe('approved') + } finally { + await enrollment.dispose() + } const created = await createAgentSession({ cwd: dir, agentDir: piAgentDir, diff --git a/packages/pi/src/tests/vault-mode.test.ts b/packages/pi/src/tests/vault-mode.test.ts index 7311fe0e..1ab7fd72 100644 --- a/packages/pi/src/tests/vault-mode.test.ts +++ b/packages/pi/src/tests/vault-mode.test.ts @@ -109,12 +109,12 @@ function sseOk(): Response { }) } -function whamOk(): Response { +function whamOk(usedPercent = 10): Response { const resetAt = Math.floor((Date.now() + 7_200_000) / 1000) return Response.json({ rate_limit: { primary_window: { - used_percent: 10, + used_percent: usedPercent, limit_window_seconds: 18_000, reset_at: resetAt, }, @@ -305,9 +305,11 @@ function poolFiles(): string[] { } describe('Pi in vault mode', () => { - test('host without a relay fails closed, hides enrollment actions and clears the placeholder when hosting ends', async () => { + test('host without a relay fails closed and leaves the native login untouched', async () => { await addExpiredLocalRow() writeNativeLogin() + const authPath = join(dir, 'auth.json') + const authBefore = readFileSync(authPath, 'utf8') const before = poolFiles() process.env.CORTEXKIT_VAULT_HOST = 'thalamus' const target = vault() @@ -315,16 +317,17 @@ describe('Pi in vault mode', () => { try { await runtime.syncVaultSlot() expect(await runtime.readAuthority()).toBe('host') - expect( - JSON.parse(readFileSync(join(dir, 'auth.json'), 'utf8'))[ - 'openai-codex' - ], - ).toEqual({ type: 'api_key', key: VAULT_PLACEHOLDER_KEY }) + expect(readFileSync(authPath, 'utf8')).toBe(authBefore) await runtime.commandSupport().observeLogin(NATIVE_ACCESS) await runtime.commandSupport().refreshAllQuota() - expect(errorOf(await send(runtime))).toBe( - VAULT_MODE_REFUSALS['vault-unreachable'], - ) + const result = await runtime + .stream(MODEL, CONTEXT, { + apiKey: NATIVE_ACCESS, + transport: 'sse', + fetch: fakeFetch, + }) + .result() + expect(result.errorMessage).toBe(VAULT_MODE_REFUSALS['vault-unreachable']) expect(codexTokens).toEqual([]) expect(whamTokens).toEqual([]) expect(refreshes).toBe(0) @@ -340,11 +343,7 @@ describe('Pi in vault mode', () => { ) delete process.env.CORTEXKIT_VAULT_HOST await runtime.syncVaultSlot() - expect( - JSON.parse(readFileSync(join(dir, 'auth.json'), 'utf8'))[ - 'openai-codex' - ], - ).toBeUndefined() + expect(readFileSync(authPath, 'utf8')).toBe(authBefore) } finally { await target.dispose() } @@ -396,6 +395,104 @@ describe('Pi in vault mode', () => { }) } + test('vault quota minimum skips a below-floor route and reports a quota block when none qualify', async () => { + daemon = await startMockDaemon({ + directory: dir, + credentials: { + 'chatgpt:openai': vaultLogin('chatgpt-low'), + 'chatgpt:openai:work': vaultLogin('chatgpt-high'), + }, + }) + enroll() + const target = vault({ + fetchImpl: () => + (async (_input, init) => + whamOk( + new Headers(init?.headers).get('authorization') === + `Bearer ${chatgptAccessToken('chatgpt-low')}` + ? 75 + : 25, + )) as typeof fetch, + }) + const runtime = runtimeWith(target) + const setMinimum = (primary: number) => + mutateAccounts((current) => { + current.quota = { enabled: true, minimumRemaining: { primary } } + return current + }, paths) + try { + await setMinimum(50) + await target.refresh() + await target.pollStale(0) + expect(errorOf(await send(runtime))).toBeUndefined() + expect(codexTokens).toEqual([chatgptAccessToken('chatgpt-high')]) + + await setMinimum(90) + expect(errorOf(await send(runtime))).toBe( + 'No OpenAI account meets the configured minimum remaining quota.', + ) + expect(codexTokens).toEqual([chatgptAccessToken('chatgpt-high')]) + } finally { + await target.dispose() + } + }) + + test('an unread vault route still gets its first reading with a configured quota minimum', async () => { + daemon = await startMockDaemon({ + directory: dir, + credentials: { 'chatgpt:openai': vaultLogin('chatgpt-vault') }, + }) + enroll() + await mutateAccounts((current) => { + current.quota = { + enabled: true, + failClosedOnUnknownQuota: true, + minimumRemaining: { primary: 50 }, + } + return current + }, paths) + const target = vault() + const runtime = runtimeWith(target) + try { + await target.refresh() + expect(target.routes()[0]?.quota).toBeUndefined() + expect(errorOf(await send(runtime))).toBeUndefined() + expect(whamTokens).toEqual([VAULT_ACCESS]) + expect(codexTokens).toEqual([VAULT_ACCESS]) + } finally { + await target.dispose() + } + }) + + test('vault sticky-to-ordered fallback uses roster order instead of preferring vault main', async () => { + daemon = await startMockDaemon({ + directory: dir, + credentials: { + 'chatgpt:openai': vaultLogin('chatgpt-default'), + 'chatgpt:openai:work': vaultLogin('chatgpt-work'), + }, + }) + enroll() + await setMode('sticky-balanced') + const target = vault() + const runtime = runtimeWith(target) + try { + await target.refresh() + await target.pollStale(0) + const routes = target.routes.bind(target) + spyOn(target, 'routes').mockImplementation(() => routes().reverse()) + expect(target.routes().map((route) => route.credentialId)).toEqual([ + 'chatgpt:openai:work', + 'chatgpt:openai', + ]) + // Without a session id Pi cannot place a pin and must use ordered routing. + expect(errorOf(await send(runtime))).toBeUndefined() + expect(codexTokens).toEqual([chatgptAccessToken('chatgpt-work')]) + } finally { + await target.dispose() + } + }) + test('alias-only vault placements keep Ordered order and never serve the local main', async () => { daemon = await startMockDaemon({ directory: dir, @@ -1019,20 +1116,42 @@ describe("Pi's real model runtime in vault mode", () => { describe('Pi vault slot lifecycle', () => { test('connect then disconnect discards the original Pi sign-in and explains it is not restored', async () => { writeNativeLogin() - enroll() + const connected = Promise.withResolvers() + daemon = await startMockDaemon({ + directory: dir, + credentials: { 'oauth:openai:vault': vaultLogin('chatgpt-vault') }, + }) const target = vault() const runtime = runtimeWith(target) const authPath = join(dir, 'auth.json') const stashPath = join(stateDir, 'pi-openai-codex-login.json') try { - const view = await createPiMenu(runtime.commandSupport()).open({ + const menu = createPiMenu(runtime.commandSupport(), { + afterApply: () => runtime.syncVaultSlot(undefined, true), + vaultWait: { + pollIntervalMs: 1, + sleep: async () => daemon?.approve('request-1'), + }, + }) + const connect = await menu.apply( + { command: 'openai', sectionId: 'vault', actionId: 'connect' }, + { notify: (message) => connected.resolve(message) }, + ) + expect(connect.ok).toBe(true) + expect(await connected.promise).toContain('Connected: the vault approved') + expect( + JSON.parse(readFileSync(authPath, 'utf8'))['openai-codex'], + ).toEqual({ + type: 'api_key', + key: VAULT_PLACEHOLDER_KEY, + }) + const view = await menu.open({ notify() {}, }) const disconnect = view.menu.sections .find((section) => section.id === 'vault') ?.actions.find((action) => action.id === 'disconnect') expect(disconnect?.confirm?.message).toContain('is not restored') - await runtime.syncVaultSlot() const keptCopyWhileConnected = existsSync(stashPath) const result = await createPiMenu(runtime.commandSupport()).apply( { diff --git a/packages/pi/src/vault-slot.ts b/packages/pi/src/vault-slot.ts index eb0834f1..72e13bbf 100644 --- a/packages/pi/src/vault-slot.ts +++ b/packages/pi/src/vault-slot.ts @@ -1,17 +1,43 @@ import { join } from 'node:path' import { openPiSlot, type PiSlot } from '@cortexkit/common-auth/pi-slot' import { vaultStateDir } from '@cortexkit/openai-auth-core/internal' -import { getAgentDir } from '@earendil-works/pi-coding-agent' +import { getAgentDir, VERSION } from '@earendil-works/pi-coding-agent' /** - * Pi reads this non-secret API-key placeholder from auth.json while the vault - * serves. Unlike an OAuth entry, it needs no refresh; it is never sent upstream. + * Pi uses this non-secret API-key placeholder while the vault serves. + * Unlike an OAuth entry, it needs no refresh; it is never sent upstream. */ export const VAULT_PLACEHOLDER_KEY = 'openai-auth-vault-mode-not-a-credential' export const VAULT_SLOT_REFUSAL = 'Request refused locally: Pi has not loaded the credential vault placeholder. Reopen the session or disconnect Pi from the vault in /openai; local credentials are not used while connected.' +let warnedMissingBridge = false + +export async function installHostedVaultKey( + registry: object, + log: { warn(message: string): unknown }, +): Promise { + // Pi resolves stored OAuth before the configured provider key. Use its + // in-memory credential override so it does not refresh the saved login. + const runtime = 'runtime' in registry ? registry.runtime : undefined + if ( + runtime && + typeof runtime === 'object' && + 'setRuntimeApiKey' in runtime && + typeof runtime.setRuntimeApiKey === 'function' + ) { + await runtime.setRuntimeApiKey('openai-codex', VAULT_PLACEHOLDER_KEY) + return + } + if (!warnedMissingBridge) { + warnedMissingBridge = true + log.warn( + `Pi ${VERSION} does not expose the in-memory credential override. Hosted OpenAI Codex requests with an expired native login may not reach the vault.`, + ) + } +} + export function openVaultSlot(statePath: string): PiSlot { return openPiSlot({ authPath: join(getAgentDir(), 'auth.json'),