From e24397ccb7931f81bc94a35d4c6e89c4147ca4f4 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:30:46 +0100 Subject: [PATCH 1/9] mason: explain OpenCode 2 vault quota minimum refusals Use the shared quota-minimum message when a vault route would pass with the minimum set to zero. Keep other vault and admission refusals unchanged. Exercise the prior empty-roster expectation with a quota minimum configured to prove the new guidance does not mask a genuinely empty vault. --- .../src/tests/opencode2-vault.test.ts | 101 ++++++++++++++++-- packages/opencode/src/v2/adapter.ts | 76 ++++++++----- 2 files changed, 145 insertions(+), 32 deletions(-) diff --git a/packages/opencode/src/tests/opencode2-vault.test.ts b/packages/opencode/src/tests/opencode2-vault.test.ts index 972e011b..20974423 100644 --- a/packages/opencode/src/tests/opencode2-vault.test.ts +++ b/packages/opencode/src/tests/opencode2-vault.test.ts @@ -23,6 +23,7 @@ import { placeholderSecret, } from '@cortexkit/common-auth/opencode2' import { + OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE, OpenAiVault, VAULT_MODE_REFUSALS, type VaultModeRefusal, @@ -64,6 +65,7 @@ import { restoreEnv } from './setup-env' const PLACEHOLDER = placeholderSecret('openai') const VAULT_ACCESS = chatgptAccessToken('chatgpt-vault') +const WORK_ACCESS = chatgptAccessToken('chatgpt-work') const ENROLLMENT_TOKEN = '01'.repeat(32) const cleanups: Array<() => Promise | void> = [] @@ -85,6 +87,23 @@ const usageOnly = (async (input: unknown) => { return new Response(usageBody(10), { status: 200 }) }) as unknown as typeof fetch +function setVaultQuotaMinimum(files: PoolFiles, killswitchFloor?: number) { + writeFileSync( + files.configPath, + JSON.stringify({ + ...files.readConfig(), + quota: { minimumRemaining: { primary: 95 } }, + ...(killswitchFloor !== undefined && { + killswitch: { + enabled: true, + schema: 'floors-v1', + defaults: { primary: killswitchFloor, secondary: 0 }, + }, + }), + }), + ) +} + async function waitFor(check: () => boolean, what: string) { const deadline = Date.now() + 5_000 while (!check()) { @@ -211,6 +230,27 @@ async function start( return { host, daemon, files, tokenPath, relay } } +function startWithMixedVaultQuota() { + return start( + 'main-first', + [{ id: 'main' }], + { + 'chatgpt:openai': vaultLogin('chatgpt-vault'), + 'chatgpt:openai:work': vaultLogin('chatgpt-work'), + }, + { + prepare: setVaultQuotaMinimum, + fetch: (async (input: unknown, init?: RequestInit) => { + if (!String(input).includes('/wham/usage')) + throw new Error('offline in tests') + const bearer = new Headers(init?.headers).get('authorization') + const usedPercent = bearer === `Bearer ${WORK_ACCESS}` ? 1 : 10 + return new Response(usageBody(usedPercent), { status: 200 }) + }) as unknown as typeof fetch, + }, + ) +} + type Host = Awaited>['host'] it('vault activation is registered and returns only the host placeholder without a pool write', async () => { @@ -241,8 +281,8 @@ it('vault activation is registered and returns only the host placeholder without ).toEqual(before) }) -/** Asserts the host's request is refused locally in vault mode for `cause`. */ -async function expectVaultRefusal(host: Host, cause: VaultModeRefusal) { +/** Asserts the host's request is refused locally without a credential. */ +async function expectLocalRefusal(host: Host, expectedMessage: string) { const draftScope = scope('ses_1', 'primary') const headers = { authorization: `Bearer ${PLACEHOLDER}`, @@ -263,15 +303,21 @@ async function expectVaultRefusal(host: Host, cause: VaultModeRefusal) { (reason: unknown) => reason, ) expect(error).toBeInstanceOf(OpenCode2AuthError) - expect((error as OpenCode2AuthError).message).toBe( - vaultModeRefusalText(cause, 'openai-auth-opencode'), - ) + expect((error as OpenCode2AuthError).kind).toBe('no-account') + expect((error as OpenCode2AuthError).message).toBe(expectedMessage) // Nothing was given a credential to go out with. expect(draft.request.headers.get('authorization')).toBe( `Bearer ${PLACEHOLDER}`, ) } +function expectVaultRefusal(host: Host, cause: VaultModeRefusal) { + return expectLocalRefusal( + host, + vaultModeRefusalText(cause, 'openai-auth-opencode'), + ) +} + /** * The receipts the vault authorized from here on, in order: the record * version each was served at and whether it was the token kept from an @@ -798,8 +844,49 @@ describe('vault accounts on OpenCode 2', () => { expect(readFileSync(files.statePath, 'utf8')).toBe(state) }) - it('refuses locally when the vault serves no account', async () => { - const { host } = await start('main-first', [{ id: 'main' }], {}) + it('refuses with the quota minimum message when every vault account is below the minimum', async () => { + const { host } = await start( + 'main-first', + [{ id: 'main' }], + { 'chatgpt:openai': vaultLogin('chatgpt-vault') }, + { prepare: setVaultQuotaMinimum }, + ) + await expectLocalRefusal(host, OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE) + }) + + it('serves a vault account above the quota minimum instead of the default below it', async () => { + const { host } = await startWithMixedVaultQuota() + expect((await send(host, 200)).get('authorization')).toBe( + `Bearer ${WORK_ACCESS}`, + ) + }) + + it('keeps the vault refusal when it declines the only account above the quota minimum', async () => { + const { host, daemon } = await startWithMixedVaultQuota() + const credential = daemon.credentials['chatgpt:openai:work'] + if (credential) credential.refuse = 'credential_unavailable' + await expectVaultRefusal(host, 'vault-refused') + }) + + it('does not blame the quota minimum when the vault account also fails the killswitch floor', async () => { + const { host } = await start( + 'main-first', + [{ id: 'main' }], + { 'chatgpt:openai': vaultLogin('chatgpt-vault') }, + { prepare: (files) => setVaultQuotaMinimum(files, 95) }, + ) + await expectVaultRefusal(host, 'vault-empty') + }) + + it('keeps the vault-empty refusal for an empty roster with a quota minimum', async () => { + const { host } = await start( + 'main-first', + [{ id: 'main' }], + {}, + { + prepare: setVaultQuotaMinimum, + }, + ) await expectVaultRefusal(host, 'vault-empty') }) diff --git a/packages/opencode/src/v2/adapter.ts b/packages/opencode/src/v2/adapter.ts index 238ef997..1b6c4286 100644 --- a/packages/opencode/src/v2/adapter.ts +++ b/packages/opencode/src/v2/adapter.ts @@ -89,10 +89,12 @@ import { hasVaultRoutingAccessor, isCompleteQuotaHeaderFrame, isKillswitchEnabled, + killswitchPassesPolicy, type LimitsProbe, logInputTransformations, normalizeQuotaHeaders, normalizeWsFrame, + OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE, type OpenAiLimitsOwner, type OpenAiLimitsRequest, type OpenAiVault, @@ -115,7 +117,6 @@ import { VAULT_ROUTING_REFUSAL_MESSAGE, VaultBillingAttempt, type VaultBillingWarming, - type VaultModeRefusal, type VaultRoutingFeedback, type VaultRoutingResponse, vaultModeNoRouteCause, @@ -855,7 +856,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { storage: AccountStorage | null, at: number, vaultMode: boolean, - ): Target[] => { + ): { targets: Target[]; quotaMinimumBlocked: boolean } => { const rows = vaultMode ? [] : routableRows( @@ -865,16 +866,32 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { vault?.identities() ?? new Set(), deps.configPath, ) - const routes = (vault?.routes() ?? []).filter( - (route) => - route.kind === 'oauth' && - quotaSnapshotPassesPolicy( - windowsFromQuotaMap(route.quota), - storage, - at, - ), + const vaultRoutes = (vault?.routes() ?? []).filter( + (route) => route.kind === 'oauth', ) - return [ + const routes = vaultRoutes.filter((route) => + quotaSnapshotPassesPolicy(windowsFromQuotaMap(route.quota), storage, at), + ) + let quotaMinimumBlocked = false + if (vaultMode && storage && routes.length === 0 && vaultRoutes.length > 0) { + // Don't blame the minimum if unknown quota or the per-account + // killswitch floor would still keep the route out. + const withoutMinimum = { + ...storage, + quota: { + ...storage.quota, + minimumRemaining: { primary: 0, secondary: 0 }, + }, + } + quotaMinimumBlocked = vaultRoutes.some((route) => { + const reading = windowsFromQuotaMap(route.quota) + return ( + quotaSnapshotPassesPolicy(reading, withoutMinimum, at) && + killswitchPassesPolicy(reading, storage, route.id, at) + ) + }) + } + const targets = [ ...rows.map( (row): Target => ({ id: row.id, @@ -891,6 +908,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { }), ), ] + return { targets, quotaMinimumBlocked } } const routingInput = ( @@ -1113,11 +1131,12 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { await source.prepareTokens(source.peek().rows, storage) } let at = now() - let targets = currentTargets(storage, at, vaultMode) + let selection = currentTargets(storage, at, vaultMode) const checkpoint = input.wake?.checkpoint if (checkpoint && clearedRoutingHolds.has(checkpoint)) throw vaultRefusal() const wake = checkpoint && routingWakes.get(checkpoint) if (wake && checkpoint) { + const { targets } = selection routingWakes.delete(checkpoint) routingWakeEnds.get(checkpoint)?.('resumed') const accountId = checkpoint.accountKey.accountId @@ -1247,7 +1266,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { deadline?.signal.throwIfAborted() if (capacityWaited) { at = now() - targets = currentTargets(storage, at, vaultMode) + selection = currentTargets(storage, at, vaultMode) if (typeof answer === 'string') { // A route offered before a capacity wait may no longer be eligible. const offered = eligible.find((route) => route.id === answer) @@ -1296,7 +1315,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { throw error } at = now() - targets = currentTargets(storage, at, vaultMode) + selection = currentTargets(storage, at, vaultMode) continue } } @@ -1315,7 +1334,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { ? undefined : waitForFirstQuotaReading( routingInput( - targets.filter( + selection.targets.filter( (target) => target.id !== input.rerouteFrom?.accountId, ), storage, @@ -1331,11 +1350,11 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { ) await firstReading at = now() - targets = currentTargets(storage, at, vaultMode) + selection = currentTargets(storage, at, vaultMode) if (end) end( planOrdered({ - ...routingInput(targets, storage, at), + ...routingInput(selection.targets, storage, at), // Reporting admission must not trigger another quota poll. requestPull: () => {}, placement: 'roster', @@ -1345,6 +1364,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { : 'resumed', ) } + const { targets, quotaMinimumBlocked } = selection const byId = new Map(targets.map((target) => [target.id, target])) let routing = routingInput(targets, storage, at) const admissionTiers = hasVaultRoutingAccessor() @@ -2000,10 +2020,9 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { (await deps.slotPlaceholderWithoutMain?.()) ) refuseMissingLogin() - // Vault mode never falls back to a local account. When no vault account - // could be tried, or the vault refused every one it was asked for, the - // request is refused here with a fixed text naming the cause and the - // remedy. An admission refusal (quota) keeps the installer's own. + // Vault mode never falls back to a local account. If no target could be + // tried, explain why here; a vault authorization refusal takes priority. + // A surviving target blocked later by admission keeps the host's error. if ( accountId === undefined && vaultMode && @@ -2011,8 +2030,12 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { !resetWake && (targets.length === 0 || refused.size > 0) ) { - const cause: VaultModeRefusal = - refused.size > 0 ? 'vault-refused' : vaultModeNoRouteCause(vault) + const cause = + refused.size > 0 + ? 'vault-refused' + : quotaMinimumBlocked + ? 'quota-minimum' + : vaultModeNoRouteCause(vault) log?.warn( 'vault mode: no vault account can serve; refusing the request', { @@ -2024,7 +2047,10 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { providerID: OPENAI_PROVIDER_ID, sessionID: input.sessionID, requestKind: input.kind, - message: vaultModeRefusalText(cause, vault.name), + message: + cause === 'quota-minimum' + ? OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE + : vaultModeRefusalText(cause, vault.name), }) } if (accountId !== undefined) { @@ -2313,7 +2339,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { ) if (!vaultMode && !(await source.current()).active) return undefined const at = now() - const targets = currentTargets(storage, at, vaultMode) + const { targets } = currentTargets(storage, at, vaultMode) const target = targets.find( (candidate) => candidate.id === input.accountId, ) From 3479dfd30576840c873d2070fd79d63730c735e3 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:32:32 +0100 Subject: [PATCH 2/9] docs(opencode2): define the killswitch floor and the later admission check in two comments --- packages/opencode/src/v2/adapter.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/v2/adapter.ts b/packages/opencode/src/v2/adapter.ts index 1b6c4286..406e84d9 100644 --- a/packages/opencode/src/v2/adapter.ts +++ b/packages/opencode/src/v2/adapter.ts @@ -874,8 +874,9 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { ) let quotaMinimumBlocked = false if (vaultMode && storage && routes.length === 0 && vaultRoutes.length > 0) { - // Don't blame the minimum if unknown quota or the per-account - // killswitch floor would still keep the route out. + // Don't blame the minimum if unknown quota or the killswitch floor (the + // remaining quota an account must keep, per account or by default) + // would still keep the route out. const withoutMinimum = { ...storage, quota: { @@ -2022,7 +2023,8 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { refuseMissingLogin() // Vault mode never falls back to a local account. If no target could be // tried, explain why here; a vault authorization refusal takes priority. - // A surviving target blocked later by admission keeps the host's error. + // A target that is still available here but refused by the later quota + // admission check keeps the host's error. if ( accountId === undefined && vaultMode && From 9cb942c4f7e3fbcce7169ee60c70640772a78e56 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:37:53 +0100 Subject: [PATCH 3/9] mason: route Pi stream limits like HTTP refusals Act only on terminal pi-ai outcomes, so provisional limits from retried sends cannot move a session or report exhaustion. Preserve explicit reset evidence on streamed usage failures so holds match HTTP 429; split the prior failed-event reset assertion into an actual resetless case and a literal reset-precedence witness. --- docs/limit-policy-conformance.md | 10 +- packages/core/src/limit-policy.ts | 2 +- packages/core/src/tests/limit-policy.test.ts | 26 +- packages/pi/src/codex-websocket.ts | 2 + packages/pi/src/pool-request.ts | 14 +- packages/pi/src/runtime.ts | 220 +++++++----- packages/pi/src/tests/quota-wait.test.ts | 336 ++++++++++++++++++- packages/pi/src/tests/vault.test.ts | 197 ++++++++++- 8 files changed, 693 insertions(+), 114 deletions(-) diff --git a/docs/limit-policy-conformance.md b/docs/limit-policy-conformance.md index 0c25466c..02ed9660 100644 --- a/docs/limit-policy-conformance.md +++ b/docs/limit-policy-conformance.md @@ -106,7 +106,7 @@ The adoption column includes the deliberate changes to OA-23/32/36/38/49/50/57/5 | 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` | | OA-30 | B | Unreplayable request gets at most one main attempt or blocks; no failover/hold replay. | [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `unreplayable requests never hold or send a fallback` | N/A — installer owns replay eligibility, not OC1 body flag. 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 model/context attempts have no OC1 body replay flag. Owning boundary: [`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-31 | R | OC1 sticky unknown/unconfirmed 429 keeps pin and original failure, with no normalized retry duration. | [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `unconfirmed 429 preserves pin and original bytes without a normalized retry duration` | N/A — OC2 does not use OC1 sticky pass-through. 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` | N/A — Pi publishes SDK events rather than OC1 provider bytes. Owning boundary: [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `sticky unknown 429 retains without a timer and raw percentages are not rounded`; [`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` | -| OA-32 | D | Confirmed exhaustion migrates without fitting hold facts; separate eligible same-account cache companion holds rather than moving to B. | [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | N/A — OC2 owns a separate hold overlay. 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` | N/A — Pi owns a separate event/wait overlay. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache` | +| OA-32 | D | Confirmed exhaustion moves the session when a hold cannot fit. A separate vector holds on A when every blocker resets before the session cache and wait budget expire. | [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | N/A — OC2 owns a separate hold overlay. 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` | N/A — Pi owns a separate event/wait overlay. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-58 HTTP 429 confirmed usage limit moves the sticky session without a fitting cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-58 HTTP 429 confirmed usage limit holds for a fitting cache` | | OA-33 | R | Sticky permanent 401/403 migrates without exhaustion mark or hold, even with fitting cache, confirmed reading, or usage-limit body. | [`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/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `auth 403 beats fitting cache, exhausted reading and usage-limit body` | N/A — OC2 host retry handles auth rather than OC1 sticky reducer. Owning boundary: [`packages/opencode/src/tests/opencode2-retry-choice.test.ts`](../packages/opencode/src/tests/opencode2-retry-choice.test.ts) → `undefined after token refusals leaves pins pending bytes and active accounts untouched` | [`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`; [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `sticky-balanced 403 parsed usage body never builds hold facts` | | OA-34 | B | Quota-pending detour may serve B without moving A's pin. | [`packages/opencode/src/tests/pool-request.test.ts`](../packages/opencode/src/tests/pool-request.test.ts) → `sticky-balanced: a pinned row awaiting a reading serves elsewhere and keeps the pin` | N/A — OC2 uses tentative choices, not OC1 detours. Owning boundary: [`packages/opencode/src/tests/opencode2-retry-choice.test.ts`](../packages/opencode/src/tests/opencode2-retry-choice.test.ts) → `undefined after token refusals leaves pins pending bytes and active accounts untouched` | [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `the original request serves after a pending first reading without a second request` | | OA-35 | B | Startup poll joins at most 5 seconds then rereads admission; it is not a limit hold. | [`packages/opencode/src/tests/pool-request.test.ts`](../packages/opencode/src/tests/pool-request.test.ts) → `main-first: the original request serves after its in-flight first reading, without a host retry` | [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `the original request joins a pending first vault quota poll and serves without a retry` | [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `the original request serves after a pending first reading without a second request` | @@ -129,12 +129,12 @@ The adoption column includes the deliberate changes to OA-23/32/36/38/49/50/57/5 | OA-52 | B | Fresh OC2 all-marked escape removes temporary exclusions only, never marks/floors/custody; no request-phase sleep. | N/A — OC2 installer attribution/choice is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | [`packages/opencode/src/tests/opencode2-rate-limits.test.ts`](../packages/opencode/src/tests/opencode2-rate-limits.test.ts) → `a fresh request is still sent once both accounts are marked`; [`packages/opencode/src/tests/opencode2-rate-limits.test.ts`](../packages/opencode/src/tests/opencode2-rate-limits.test.ts) → `pool http: live-mark escape never clears, expired clean probe clears only once` | N/A — OC2 installer attribution/choice is not used by Pi. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache` | | OA-53 | R | Latest-foreign/mixed attribution leaves host retry before output veto; no plugin quota hold/reroute. | N/A — OC2 installer attribution/choice is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | [`packages/opencode/src/tests/opencode2-active-connection.test.ts`](../packages/opencode/src/tests/opencode2-active-connection.test.ts) → `redacts owned HTTP WebSocket and retry errors without touching foreign connections` | N/A — OC2 installer attribution/choice is not used by Pi. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache` | | OA-54 | R | Owned attributable nonmixed output-started forces retry false; mark may still publish. | N/A — OC2 installer attribution/choice is not used by OC1. Owning boundary: [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `does NOT force a retry when output already streamed before a rate-limit failure (no duplicate replay)` | [`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 — OC2 installer attribution/choice is not used by Pi. Owning boundary: [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-60 published text delta drains its late quota error without rerouting or waiting` | -| OA-55 | R | Preserve OC2 failed-event reason allow-list and quota/lifecycle/output facts; usage_limit_reached confirms without reset, rate_limit_exceeded never confirms; no OC1 synthetic rule. | N/A — OC2 installer attribution/choice is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | [`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 — OC2 installer attribution/choice is not used by Pi. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache` | +| OA-55 | R | Preserve OC2 failed-event reason allow-list and quota/lifecycle/output facts; usage_limit_reached confirms without reset, rate_limit_exceeded never confirms; no OC1 synthetic rule. | N/A — OC2 installer attribution/choice is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | [`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 — OC2 installer attribution/choice is not used by Pi. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-55 SSE code-only usage_limit_reached confirms without status or reset`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-55 SSE type-only rate_limit_exceeded at 429 is not exhaustion`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-55 SSE code takes precedence over a usage-limit type`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-55 SSE an explicit 403 is not replaced with 429` | | OA-56 | R | Retry undefined/throw leaves host and commits no choice; real fresh custody/admission refusal stays distinct; new veto uses typed channel. | N/A — OC2 installer attribution/choice is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | [`packages/opencode/src/tests/opencode2-retry-choice.test.ts`](../packages/opencode/src/tests/opencode2-retry-choice.test.ts) → `undefined after token refusals leaves pins pending bytes and active accounts untouched`; [`packages/opencode/src/tests/opencode2-limit-policy.test.ts`](../packages/opencode/src/tests/opencode2-limit-policy.test.ts) → `one cache hold consumes one host retry and cannot chain` | N/A — OC2 installer attribution/choice is not used by Pi. Owning boundary: [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache` | -| OA-57 | R+D | Pi ordered uses captured status before output. Hold lifecycle events and empty blocks; discard them if the attempt is replaced. Setup throw supplies no status. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | N/A — Pi buffered-head/countdown executor is not used by OC2. 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`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 ordered 429 after only empty events moves without publishing them`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 fitting-cache companion holds after only empty events without publishing them` | -| OA-58 | D | Pi confirmed exhaustion migrates if hold cannot fit; eligible cache/confirmed reset waits on A with spinner/Escape before publication. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | N/A — Pi buffered-head/countdown executor is not used by OC2. 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-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache` | +| OA-57 | R+D | Pi uses an HTTP status or classified streamed limit before output and acts only on the routing attempt’s terminal result. Hold lifecycle events and empty blocks; discard them if the attempt is replaced. A setup throw or an unclassified upgrade failure supplies no status. | N/A — OC1 does not use Pi's SDK event buffering and countdown waits. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | N/A — Pi buffered-head/countdown executor is not used by OC2. 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`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 ordered 429 after only empty events moves without publishing them`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-57 fitting-cache companion holds after only empty events without publishing them`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-57 rejected WebSocket upgrade and unclassified fallback failure do not guess a status`; [`packages/pi/src/tests/vault.test.ts`](../packages/pi/src/tests/vault.test.ts) → `OA-57 a successful pi-ai HTTP retry does not report or act on the first limit` | +| OA-58 | D | Pi confirmed exhaustion migrates if a hold cannot fit; an eligible cache and confirmed reset wait on A with spinner/Escape before publication. HTTP 429, SSE and WebSocket limits take the same route. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | N/A — Pi buffered-head/countdown executor is not used by OC2. 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-58 original confirmed refusal without cache migrates without waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 fitting-cache companion waits for every blocker then retries A before publication`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-58 four-day blocker companion cannot wait despite fitting primary and cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-58 HTTP 429 confirmed usage limit moves the sticky session without a fitting cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-58 HTTP 429 confirmed usage limit holds for a fitting cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-58 SSE confirmed usage limit moves the sticky session without a fitting cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-58 SSE confirmed usage limit holds for a fitting cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-58 WebSocket confirmed usage limit moves the sticky session without a fitting cache`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-58 WebSocket confirmed usage limit holds for a fitting cache` | | OA-59 | R | Pi sticky unknown 429 stays untimed retain/original event; permanent 401/403 may migrate but never waits; no manufactured countdown. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 original confirmed reset without cache still migrates`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 fitting-cache companion holds only when every blocker fits`; [`packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts`](../packages/opencode/src/tests/limit-policy-oc1-conformance.test.ts) → `OA-32 four-day secondary companion cannot hold despite a fitting primary and cache` | N/A — Pi buffered-head/countdown executor is not used by OC2. 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/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `sticky unknown 429 retains without a timer and raw percentages are not rounded`; [`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` | -| OA-60 | B | After Pi publishes the first non-empty text or reasoning event, or any tool-call event, drain/end only; never re-enter routing. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `does NOT force a retry when output already streamed before a rate-limit failure (no duplicate replay)` | N/A — Pi buffered-head/countdown executor is not used by OC2. 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` | [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-60 published text delta drains its late quota error without rerouting or waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-60 a text delta takes precedence over a captured 429`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-60 toolcall_start takes precedence over a captured 429` | +| OA-60 | B | After Pi publishes the first non-empty text or reasoning event, or any tool-call event, drain/end only; never re-enter routing. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/ws-pool.test.ts`](../packages/opencode/src/tests/ws-pool.test.ts) → `does NOT force a retry when output already streamed before a rate-limit failure (no duplicate replay)` | N/A — Pi buffered-head/countdown executor is not used by OC2. 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` | [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-60 published text delta drains its late quota error without rerouting or waiting`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-60 a text delta takes precedence over a captured 429`; [`packages/pi/src/tests/limit-policy-conformance.test.ts`](../packages/pi/src/tests/limit-policy-conformance.test.ts) → `OA-60 toolcall_start takes precedence over a captured 429`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-60 WebSocket usage limit after published text does not reroute or hold` | | OA-61 | D | Preserve auth causes; quota gains known-reset bounded terminal wait and safe final text; unknown reset never advertises scheduled wait. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `fresh provider mark uses the pinned 90-second retry and rounded reset text`; [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `unproven live mark uses pinned OA-36 wire at 15` | N/A — Pi buffered-head/countdown executor is not used by OC2. Owning boundary: [`packages/opencode/src/tests/opencode2-limit-policy.test.ts`](../packages/opencode/src/tests/opencode2-limit-policy.test.ts) → `case 16 scans B without holding A for its reset` | [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-61 known 60s terminal wait revalidates then sends once with current credentials`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-61 two-hour reset waits only 15 minutes then gives the exact final text`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `unknown terminal reset never starts a countdown even with UI` | | OA-62 | B | Pi first-reading startup join/reread and incomplete error remain separate from quota wait. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/pool-request.test.ts`](../packages/opencode/src/tests/pool-request.test.ts) → `main-first: the original request serves after its in-flight first reading, without a host retry` | N/A — Pi buffered-head/countdown executor is not used by OC2. Owning boundary: [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `the original request joins a pending first vault quota poll and serves without a retry` | [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `the original request serves after a pending first reading without a second request` | | OA-63 | R | Unreachable vault without usable receipt keeps bounded startup/incomplete/custody refusal, never local fallback. | [`packages/opencode/src/tests/vault.test.ts`](../packages/opencode/src/tests/vault.test.ts) → `a vault daemon that never answers holds neither the loader nor, past a bounded wait, a request, which is refused with nothing sent or refreshed` | [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `a vault daemon that never answers holds neither setup nor, past a bounded wait, a request, which is refused locally` | [`packages/pi/src/tests/vault-mode.test.ts`](../packages/pi/src/tests/vault-mode.test.ts) → `a vault that cannot be reached refuses the request locally after a bounded wait: nothing is sent, refreshed or polled` | diff --git a/packages/core/src/limit-policy.ts b/packages/core/src/limit-policy.ts index 20a0d490..78fa5341 100644 --- a/packages/core/src/limit-policy.ts +++ b/packages/core/src/limit-policy.ts @@ -192,7 +192,7 @@ export function classifyOpenAiLimitBody(input: { ? openAiSignalWindows( { window: reason ?? 'rate_limit', - resetAt: failed ? undefined : resetAt, + resetAt, }, input.now, input.reading, diff --git a/packages/core/src/tests/limit-policy.test.ts b/packages/core/src/tests/limit-policy.test.ts index 61805253..34e32f29 100644 --- a/packages/core/src/tests/limit-policy.test.ts +++ b/packages/core/src/tests/limit-policy.test.ts @@ -168,7 +168,7 @@ describe('evidence-table confirmation', () => { body: { type: 'response.failed', response: { - error: { [field]: reason, resets_at: (now + 60000) / 1000 }, + error: { [field]: reason }, }, }, now, @@ -182,6 +182,30 @@ describe('evidence-table confirmation', () => { } }, ) + test('failed-event usage reset uses the same absolute-before-relative rule as HTTP 429', () => { + const signal = classifyOpenAiLimitBody({ + account: a, + body: { + type: 'response.failed', + status: 429, + response: { + error: { + code: 'usage_limit_reached', + resets_at: 1800000060, + resets_in_seconds: 90, + }, + }, + }, + now, + }) + expect(signal?.windows[0]).toMatchObject({ + window: 'usage', + confirmed: true, + resetAt: 1800000060000, + provenance: 'provider', + }) + expect(signal?.status).toBe(429) + }) test('cloned raw body uses positive absolute before relative reset, not Retry-After', () => { const signal = classifyOpenAiLimitBody({ account: a, diff --git a/packages/pi/src/codex-websocket.ts b/packages/pi/src/codex-websocket.ts index d840dd1f..f12e4e1d 100644 --- a/packages/pi/src/codex-websocket.ts +++ b/packages/pi/src/codex-websocket.ts @@ -13,6 +13,7 @@ type WebSocketAttempt = { token: string owner: object sessionId?: string | undefined + onSend(): void onMessage(data: string): void } @@ -124,6 +125,7 @@ class PiRawCodexWebSocket extends RawWebSocket { if (!this.activeAttempt && this.cacheKey && this.readyState === 1) cachedSockets.set(this.cacheKey, this) this.activeAttempt = attempt + attempt.onSend() super.send(shapePiCodexWebSocketFrame(data)) } } diff --git a/packages/pi/src/pool-request.ts b/packages/pi/src/pool-request.ts index 576dce30..a7a72d17 100644 --- a/packages/pi/src/pool-request.ts +++ b/packages/pi/src/pool-request.ts @@ -104,7 +104,7 @@ function sendable(account: RouteAccount | undefined): account is RouteAccount { return account !== undefined && (account.vault === true || !!account.token) } -/** What one attempt reports back: the HTTP status, when a response arrived. */ +/** What one attempt reports back: an HTTP response or a classified stream limit. */ export interface RouteAttempt { status?: number /** Captured before dispatch, so a replacement cannot inherit old evidence. */ @@ -838,9 +838,17 @@ async function routeSticky( ) const execution = policyResult(ctx, decision, attempt.signal) if (execution) return execution - if (after.action === 'migrate') { + // A confirmed refusal can arrive without a quota reading that moves the pin. + const confirmedMove = + attempt.status === 429 && + attempt.signal?.kind === 'quota-exhausted' && + decision?.action === 'reroute' + if (after.action === 'migrate' || confirmedMove) { const from = id - if (migrate(after.reason) && id !== from) { + if ( + migrate(confirmedMove ? 'quota-exhausted' : after.reason) && + id !== from + ) { const replacement = current.find((candidate) => candidate.id === id) const replaced = sendable(replacement) ? await ctx.send(replacement, tiers?.get(id)) diff --git a/packages/pi/src/runtime.ts b/packages/pi/src/runtime.ts index 3cc7b275..b3b4c434 100644 --- a/packages/pi/src/runtime.ts +++ b/packages/pi/src/runtime.ts @@ -9,13 +9,12 @@ // account's token in place of Pi's: pi-ai derives the `chatgpt-account-id` // header from that token, so the token is the whole credential. // -// An attempt that fails before streaming anything (an HTTP error answer) may -// be sent again with another account: nothing reached Pi yet. Once an attempt -// has streamed its first event, that attempt is the request's answer. +// An attempt that fails before publishing output may hold or move to another +// account. Once output reaches Pi, that attempt is the request's answer. // // Quota is recorded from every HTTP response's `x-codex-*` headers and from -// every `codex.rate_limits` WebSocket frame, against the account whose token -// produced it. +// `codex.rate_limits` events on HTTP SSE and WebSocket, against the account +// whose token produced them. // // Once Pi is connected to the Claustrum vault (`/openai` > Vault), Pi is in // vault mode: the OpenAI accounts the vault serves it are the only accounts @@ -180,6 +179,8 @@ const TERMINAL_AFTER_OUTPUT_MESSAGE = /** An attempt as the router sees it, with the events it produced so far. */ interface StreamAttempt extends RouteAttempt { + /** Only a real HTTP status can trigger vault credential recovery. */ + httpStatus?: number /** The events through the first output or terminal event, held until selection. */ buffered: AssistantMessageEvent[] /** The rest of the attempt's events, when it is streaming. */ @@ -667,7 +668,10 @@ export class PiOpenAIRuntime { } /** Credit quota to the account and vault credential that sent this request, not the socket's opener. */ - observeWebSocketMessage(dispatch: PiQuotaDispatch, data: string): void { + observeWebSocketMessage( + dispatch: PiQuotaDispatch, + data: string, + ): OAuthQuotaSnapshot | undefined { if (!data.includes('codex.rate_limits')) return let event: unknown try { @@ -675,20 +679,18 @@ export class PiOpenAIRuntime { } catch { return } - if ( - !event || - typeof event !== 'object' || - (event as { type?: unknown }).type !== 'codex.rate_limits' - ) - return - this.recordQuota( - dispatch, - normalizeWsFrame( - event as Parameters[0], - ) as Record, - true, - { frame: event }, + return this.recordQuotaEvent(dispatch, event) + } + + private recordQuotaEvent(dispatch: PiQuotaDispatch, event: unknown) { + if (!isRecord(event) || event.type !== 'codex.rate_limits') return + const snapshot = normalizeWsFrame( + event as unknown as Parameters[0], ) + this.recordQuota(dispatch, snapshot as Record, true, { + frame: event, + }) + return snapshot } // ------------------------------------------------------------------------- @@ -962,7 +964,7 @@ export class PiOpenAIRuntime { } /** - * Sends the request once with `token` and waits for output or termination. + * Calls pi-ai with one account's token and waits for output or termination. * Lifecycle events alone do not commit the attempt to a serving account. */ private async attempt( @@ -998,13 +1000,53 @@ export class PiOpenAIRuntime { freeQuota, ) } - let status: number | undefined - let signal: LimitSignal | undefined - let reading: OAuthQuotaSnapshot | undefined const account = this.accounts( this.settings(this.storageCache?.storage ?? null), ).find((value) => value.id === accountId) const accountKey = account?.accountKey + const initialReading = windowsFromQuotaMap(account?.quota) + let reading = initialReading + let httpStatus: number | undefined + let httpBody: string | undefined + let headers: Headers | undefined + let limit: { signal: LimitSignal; body: unknown } | undefined + const status = () => limit?.signal.status ?? httpStatus + const beginSend = () => { + // pi-ai can retry a send or switch transports without ending its stream. + httpStatus = undefined + httpBody = undefined + headers = undefined + limit = undefined + reading = initialReading + } + const mergeReading = (snapshot: OAuthQuotaSnapshot | undefined) => { + if (!snapshot) return + const observedAt = this.now() + for (const window of [snapshot.primary, snapshot.secondary]) { + if (window) window.checkedAt = observedAt + } + reading = { ...reading, ...snapshot } + } + const reportLimit = () => { + if ( + !receipt || + !hasVaultRoutingAccessor() || + limit?.signal.kind !== 'quota-exhausted' + ) + 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 }, + ) + } const dispatch: SessionDispatch | undefined = accountKey && options?.sessionId ? { @@ -1014,7 +1056,6 @@ export class PiOpenAIRuntime { ttlMs: ttlForModel(JSON.stringify({ model: model.id })), } : undefined - let body: unknown let inner: AssistantMessageEventStream try { const send = options?.fetch ?? globalThis.fetch @@ -1053,25 +1094,22 @@ export class PiOpenAIRuntime { // Scrub before pi-ai parses errors into its shared partial message objects. fetch: Object.assign( async (input: RequestInfo | URL, init?: RequestInit) => { + beginSend() try { const response = await send( input, input === httpUrl ? shapePiCodexHttpRequest(init) : init, ) - // Never read an SSE success body: it may be an unbounded stream. - // The clone leaves the SDK's error bytes and response untouched. - if (response.status >= 400) { - try { - body = await response.clone().text() - } catch { - body = undefined - } - } - return await redactCredentialResponse( + const safe = await redactCredentialResponse( response, token, 'event-stream', + { boundRefusal: !!receipt && hasVaultRoutingAccessor() }, ) + // Read the same diagnostic pi-ai gets, never a second copy of + // the provider's potentially unbounded body. + if (safe.status === 429) httpBody = await safe.clone().text() + return safe } catch (error) { // pi-ai can inspect a fetch rejection before emitting its shared partial error. throw redactCredentialError(error, token) @@ -1080,65 +1118,55 @@ export class PiOpenAIRuntime { send, ), onResponse: async (response, responseModel) => { - status = response.status + httpStatus = response.status + headers = new Headers(response.headers) this.recordHeaders(quotaDispatch, response.headers) - const observedAt = this.now() - const headersReading = normalizeQuotaHeaders( - new Headers(response.headers), - ) - // Freshness must use the same clock as routing and stored observations. - for (const window of [ - headersReading.primary, - headersReading.secondary, - ]) { - if (window) window.checkedAt = observedAt - } - reading = { - ...windowsFromQuotaMap(account?.quota), - ...headersReading, - } - if (accountKey && status === 429) - signal = classifyOpenAiLimitBody({ + mergeReading(normalizeQuotaHeaders(headers)) + limit = undefined + if (accountKey && httpStatus === 429) { + let body: unknown + if (httpBody !== undefined) { + try { + body = JSON.parse(httpBody) + } catch { + // A non-JSON diagnostic can only supply the HTTP status. + } + } + const signal = classifyOpenAiLimitBody({ account: accountKey, - status, - headers: new Headers(response.headers), + status: httpStatus, + headers, body, now: this.now(), reading, }) + if (signal) limit = { signal, body } + } + await options?.onResponse?.(response, responseModel) + }, + onProviderStreamEvent: async (event, eventModel) => { + // The bound WebSocket records quota before pi-ai dispatches this callback. + if (httpStatus !== undefined || !useWebSocketShim) + mergeReading(this.recordQuotaEvent(quotaDispatch, event)) if ( - receipt && - hasVaultRoutingAccessor() && - signal?.kind === 'quota-exhausted' + accountKey && + isRecord(event) && + event.type === 'response.failed' ) { - let parsed = body - if (typeof parsed === 'string') { - try { - parsed = JSON.parse(parsed) - } catch { - parsed = undefined + const signal = classifyOpenAiLimitBody({ + account: accountKey, + body: event, + headers, + now: this.now(), + reading, + }) + if (signal) + limit = { + signal: { ...signal, status: signal.status ?? 429 }, + body: structuredClone(event), } - } - // Report before routing chooses another account or waits on this one. - reportVaultRoutingLimit( - options?.sessionId, - receipt, - { - window: signal.reason, - resetAt: signal.windows.find( - (window) => - window.confirmed && window.provenance === 'provider', - )?.resetAt, - }, - { - body: parsed, - headers: new Headers(response.headers), - quota: account?.quota, - now: observedAt, - }, - ) } - await options?.onResponse?.(response, responseModel) + await options?.onProviderStreamEvent?.(event, eventModel) }, } const start = () => this.deps.streamSimple(model, context, streamOptions) @@ -1149,14 +1177,15 @@ export class PiOpenAIRuntime { token, owner: this, sessionId: effortSessionId, + onSend: beginSend, onMessage: (data) => - this.observeWebSocketMessage(quotaDispatch, data), + mergeReading(this.observeWebSocketMessage(quotaDispatch, data)), }, start, ) : start() } catch (error) { - billing?.end(false, false, status) + billing?.end(false, false, status()) return { buffered: [ errorEvent(model, redactCredentialError(error, token).message), @@ -1179,12 +1208,15 @@ export class PiOpenAIRuntime { else if (event.type === 'error') { billing.piResponseId(event.error.responseId) if (event.reason !== 'aborted') billing.event({ type: 'error' }) - // Routing may discard an unpublished error without draining the iterator. - billing.end(outputStarted, false, status) } } if (event.type === 'error') { 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() + // 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. event.error.errorMessage = outputStarted && event.reason !== 'aborted' @@ -1207,7 +1239,7 @@ export class PiOpenAIRuntime { }, ) } catch (error) { - billing?.end(outputStarted, false, status) + billing?.end(outputStarted, false, status()) yield errorEvent( model, outputStarted @@ -1215,7 +1247,7 @@ export class PiOpenAIRuntime { : redactCredentialError(error, token).message, ) } finally { - billing?.end(outputStarted, stopped && !failed, status) + billing?.end(outputStarted, stopped && !failed, status()) } })() const buffered: AssistantMessageEvent[] = [] @@ -1233,12 +1265,16 @@ export class PiOpenAIRuntime { break } } + const attemptStatus = status() return { // The observed status still reaches billing. Neither the account router // nor vault credential recovery may use it to replay an output attempt. - ...(status !== undefined && !outputStarted ? { status } : {}), + ...(attemptStatus !== undefined && !outputStarted + ? { status: attemptStatus } + : {}), + ...(httpStatus !== undefined && !outputStarted ? { httpStatus } : {}), ...(accountKey ? { accountKey } : {}), - ...(signal && !outputStarted ? { signal } : {}), + ...(limit && !outputStarted ? { signal: limit.signal } : {}), ...(reading ? { reading } : {}), buffered, rest, @@ -1275,7 +1311,7 @@ export class PiOpenAIRuntime { execution, freeQuota, ) - return new Response(null, { status: last.status ?? 200 }) + return new Response(null, { status: last.httpStatus ?? 200 }) }, { site: 'model', ...(options?.signal ? { signal: options.signal } : {}) }, ) diff --git a/packages/pi/src/tests/quota-wait.test.ts b/packages/pi/src/tests/quota-wait.test.ts index 17a158fe..8903a4fc 100644 --- a/packages/pi/src/tests/quota-wait.test.ts +++ b/packages/pi/src/tests/quota-wait.test.ts @@ -26,7 +26,15 @@ import { type Model, type SimpleStreamOptions, } from '@earendil-works/pi-ai' +import { closeOpenAICodexWebSocketSessions } from '@earendil-works/pi-ai/api/openai-codex-responses' import { streamSimple } from '@earendil-works/pi-ai/compat' +import { installRawCodexWebSocket } from '../codex-websocket.ts' +import { RawWebSocket } from '../raw-ws-node.ts' +import { + clearPiStickyRouting, + getPiStickyRouting, + setPiStickyRouting, +} from '../routing.ts' import { PiOpenAIRuntime, type PiOpenAIRuntimeDeps } from '../runtime.ts' import { isolatePiAgentDir } from './test-isolation.ts' @@ -52,17 +60,19 @@ function jwt(identity: string, nonce = '') { } const MAIN = jwt('main') const B = jwt('beta') -function ok(tail = '') { +const textFrames = [ + '{"type":"response.output_item.added","item":{"type":"message","id":"m","role":"assistant","status":"in_progress","content":[]}}', + '{"type":"response.output_text.delta","item_id":"m","delta":"hello"}', + '{"type":"response.output_item.done","item":{"type":"message","id":"m","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hello"}]}}', +] +const completed = + '{"type":"response.completed","response":{"id":"r","status":"completed","usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}' +function ok(tail = `data: ${completed}`) { return new Response( - [ - 'data: {"type":"response.output_item.added","item":{"type":"message","id":"m","role":"assistant","status":"in_progress","content":[]}}', - 'data: {"type":"response.output_text.delta","item_id":"m","delta":"hello"}', - 'data: {"type":"response.output_item.done","item":{"type":"message","id":"m","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hello"}]}}', - tail || - 'data: {"type":"response.completed","response":{"id":"r","status":"completed","usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}', - '', - ].join('\n\n'), - { headers: { 'content-type': 'text/event-stream' } }, + [...textFrames.map((frame) => `data: ${frame}`), tail, ''].join('\n\n'), + { + headers: { 'content-type': 'text/event-stream' }, + }, ) } @@ -124,6 +134,7 @@ beforeEach(async () => { }, paths) }) afterEach(async () => { + clearPiStickyRouting('stream-limit') if (originalRouting) Object.defineProperty(globalThis, routingKey, originalRouting) else Reflect.deleteProperty(globalThis, routingKey) @@ -180,9 +191,10 @@ async function start(overrides: Partial = {}, ui = true) { async function send( options: SimpleStreamOptions = {}, events: AssistantMessageEvent[] = [], + model = MODEL, ) { for await (const event of runtime.stream( - MODEL, + model, { messages: [{ role: 'user', content: 'hi', timestamp: 0 }] }, { apiKey: MAIN, @@ -241,6 +253,308 @@ async function addB() { }) } +const heldFrames = [ + '{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"empty-rs","summary":[]}}', + '{"type":"response.reasoning_summary_text.delta","output_index":0,"delta":""}', + '{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"empty-rs","summary":[]}}', +] + +function withSseFrames(frames: string[]) { + return new Response(frames.map((frame) => `data: ${frame}\n\n`).join(''), { + headers: { 'content-type': 'text/event-stream' }, + }) +} + +function withWebSocketPeer(framesFor: (token: string) => string[]) { + const sentFrames: string[] = [] + const seamFrames: string[] = [] + const tokens: string[] = [] + const rawSend = RawWebSocket.prototype.send + const seam = spyOn(RawWebSocket.prototype, 'send').mockImplementation( + function (this: RawWebSocket, data: string) { + expect(globalThis.WebSocket.name).toBe('PiRawCodexWebSocket') + expect(this).toBeInstanceOf(globalThis.WebSocket) + seamFrames.push(data) + rawSend.call(this, data) + }, + ) + const server = Bun.serve({ + hostname: '127.0.0.1', + port: 0, + fetch(request, server) { + const token = request.headers.get('authorization')?.slice(7) ?? '' + if (server.upgrade(request, { data: token })) return + return new Response(null, { status: 400 }) + }, + websocket: { + message(socket, data) { + tokens.push(socket.data) + sentFrames.push(data.toString()) + for (const frame of framesFor(socket.data)) socket.send(frame) + }, + }, + }) + return { + model: { ...MODEL, baseUrl: server.url.href }, + expectSends(expected: string[]) { + expect(tokens).toEqual(expected) + expect(sends).toEqual([]) + expect(sentFrames).toHaveLength(expected.length) + expect(sentFrames).toEqual(seamFrames) + }, + async stop(sessionId: string) { + closeOpenAICodexWebSocketSessions(sessionId) + seam.mockRestore() + await server.stop(true) + }, + } +} + +describe('Pi routed Codex transport limits', () => { + const sessionId = 'stream-limit' + async function startSticky() { + await addB() + await mutateAccounts((storage) => { + storage.routing = { mode: 'sticky-balanced', maxSameAccountWait: 15 } + return storage + }, paths) + setPiStickyRouting(sessionId, 'main') + } + + for (const [transport, move, hold] of [ + [ + 'HTTP 429', + 'OA-58 HTTP 429 confirmed usage limit moves the sticky session without a fitting cache', + 'OA-58 HTTP 429 confirmed usage limit holds for a fitting cache', + ], + [ + 'SSE', + 'OA-58 SSE confirmed usage limit moves the sticky session without a fitting cache', + 'OA-58 SSE confirmed usage limit holds for a fitting cache', + ], + [ + 'WebSocket', + 'OA-58 WebSocket confirmed usage limit moves the sticky session without a fitting cache', + 'OA-58 WebSocket confirmed usage limit holds for a fitting cache', + ], + ] as const) { + for (const fitting of [false, true]) { + test(fitting ? hold : move, async () => { + await startSticky() + const waits: number[] = [] + let refusing = false + await start({ + installWebSocket: installRawCodexWebSocket, + waitForPi: async (delay) => { + waits.push(delay) + now += delay + refusing = false + return 'elapsed' + }, + }) + const frame = + '{"type":"response.failed","response":{"error":{"code":"usage_limit_reached","message":"provider limit on A","resets_at":1900000060}}}' + const framesFor = (token: string) => + refusing && token === MAIN + ? [...heldFrames, frame] + : [...textFrames, completed] + reply = (token) => { + if (transport === 'SSE') return withSseFrames(framesFor(token)) + if (!refusing || token !== MAIN) return ok() + return Response.json( + { + error: { + type: 'usage_limit_reached', + message: 'provider limit on A', + resets_at: 1900000060, + }, + }, + { status: 429 }, + ) + } + const peer = + transport === 'WebSocket' ? withWebSocketPeer(framesFor) : undefined + try { + const opts: SimpleStreamOptions = { + sessionId, + maxRetries: 0, + transport: peer ? 'websocket-cached' : 'sse', + } + const model = peer?.model ?? MODEL + if (fitting) + expect((await send(opts, [], model)).at(-1)?.type).toBe('done') + refusing = true + const events = await send(opts, [], model) + expect(events.map((event) => event.type)).toEqual([ + 'start', + 'text_start', + 'text_delta', + 'text_end', + 'done', + ]) + expect(events[2]).toMatchObject({ delta: 'hello' }) + expect(waits).toEqual(fitting ? [60_000] : []) + expect(runtime.main.quotaSnapshot()?.primary?.usedPercent).toBe(10) + expect(getPiStickyRouting(sessionId)).toBe(fitting ? 'main' : 'beta') + expect(decisions[0]?.decision.action).toBe( + fitting ? 'hold' : 'reroute', + ) + expect(decisions[0]?.facts).toMatchObject({ + status: 429, + signal: { + kind: 'quota-exhausted', + status: 429, + windows: [ + { window: 'usage', confirmed: true, resetAt: 1900000060000 }, + ], + }, + }) + const expected = fitting ? [MAIN, MAIN, MAIN] : [MAIN, B] + if (peer) peer.expectSends(expected) + else expect(sends).toEqual(expected) + } finally { + await peer?.stop(sessionId) + } + }) + } + } + + for (const { title, error, status, expected, expectedStatus } of [ + { + title: + 'OA-55 SSE code-only usage_limit_reached confirms without status or reset', + error: { code: 'usage_limit_reached' }, + status: undefined, + expectedStatus: 429, + expected: 'reroute', + }, + { + title: 'OA-55 SSE type-only rate_limit_exceeded at 429 is not exhaustion', + error: { type: 'rate_limit_exceeded', resets_at: 1900000060 }, + status: 429, + expectedStatus: 429, + expected: 'retain', + }, + { + title: 'OA-55 SSE code takes precedence over a usage-limit type', + error: { code: 'unrelated', type: 'usage_limit_reached' }, + status: 429, + expectedStatus: undefined, + expected: undefined, + }, + { + title: 'OA-55 SSE an explicit 403 is not replaced with 429', + error: { code: 'usage_limit_reached' }, + status: 403, + expectedStatus: 403, + expected: 'reroute', + }, + ] as const) + test(title, async () => { + await startSticky() + await start() + reply = (token) => + token === MAIN + ? withSseFrames([ + ...heldFrames, + JSON.stringify({ + type: 'response.failed', + status, + response: { error }, + }), + ]) + : ok() + const events = await send({ sessionId, maxRetries: 0 }) + expect(decisions[0]?.decision.action).toBe(expected) + expect(decisions[0]?.facts.status).toBe(expectedStatus) + expect(decisions[0]?.facts.signal?.kind).toBe( + expected === 'retain' + ? 'rate-limit' + : expected === 'reroute' + ? 'quota-exhausted' + : undefined, + ) + expect(sends).toEqual(expected === 'reroute' ? [MAIN, B] : [MAIN]) + expect(events.at(-1)?.type).toBe( + expected === 'reroute' ? 'done' : 'error', + ) + }) + + test('OA-57 rejected WebSocket upgrade and unclassified fallback failure do not guess a status', async () => { + await addB() + await start({ installWebSocket: installRawCodexWebSocket }) + const upgrades: string[] = [] + const server = Bun.serve({ + hostname: '127.0.0.1', + port: 0, + fetch(request) { + upgrades.push(request.headers.get('authorization') ?? '') + return new Response('not a quota response', { status: 429 }) + }, + }) + try { + reply = () => { + throw new Error('fallback failed without an HTTP response') + } + const events = await send( + { + sessionId: 'failed-upgrade', + transport: 'websocket-cached', + maxRetries: 0, + }, + [], + { ...MODEL, baseUrl: server.url.href }, + ) + expect(upgrades).toEqual([`Bearer ${MAIN}`]) + expect(sends).toEqual([MAIN]) + expect(decisions).toEqual([]) + expect(text(events)).toContain('fallback failed without an HTTP response') + } finally { + closeOpenAICodexWebSocketSessions('failed-upgrade') + await server.stop(true) + } + }) + + test('OA-60 WebSocket usage limit after published text does not reroute or hold', async () => { + await startSticky() + const waits: number[] = [] + await start({ + installWebSocket: installRawCodexWebSocket, + waitForPi: async (delay) => { + waits.push(delay) + return 'elapsed' + }, + }) + const peer = withWebSocketPeer(() => [ + ...textFrames, + '{"type":"response.failed","response":{"error":{"code":"usage_limit_reached","message":"late WebSocket quota limit","resets_at":1900000060}}}', + ]) + try { + const events = await send( + { sessionId, transport: 'websocket-cached', maxRetries: 0 }, + [], + peer.model, + ) + peer.expectSends([MAIN]) + expect(events.map((event) => event.type)).toEqual([ + 'start', + 'text_start', + 'text_delta', + 'text_end', + 'error', + ]) + expect(events[2]).toMatchObject({ delta: 'hello' }) + expect(text(events)).toContain('It was not sent again') + expect(text(events)).not.toContain('late WebSocket quota limit') + expect(waits).toEqual([]) + expect(decisions).toEqual([]) + expect(getPiStickyRouting(sessionId)).toBe('main') + } finally { + await peer.stop(sessionId) + } + }) +}) + describe('Pi bounded quota waits', () => { test.each([ { diff --git a/packages/pi/src/tests/vault.test.ts b/packages/pi/src/tests/vault.test.ts index d306cc7f..0fe6f4b2 100644 --- a/packages/pi/src/tests/vault.test.ts +++ b/packages/pi/src/tests/vault.test.ts @@ -32,6 +32,7 @@ import { type Context, createAssistantMessageEventStream, type Model, + type SimpleStreamOptions, } from '@earendil-works/pi-ai' import { closeOpenAICodexWebSocketSessions } from '@earendil-works/pi-ai/api/openai-codex-responses' import { streamSimple } from '@earendil-works/pi-ai/compat' @@ -180,7 +181,7 @@ function runtimeWith(target: OpenAiVault, webSocket = false): PiOpenAIRuntime { async function send( runtime: PiOpenAIRuntime, - options: { sessionId?: string; apiKey?: string } = {}, + options: SimpleStreamOptions = {}, ): Promise { const events: AssistantMessageEvent[] = [] const stream = runtime.stream(MODEL, CONTEXT, { @@ -213,6 +214,200 @@ function enroll() { } describe('Pi and the Claustrum vault', () => { + test('vault slow and oversized diagnostics are bounded for pi-ai without rewriting an ordinary refusal', async () => { + Reflect.set(globalThis, routingKey, () => ({})) + daemon = await startMockDaemon({ + directory: dir, + credentials: { 'oauth:openai:vault': vaultLogin('chatgpt-vault') }, + }) + enroll() + const target = vault() + const runtime = runtimeWith(target) + const encoder = new TextEncoder() + let timer: ReturnType | undefined + let cancelled = false + let sentAt = 0 + const slow = () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode('partial provider text')) + timer = setTimeout(() => controller.close(), 3000) + }, + cancel() { + cancelled = true + clearTimeout(timer) + }, + }), + { status: 403 }, + ) + let sentBytes = 0 + let overflowCancelled = false + const oversized = () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(65_536).fill(120)) + controller.enqueue(encoder.encode('x')) + sentBytes = 65_537 + timer = setTimeout(() => controller.close(), 100) + }, + cancel() { + overflowCancelled = true + clearTimeout(timer) + }, + }), + { status: 429 }, + ) + const refusal = async (body: () => Response) => { + const options = { + maxRetries: 0, + fetch: (async () => { + sentAt = performance.now() + return body() + }) as unknown as typeof fetch, + } + const event = (await send(runtime, options)).at(-1) + expect(event?.type).toBe('error') + return event?.type === 'error' ? event.error.errorMessage : undefined + } + try { + await target.refresh() + await target.pollStale(0) + expect(await refusal(slow)).toBe('No diagnostic was received.') + const elapsed = performance.now() - sentAt + expect(elapsed).toBeGreaterThanOrEqual(1900) + expect(elapsed).toBeLessThan(3000) + expect(cancelled).toBe(true) + expect(await refusal(oversized)).toBe('No diagnostic was received.') + expect(sentBytes).toBe(65_537) + expect(overflowCancelled).toBe(true) + expect( + await refusal( + () => new Response('ordinary provider refusal', { status: 403 }), + ), + ).toBe('ordinary provider refusal') + } finally { + clearTimeout(timer) + await target.dispose() + await runtime.pool.dispose() + } + }) + + test('OA-57 a successful pi-ai HTTP retry does not report or act on the first limit', async () => { + const reports: Record[] = [] + let asks = 0 + Reflect.set(globalThis, routingKey, () => ({ + report(payload: Record) { + reports.push(payload) + }, + accountFor() { + asks++ + }, + })) + daemon = await startMockDaemon({ + directory: dir, + credentials: { 'oauth:openai:vault': vaultLogin('chatgpt-vault') }, + }) + enroll() + const target = vault() + const decisions: PolicyFacts[] = [] + const waits: number[] = [] + const runtime = new PiOpenAIRuntime({ + streamSimple, + createStream: createAssistantMessageEventStream, + paths: () => paths, + vault: target, + fetchImpl: fakeFetch, + firstReadingWaitMs: 0, + onLimitDecision: (_decision, facts) => decisions.push(facts), + waitForPi: async (delay) => { + waits.push(delay) + return 'elapsed' + }, + }) + runtime.setWorkingMessage = () => {} + try { + await target.refresh() + await target.pollStale(0) + codexStatus = () => (codexTokens.length === 1 ? 429 : 200) + codexErrorBody = + '{"error":{"type":"usage_limit_reached","rate_limit_reached_type":"primary","resets_in_seconds":60}}' + codexReplyHeaders = { 'retry-after': '0' } + const events = await send(runtime, { + maxRetries: 1, + sessionId: 'session-1', + }) + expect(events.at(-1)?.type).toBe('done') + expect(codexTokens).toEqual([VAULT_ACCESS, VAULT_ACCESS]) + 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', + }), + ]) + } finally { + await target.dispose() + await runtime.pool.dispose() + } + }) + + test('Pi attributes SSE-only codex.rate_limits to the receipt that sent the request', async () => { + daemon = await startMockDaemon({ + directory: dir, + credentials: { + 'oauth:openai:vault': vaultLogin('chatgpt-vault', { + record_version: 3, + }), + }, + }) + enroll() + const target = vault() + const runtime = runtimeWith(target) + const usage = spyOn(target, 'reportUsage') + const quota = { + type: 'codex.rate_limits', + rate_limits: { primary: { used_percent: 77, window_minutes: 300 } }, + } + try { + await target.refresh() + await target.pollStale(0) + usage.mockClear() + const events = await send(runtime, { + fetch: (async () => + new Response( + `data: ${JSON.stringify(quota)}\n\n${await sseOk().text()}`, + { headers: { 'content-type': 'text/event-stream' } }, + )) as unknown as typeof fetch, + }) + expect(events.at(-1)?.type).toBe('done') + const accountId = target.routes()[0]?.id + if (!accountId) throw new Error('Expected a served vault route') + expect( + usage.mock.calls.filter(([, reading]) => 'frame' in reading), + ).toEqual([ + [ + accountId, + { frame: quota }, + expect.objectContaining({ + credentialId: 'oauth:openai:vault', + recordVersion: 3, + accountIdentity: 'chatgpt-vault', + }), + ], + ]) + } finally { + usage.mockRestore() + await target.dispose() + await runtime.pool.dispose() + } + }) for (const scenario of [ { name: 'usage-limit refusal', accessor: true, wait: false, usage: true }, { From a72a1fdf7a1c5db08e356f152da0d4bdc674d421 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:40:34 +0100 Subject: [PATCH 4/9] docs: point the ledger at the renamed OpenCode 2 empty-vault refusal test --- docs/limit-policy-conformance.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/limit-policy-conformance.md b/docs/limit-policy-conformance.md index 02ed9660..6c33761d 100644 --- a/docs/limit-policy-conformance.md +++ b/docs/limit-policy-conformance.md @@ -138,7 +138,7 @@ The adoption column includes the deliberate changes to OA-23/32/36/38/49/50/57/5 | OA-61 | D | Preserve auth causes; quota gains known-reset bounded terminal wait and safe final text; unknown reset never advertises scheduled wait. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `fresh provider mark uses the pinned 90-second retry and rounded reset text`; [`packages/opencode/src/tests/opencode1-limit-policy.test.ts`](../packages/opencode/src/tests/opencode1-limit-policy.test.ts) → `unproven live mark uses pinned OA-36 wire at 15` | N/A — Pi buffered-head/countdown executor is not used by OC2. Owning boundary: [`packages/opencode/src/tests/opencode2-limit-policy.test.ts`](../packages/opencode/src/tests/opencode2-limit-policy.test.ts) → `case 16 scans B without holding A for its reset` | [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-61 known 60s terminal wait revalidates then sends once with current credentials`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `OA-61 two-hour reset waits only 15 minutes then gives the exact final text`; [`packages/pi/src/tests/quota-wait.test.ts`](../packages/pi/src/tests/quota-wait.test.ts) → `unknown terminal reset never starts a countdown even with UI` | | OA-62 | B | Pi first-reading startup join/reread and incomplete error remain separate from quota wait. | N/A — Pi buffered-head/countdown executor is not used by OC1. Owning boundary: [`packages/opencode/src/tests/pool-request.test.ts`](../packages/opencode/src/tests/pool-request.test.ts) → `main-first: the original request serves after its in-flight first reading, without a host retry` | N/A — Pi buffered-head/countdown executor is not used by OC2. Owning boundary: [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `the original request joins a pending first vault quota poll and serves without a retry` | [`packages/pi/src/tests/pool-routing.test.ts`](../packages/pi/src/tests/pool-routing.test.ts) → `the original request serves after a pending first reading without a second request` | | OA-63 | R | Unreachable vault without usable receipt keeps bounded startup/incomplete/custody refusal, never local fallback. | [`packages/opencode/src/tests/vault.test.ts`](../packages/opencode/src/tests/vault.test.ts) → `a vault daemon that never answers holds neither the loader nor, past a bounded wait, a request, which is refused with nothing sent or refreshed` | [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `a vault daemon that never answers holds neither setup nor, past a bounded wait, a request, which is refused locally` | [`packages/pi/src/tests/vault-mode.test.ts`](../packages/pi/src/tests/vault-mode.test.ts) → `a vault that cannot be reached refuses the request locally after a bounded wait: nothing is sent, refreshed or polled` | -| OA-64 | R | Listed but unusable/old empty roster preserves no-usable-vault-account cause. | [`packages/opencode/src/tests/vault.test.ts`](../packages/opencode/src/tests/vault.test.ts) → `an empty vault refusal: an older vault keeps the general empty-vault text` | [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `refuses locally when the vault serves no account` | [`packages/pi/src/tests/vault-mode.test.ts`](../packages/pi/src/tests/vault-mode.test.ts) → `an empty vault: an older vault keeps the general texts` | +| OA-64 | R | Listed but unusable/old empty roster preserves no-usable-vault-account cause. | [`packages/opencode/src/tests/vault.test.ts`](../packages/opencode/src/tests/vault.test.ts) → `an empty vault refusal: an older vault keeps the general empty-vault text` | [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `keeps the vault-empty refusal for an empty roster with a quota minimum` | [`packages/pi/src/tests/vault-mode.test.ts`](../packages/pi/src/tests/vault-mode.test.ts) → `an empty vault: an older vault keeps the general texts` | | OA-65 | R | Zero grants preserves no-grant guidance and host principal template, without local fallback. | [`packages/opencode/src/tests/vault.test.ts`](../packages/opencode/src/tests/vault.test.ts) → `an empty vault refusal: no grant gives the exact grant command` | [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `an empty vault with no grant for this host refuses with the exact grant command` | [`packages/pi/src/tests/vault-mode.test.ts`](../packages/pi/src/tests/vault-mode.test.ts) → `an empty vault: no grant names the grant command for Pi` | | OA-66 | R | Grant with no ChatGPT login preserves category/reclassification guidance. | [`packages/opencode/src/tests/vault.test.ts`](../packages/opencode/src/tests/vault.test.ts) → `an empty vault refusal: a grant reaching no login names reclassify and status` | [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `an empty vault whose grant reaches no login refuses with reclassify and status` | [`packages/pi/src/tests/vault-mode.test.ts`](../packages/pi/src/tests/vault-mode.test.ts) → `an empty vault: a grant reaching no login names reclassify and status` | | OA-67 | R | Authorization refusals keep custody cause; may skip unsent vault candidate, never infer exhaustion or use local credentials. | [`packages/opencode/src/tests/vault.test.ts`](../packages/opencode/src/tests/vault.test.ts) → `in an ordered mode, a refused vault account passes the request to another vault account` | [`packages/opencode/src/tests/opencode2-vault.test.ts`](../packages/opencode/src/tests/opencode2-vault.test.ts) → `refuses locally a request the vault refuses to serve: no local row takes it` | [`packages/pi/src/tests/vault.test.ts`](../packages/pi/src/tests/vault.test.ts) → `in an ordered mode, a vault account the vault will not serve passes the request to the next account` | From cb55764288aa4fee8550e7aaa9c46e950c3340f2 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:49:23 +0100 Subject: [PATCH 5/9] docs: add the OpenCode 2 sign-in step to the quick start (#297); release: recheck version-only changes before commit and push atomically (#299) --- README.md | 2 ++ scripts/release.sh | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7cad7c32..dd28de19 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ The setup command detects OpenCode and Pi, registers the plugin, and offers a co Then start OpenCode and run `/openai`. +On OpenCode 2, sign in once more: run `opencode auth login openai` and choose **ChatGPT (openai-auth pool, browser)** or **(headless)**, or use **Vault → Connect** in `/openai` on a host that uses only the vault. Do this after an upgrade from OpenCode 1 too, because OpenCode 2.3 and later import OpenCode 1's sign-in, which the plugin can't use. See [Signing in](docs/opencode-2.md#signing-in). + ## Shared limit policy In `/openai`, **Routing → Longest wait on the same account** offers **Don't wait**, **15 minutes** (the default), and **Until the cache expires**. A wait needs a confirmed reset and usable cache evidence; an unknown reset does not justify holding the account. The killswitch and credential checks still apply, and the killswitch can prevent a same-account wait. diff --git a/scripts/release.sh b/scripts/release.sh index 46f64710..588b4f9d 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -155,6 +155,9 @@ echo " ✓ All checks passed" echo "" echo "→ Committing version bump..." +# The gate and the tests run after the first check and can leave files behind. +# Check again so nothing but the version files reaches the release commit. +check_version_changes git add -A if git diff --cached --quiet; then echo " (no changes — version already at $VERSION)" @@ -167,7 +170,8 @@ git tag -a "$TAG" -m "Release $TAG" echo "" echo "→ Pushing to origin..." -git push origin "$BRANCH" "$TAG" +# The tag starts the npm publish, so it must never land without the branch. +git push --atomic origin "$BRANCH" "$TAG" echo "" echo " ✓ Released $TAG" From b1b293979ceababc86cf10c9b9b8df5987747a0d Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:57:32 +0100 Subject: [PATCH 6/9] release: name the pre-release checks in the second file check and test it (#299) --- packages/opencode/src/tests/release.test.ts | 22 ++++++++++++++++++--- scripts/release.sh | 6 +++--- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/tests/release.test.ts b/packages/opencode/src/tests/release.test.ts index d10e3b45..f481d58a 100644 --- a/packages/opencode/src/tests/release.test.ts +++ b/packages/opencode/src/tests/release.test.ts @@ -93,7 +93,7 @@ function fixture() { } script( join(repo, 'scripts/gate.sh'), - `printf "gate %s\\n" "$*" >> "$RELEASE_LOG"\nexit "\${GATE_STATUS:-0}"`, + `printf "gate %s\\n" "$*" >> "$RELEASE_LOG"\nif [[ -n "\${GATE_LEAVES:-}" ]]; then printf 'left\\n' > "$GATE_LEAVES"; fi\nexit "\${GATE_STATUS:-0}"`, ) script( join(bin, 'gh'), @@ -204,7 +204,7 @@ describe('release script CI suite selection', () => { expect(result.status).toBe(0) expect(result.events).toContain('gate --fast\n') expect(result.events).not.toContain('suite\n') - expect(result.events).toContain('push push origin main v9.8.7\n') + expect(result.events).toContain('push push --atomic origin main v9.8.7\n') expect(f.git('rev-parse', 'HEAD')).not.toBe(f.sha) expect(f.git('rev-parse', 'v9.8.7^{}')).toBe(f.git('rev-parse', 'HEAD')) expect(f.git('status', '--porcelain')).toBe('') @@ -275,9 +275,25 @@ describe('release version-sync boundary', () => { expect(result.status).toBe(0) expect(result.events).toContain('gate --fast\n') expect(result.events).not.toContain('suite\n') - expect(result.events).toContain('push push origin main v9.8.7\n') + expect(result.events).toContain('push push --atomic origin main v9.8.7\n') }) + it.each(['unexpected.txt', 'source.ts'])( + 'refuses a file the pre-release checks left behind (%s) before committing', + (path) => { + const f = fixture() + const result = f.release({ extraEnv: { GATE_LEAVES: path } }) + expect(result.status).not.toBe(0) + expect(result.output).toContain( + `Error: the pre-release checks changed a non-version file: ${path}`, + ) + expect(result.events).toContain('gate --fast\n') + expect(result.events).not.toContain('push ') + expect(f.git('rev-parse', 'HEAD')).toBe(f.sha) + expect(f.git('tag', '--list')).toBe('') + }, + ) + for (const green of [true, false]) { it.each(['tracked', 'untracked', 'staged', 'rename'])( `refuses a non-version %s change even when CI is ${green ? 'green' : 'red'}`, diff --git a/scripts/release.sh b/scripts/release.sh index 588b4f9d..f8f570bb 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -107,11 +107,11 @@ if ci_passed; then CI_PASSED=true; fi # Keep this allowlist aligned with version-sync.mjs: no other source edits # may hitch a ride on a release that relies on the source commit's CI. check_version_changes() { - local path + local source="${1:-version sync}" path while IFS= read -r -d '' path; do case "$path" in packages/opencode/package.json|packages/pi/package.json|packages/opencode/src/version.ts|README.md|packages/opencode/README.md|packages/pi/README.md|docs/configuration.md|docs/opencode-2.md) ;; - *) echo "Error: version sync changed a non-version file: $path" >&2; return 1 ;; + *) echo "Error: $source changed a non-version file: $path" >&2; return 1 ;; esac done < <(git diff --no-renames --name-only -z HEAD; git ls-files --others --exclude-standard -z) } @@ -157,7 +157,7 @@ echo "" echo "→ Committing version bump..." # The gate and the tests run after the first check and can leave files behind. # Check again so nothing but the version files reaches the release commit. -check_version_changes +check_version_changes "the pre-release checks" git add -A if git diff --cached --quiet; then echo " (no changes — version already at $VERSION)" From 61e9a522d5e16f65a221495e39aad19aab77675f Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:57:57 +0100 Subject: [PATCH 7/9] mason: guard OpenCode 2 pool login replacements Compare the selected row epoch and identity during replacement, and reselect after a stale write. Keep a mismatched account from falling back to an unconditional replacement by row ID. --- .../src/tests/opencode2-pool-login.test.ts | 189 ++++++++++++++++++ packages/opencode/src/v2/login.ts | 154 ++++++++------ 2 files changed, 285 insertions(+), 58 deletions(-) create mode 100644 packages/opencode/src/tests/opencode2-pool-login.test.ts diff --git a/packages/opencode/src/tests/opencode2-pool-login.test.ts b/packages/opencode/src/tests/opencode2-pool-login.test.ts new file mode 100644 index 00000000..7b04f56b --- /dev/null +++ b/packages/opencode/src/tests/opencode2-pool-login.test.ts @@ -0,0 +1,189 @@ +import { afterEach, expect, test } from 'bun:test' +import { rmSync, writeFileSync } from 'node:fs' +import { quotaCodec } from '@cortexkit/common-auth/quota' +import { openPoolStore, type PoolStore } from '@cortexkit/common-auth/store' +import { writeLoginToPool } from '../v2/login' +import { + type PoolSeedRow, + poolFiles, + seedPool, +} from './fixtures/opencode2-host' + +const dirs: string[] = [] +afterEach(() => { + for (const dir of dirs.splice(0)) + rmSync(dir, { recursive: true, force: true }) +}) + +function setupPool(rows: PoolSeedRow[], emptyMain = false) { + const files = poolFiles() + dirs.push(files.dir) + seedPool(files, 'main-first', rows) + if (emptyMain) + writeFileSync(files.statePath, JSON.stringify({ version: 1, accounts: {} })) + const store = openPoolStore({ + provider: 'openai', + ...files.paths(), + quota: quotaCodec, + }) + return { files, store } +} + +function pauseFirstReplace(store: PoolStore) { + const selected = Promise.withResolvers() + const resume = Promise.withResolvers() + let first = true + const gatedStore: PoolStore = { + ...store, + async replace(...args) { + if (first) { + first = false + selected.resolve() + await resume.promise + } + return store.replace(...args) + }, + } + return { + store: gatedStore, + selected: selected.promise, + resume: resume.resolve, + } +} + +test('two OpenCode 2 sign-ins that select empty main keep both credentials', async () => { + const { files, store } = setupPool( + [{ id: 'main', identity: 'former-main' }], + true, + ) + const gate = pauseFirstReplace(store) + const bob = writeLoginToPool(gate.store, files.paths(), { + id: 'bob', + accountId: 'bob', + refresh: 'bob-login', + }) + let bobResult: Awaited + try { + await Promise.race([gate.selected, bob]) + expect( + await writeLoginToPool(store, files.paths(), { + id: 'alice', + accountId: 'alice', + refresh: 'alice-login', + }), + ).toEqual({ id: 'main', operation: 'replaced' }) + } finally { + gate.resume() + bobResult = await bob + } + expect(files.readState().accounts.main?.refresh).toBe('alice-login') + expect(files.readState().accounts.bob?.refresh).toBe('bob-login') + expect(bobResult).toEqual({ id: 'bob', operation: 'added' }) +}) + +test('an OpenCode 2 sign-in reselects a row after its holder changes account', async () => { + const { files, store } = setupPool([{ id: 'main', identity: 'alice' }]) + const gate = pauseFirstReplace(store) + const alice = writeLoginToPool(gate.store, files.paths(), { + id: 'alice', + accountId: 'alice', + refresh: 'alice-login', + }) + let aliceResult: Awaited + try { + await Promise.race([gate.selected, alice]) + await store.replace( + 'main', + { type: 'oauth', refresh: 'bob-login' }, + { identity: 'bob' }, + ) + } finally { + gate.resume() + aliceResult = await alice + } + expect(files.readState().accounts.main?.refresh).toBe('bob-login') + expect(files.readState().accounts.alice?.refresh).toBe('alice-login') + expect(aliceResult).toEqual({ id: 'alice', operation: 'added' }) +}) + +test('a refused add of main re-reads before adding the login as a new row', async () => { + const { files, store } = setupPool([]) + const events: string[] = [] + const gatedStore: PoolStore = { + ...store, + async read() { + events.push('read') + return store.read() + }, + async add(...args) { + events.push(`add:${args[0].id}`) + if (events.length === 2) + await writeLoginToPool(store, files.paths(), { + id: 'alice', + accountId: 'alice', + refresh: 'alice-login', + }) + return store.add(...args) + }, + } + expect( + await writeLoginToPool(gatedStore, files.paths(), { + id: 'bob', + accountId: 'bob', + refresh: 'bob-login', + }), + ).toEqual({ id: 'bob', operation: 'added' }) + expect(events).toEqual(['read', 'add:main', 'read', 'add:bob']) + expect(files.readState().accounts.main?.refresh).toBe('alice-login') + expect(files.readState().accounts.bob?.refresh).toBe('bob-login') +}) + +test('a stale holder whose row ID matches the login is not replaced by ID', async () => { + const { files, store } = setupPool([ + { id: 'main' }, + { id: 'alice', identity: 'alice' }, + ]) + const gate = pauseFirstReplace(store) + const alice = writeLoginToPool(gate.store, files.paths(), { + id: 'alice', + accountId: 'alice', + refresh: 'alice-login', + }) + try { + await Promise.race([gate.selected, alice]) + await store.replace( + 'alice', + { type: 'oauth', refresh: 'bob-login' }, + { identity: 'bob' }, + ) + } finally { + gate.resume() + await expect(alice).rejects.toMatchObject({ kind: 'id-exists' }) + } + expect(files.readState().accounts.alice?.refresh).toBe('bob-login') +}) + +test('persistent replacement of the same account exhausts the login retry budget', async () => { + const { files, store } = setupPool([{ id: 'main', identity: 'alice' }]) + let writes = 0 + const contendedStore: PoolStore = { + ...store, + async replace(...args) { + await store.replace( + 'main', + { type: 'oauth', refresh: `other-login-${++writes}` }, + { identity: 'alice' }, + ) + return store.replace(...args) + }, + } + await expect( + writeLoginToPool(contendedStore, files.paths(), { + id: 'alice', + accountId: 'alice', + refresh: 'alice-login', + }), + ).rejects.toMatchObject({ kind: 'attribution' }) + expect(writes).toBe(3) + expect(files.readState().accounts.main?.refresh).toBe('other-login-3') +}) diff --git a/packages/opencode/src/v2/login.ts b/packages/opencode/src/v2/login.ts index bcf0c523..38c81422 100644 --- a/packages/opencode/src/v2/login.ts +++ b/packages/opencode/src/v2/login.ts @@ -31,7 +31,10 @@ import { type PoolLoginMethod, type VaultActivationMethod, } from '@cortexkit/common-auth/opencode2' -import type { PoolStore } from '@cortexkit/common-auth/store' +import { + PoolOperationError, + type PoolStore, +} from '@cortexkit/common-auth/store' import { withAccountRules } from '@cortexkit/openai-auth-core' import { type AccountPaths, @@ -164,6 +167,8 @@ function identityOf(login: PoolLoginResult): string | undefined { return claims ? extractAccountIdFromClaims(claims) : undefined } +const LOGIN_WRITE_ATTEMPTS = 3 + /** * Writes one login into the pool by the rules at the top of this file. Row * writes hold the legacy locks an older openai-auth process refreshes a row @@ -186,11 +191,6 @@ export async function writeLoginToPool( const store = withAccountRules(pool, { rowLocks: (id) => legacyRefreshLocks(paths, id), }) - const load = await store.read() - if (load.status !== 'ready') - throw new Error( - `the account pool cannot be read (${load.status}); the login was not stored`, - ) const credential = { type: 'oauth' as const, refresh: login.refresh, @@ -198,60 +198,98 @@ export async function writeLoginToPool( ...(login.expires !== undefined ? { expires: login.expires } : {}), } const identity = identityOf(login) - if (options.vault) await assertLocalPoolLogin(options.vault) const withIdentity = identity !== undefined ? { identity } : {} - if (options.origin === 'import') { - const held = load.rows.find( - (row) => - (identity !== undefined && row.identity === identity) || - (row.credential?.type === 'oauth' && - row.credential.refresh === login.refresh), - ) - if (held) return { id: held.id, operation: 'kept' } - } - const oauth = load.rows.filter((row) => row.type === 'oauth' && !row.invalid) - const holder = identity - ? oauth.find((row) => row.identity === identity) - : undefined - const main = load.rows.find((row) => row.id === POOL_MAIN_ROW_ID) - if (holder) { - const replaced = await store.replace(holder.id, credential, withIdentity) - return { id: replaced.id, operation: 'replaced' } - } - if (!main) { - const added = await store.add({ - id: POOL_MAIN_ROW_ID, - credential, - ...withIdentity, - ...(login.label !== undefined ? { label: login.label } : {}), - }) - return { - id: added.id, - operation: - added.outcome === 'added-disabled' ? 'added-disabled' : 'added', + for (let attempt = 1; ; attempt++) { + const load = await pool.read() + if (load.status !== 'ready') + throw new Error( + `the account pool cannot be read (${load.status}); the login was not stored`, + ) + if (options.vault) await assertLocalPoolLogin(options.vault) + if (options.origin === 'import') { + const held = load.rows.find( + (row) => + (identity !== undefined && row.identity === identity) || + (row.credential?.type === 'oauth' && + row.credential.refresh === login.refresh), + ) + if (held) return { id: held.id, operation: 'kept' } } - } - if (!main.invalid && !main.credential) { - const replaced = await store.replace( - POOL_MAIN_ROW_ID, - credential, - withIdentity, + const oauth = load.rows.filter( + (row) => row.type === 'oauth' && !row.invalid, ) - return { id: replaced.id, operation: 'replaced' } - } - const added = await store.add({ - id: login.id, - credential, - ...withIdentity, - ...(login.label !== undefined ? { label: login.label } : {}), - }) - return { - id: added.id, - operation: - added.outcome === 'added-disabled' - ? 'added-disabled' - : added.outcome === 'rotated' - ? 'replaced' - : 'added', + const holder = identity + ? oauth.find((row) => row.identity === identity) + : undefined + const main = load.rows.find((row) => row.id === POOL_MAIN_ROW_ID) + const emptyMain = + main && !main.invalid && !main.credential ? main : undefined + // Use the row ID as a fallback only if the login or row lacks an identity. + const byId = + main && login.id !== POOL_MAIN_ROW_ID + ? oauth.find( + (row) => + row.id === login.id && + (identity === undefined || row.identity === undefined), + ) + : undefined + const target = holder ?? emptyMain ?? byId + try { + if (target) { + // A competing replace advances the epoch. This cannot detect another + // writer completing an empty row via add at the same epoch and identity. + const replaced = await store.replace( + target.id, + credential, + withIdentity, + { + attribution: { + credentialEpoch: target.credentialEpoch ?? 1, + ...(target.identity !== undefined + ? { identity: target.identity } + : {}), + }, + }, + ) + return { id: replaced.id, operation: 'replaced' } + } + // The account-rules add can replace a row by ID without checking its + // epoch and identity. Use the store's own add instead. + const added = await pool.add( + { + id: main ? login.id : POOL_MAIN_ROW_ID, + credential, + ...withIdentity, + ...(login.label !== undefined ? { label: login.label } : {}), + }, + main + ? undefined + : { + protect: ({ row }) => + row ? 'row main already exists' : undefined, + }, + ) + return { + id: added.id, + operation: + added.outcome === 'added-disabled' + ? 'added-disabled' + : main && added.outcome === 'rotated' + ? 'replaced' + : 'added', + } + } catch (error) { + if ( + attempt === LOGIN_WRITE_ATTEMPTS || + !(error instanceof PoolOperationError) || + error.phase !== 'before-first-write' || + (error.kind !== 'attribution' && + error.kind !== 'unknown-row' && + error.kind !== 'row-key-changed' && + error.kind !== 'row-protected' && + error.kind !== 'id-exists') + ) + throw error + } } } From 5022e181db35bf8ce2b3e0d3ffa2a7a4a0a62507 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:58:27 +0100 Subject: [PATCH 8/9] mason: bound OpenCode 2 setup rollback and teardown Register each owned release during setup and use the same ordered cleanup on setup failure and shutdown. Give each release or drain its own five-second deadline and log only the failed step, then release the vault and heartbeat even if earlier work fails. --- .../src/tests/opencode2-shutdown.test.ts | 279 +++++++++++++++++- packages/opencode/src/v2/setup.ts | 224 ++++++++------ 2 files changed, 407 insertions(+), 96 deletions(-) diff --git a/packages/opencode/src/tests/opencode2-shutdown.test.ts b/packages/opencode/src/tests/opencode2-shutdown.test.ts index 91618e74..1ffc3182 100644 --- a/packages/opencode/src/tests/opencode2-shutdown.test.ts +++ b/packages/opencode/src/tests/opencode2-shutdown.test.ts @@ -1,15 +1,24 @@ -import { expect, test } from 'bun:test' +import { expect, spyOn, test } from 'bun:test' import { rmSync } from 'node:fs' import { join } from 'node:path' import * as locks from '@cortexkit/common-auth/fs' +import * as config from '../config' +import { OpenCodeLimitSource } from '../core/limit-source' +import * as poolLifecycle from '../core/pool-lifecycle' +import * as heartbeat from '../core/process-heartbeat' +import * as sharedVault from '../core/shared-vault' +import * as cacheKeep from '../v2/cache-keep' +import * as controlPlane from '../v2/control-plane' import { opencode1HostSlot } from '../v2/host-slot' import { setupOpenAIAuth } from '../v2/setup' +import * as sidebar from '../v2/sidebar-publisher' import { fakeOpenCode2Host, poolFiles, seedPool, } from './fixtures/opencode2-host' import { openCode2PhaseClock } from './fixtures/opencode2-phase-clock' +import { restoreEnv } from './setup-env' test('OpenCode 2 shutdown stops waiting for a contended host-slot transfer lock', async () => { const files = poolFiles() @@ -77,3 +86,271 @@ test('OpenCode 2 shutdown stops waiting for a contended host-slot transfer lock' rmSync(files.dir, { recursive: true, force: true }) } }) + +function shutdownFixture(promptFailure?: Error) { + const files = poolFiles() + seedPool(files, 'main-first', []) + const host = fakeOpenCode2Host({ directory: files.dir }) + const ctx: Parameters[0] = host.ctx + const cleanups: Array<() => unknown> = [] + const called: string[] = [] + function track(step: string, release: () => T): () => T { + let done = false + cleanups.push(() => { + if (!done) return release() + }) + return () => { + done = true + called.push(step) + return release() + } + } + + const settingsEnv = 'OPENCODE_OPENAI_AUTH_SETTINGS_FILE' + const previous = process.env[settingsEnv] + process.env[settingsEnv] = join(files.dir, 'settings.jsonc') + const acquireHeartbeat = heartbeat.startProcessHeartbeat + const heartbeatSpy = spyOn( + heartbeat, + 'startProcessHeartbeat', + ).mockImplementation(async (...args) => { + const handle = await acquireHeartbeat(...args) + handle.release = track('heartbeat', handle.release) + return handle + }) + const createLifecycle = poolLifecycle.createPoolLifecycle + const lifecycleSpy = spyOn( + poolLifecycle, + 'createPoolLifecycle', + ).mockImplementation((...args) => { + const handle = createLifecycle(...args) + handle.dispose = track('migration lifecycle', handle.dispose) + return handle + }) + const acquireVault = sharedVault.acquireOpenCodeVault + const vaultSpy = spyOn( + sharedVault, + 'acquireOpenCodeVault', + ).mockImplementation((...args) => { + const handle = acquireVault(...args) + handle.release = track('vault lease', handle.release) + return handle + }) + const acquireSidebar = sidebar.acquireSidebarPublisher + const sidebarSpy = spyOn( + sidebar, + 'acquireSidebarPublisher', + ).mockImplementation((...args) => { + const handle = acquireSidebar(...args) + handle.release = track('sidebar', handle.release) + return handle + }) + const acquireKeep = cacheKeep.acquireCacheKeep + const cacheKeepSpy = spyOn(cacheKeep, 'acquireCacheKeep').mockImplementation( + (...args) => { + const handle = acquireKeep(...args) + handle.release = track('cache keep', handle.release) + return handle + }, + ) + const register = config.registerSettingsSnapshot + const settingsSpy = spyOn( + config, + 'registerSettingsSnapshot', + ).mockImplementation((path, snapshot) => { + snapshot.dispose = track( + 'settings snapshot', + snapshot.dispose.bind(snapshot), + ) + return track('settings registration', register(path, snapshot)) + }) + const limits = spyOn(OpenCodeLimitSource.prototype, 'dispose') + const hook = ctx.session.hook + const hooks = spyOn(ctx.session, 'hook').mockImplementation( + async (...args) => { + if (promptFailure && args[0] === 'prompt') throw promptFailure + const registration = await hook(...args) + return { + ...registration, + dispose: track(`hook ${args[0]}`, registration.dispose), + } + }, + ) + const auth = ctx.integration.transform + const authMethods = spyOn(ctx.integration, 'transform').mockImplementation( + async (...args) => { + const registration = await auth(...args) + return { + ...registration, + dispose: track('auth methods', registration.dispose), + } + }, + ) + const models = ctx.model.transform + const modelRules = spyOn(ctx.model, 'transform').mockImplementation( + async (...args) => { + const registration = await models(...args) + return { + ...registration, + dispose: track('model rules', registration.dispose), + } + }, + ) + const events = spyOn(ctx.event, 'subscribe') + + return { + host, + released: () => called.filter((step) => !step.startsWith('hook ')).sort(), + limits, + events, + start: () => + setupOpenAIAuth(ctx, { + paths: files.paths, + poolMigration: true, + slot: opencode1HostSlot(join(files.dir, 'auth.json')), + fence: async () => ({ open: false, blockers: [] }), + sidebarStateFile: join(files.dir, 'sidebar.json'), + vault: { + stateDir: join(files.dir, 'vault'), + connectionFile: () => join(files.dir, 'no-vault.json'), + pollIntervalMs: 0, + }, + }), + async dispose() { + for (const restore of [ + heartbeatSpy, + lifecycleSpy, + vaultSpy, + sidebarSpy, + cacheKeepSpy, + settingsSpy, + limits, + hooks, + authMethods, + modelRules, + events, + ]) + restore.mockRestore() + try { + for (const cleanup of cleanups.reverse()) await cleanup() + } finally { + restoreEnv(settingsEnv, previous) + rmSync(files.dir, { recursive: true, force: true }) + } + }, + } +} + +const rollbackSteps = [ + 'cache keep', + 'heartbeat', + 'migration lifecycle', + 'settings registration', + 'settings snapshot', + 'sidebar', + 'vault lease', +] + +test('OpenCode 2 releases acquired resources when the prompt hook rejects', async () => { + const error = new Error('prompt hook rejected') + const fixture = shutdownFixture(error) + try { + const rejection = await fixture.start().catch((reason: unknown) => reason) + expect(rejection).toBe(error) + expect(fixture.host.hooks.length).toBeGreaterThan(0) + expect({ + liveHooks: fixture.host.hooks + .filter(({ disposed }) => !disposed) + .map(({ name }) => name), + released: fixture.released(), + }).toEqual({ liveHooks: [], released: rollbackSteps }) + expect(fixture.limits).toHaveBeenCalledTimes(1) + } finally { + await fixture.dispose() + } +}) + +for (const failure of ['rejects', 'never settles'] as const) { + test(`OpenCode 2 finishes teardown when control-plane cleanup ${failure}`, async () => { + const fixture = shutdownFixture() + const blocked = Promise.withResolvers() + let controlStarted = false + const controlCleanup = spyOn( + controlPlane, + 'installControlPlane', + ).mockResolvedValue(async () => { + controlStarted = true + if (failure === 'rejects') throw new Error('control-plane cleanup failed') + await blocked.promise + }) + const realTimer = globalThis.setTimeout + let accelerated = false + let restoreTimer: (() => void) | undefined + let watchdog: ReturnType | undefined + let stopping: Promise | undefined + try { + const stop = await fixture.start() + expect(fixture.host.hooks.some(({ name }) => name === 'prompt')).toBe( + true, + ) + const signals = fixture.events.mock.calls.map( + ([options]) => options?.signal, + ) + expect(signals).toEqual([ + expect.any(AbortSignal), + expect.any(AbortSignal), + ]) + expect(signals.every((signal) => signal?.aborted === false)).toBe(true) + if (failure === 'never settles') { + // Advance the control plane's deadline without rushing other releases. + const clock = spyOn(globalThis, 'setTimeout').mockImplementation((( + callback: () => void, + delay?: number, + ...args: unknown[] + ) => { + if (controlStarted && !accelerated && delay === 5_000) { + accelerated = true + return realTimer(callback, 1, ...args) + } + return realTimer(callback, delay, ...args) + }) as typeof setTimeout) + restoreTimer = () => clock.mockRestore() + } + stopping = Promise.resolve(stop?.()).then( + () => 'finished', + () => 'rejected', + ) + const outcome = await Promise.race([ + stopping, + new Promise((resolve) => { + watchdog = realTimer(() => resolve('still pending'), 1_000) + }), + ]) + expect({ + controlStarted, + outcome, + liveHooks: fixture.host.hooks + .filter(({ disposed }) => !disposed) + .map(({ name }) => name), + released: fixture.released(), + limits: fixture.limits.mock.calls.length, + eventsAborted: signals.every((signal) => signal?.aborted), + }).toEqual({ + controlStarted: true, + outcome: 'finished', + liveHooks: [], + released: [...rollbackSteps, 'auth methods', 'model rules'].sort(), + limits: 1, + eventsAborted: true, + }) + if (failure === 'never settles') expect(accelerated).toBe(true) + } finally { + clearTimeout(watchdog) + restoreTimer?.() + blocked.resolve() + await stopping + controlCleanup.mockRestore() + await fixture.dispose() + } + }) +} diff --git a/packages/opencode/src/v2/setup.ts b/packages/opencode/src/v2/setup.ts index 6bc7e639..2d5688f1 100644 --- a/packages/opencode/src/v2/setup.ts +++ b/packages/opencode/src/v2/setup.ts @@ -159,8 +159,84 @@ import { acquireSidebarPublisher } from './sidebar-publisher' */ export const OPENAI_AUTH_PLUGIN_ID = 'cortexkit-openai-auth' -/** Longest a shutdown waits for queued quota writes before it lets go. */ -const SETTLE_ON_DISPOSE_MS = 5_000 +/** Longest shutdown waits for any one release or drain. */ +const CLEANUP_STEP_TIMEOUT_MS = 5_000 + +const CLEANUP_PHASES = [ + ['control plane'], + ['migration lifecycle'], + ['limits and pool'], + ['sidebar'], + ['pool hooks', 'prompt hook', 'auth methods', 'model rules'], + ['migration drain', 'pool drain', 'session saves', 'cache keep'], + ['settings registration'], + ['settings snapshot'], +] as const + +type CleanupStep = + | (typeof CLEANUP_PHASES)[number][number] + | 'session events' + | 'adapter' + | 'vault lease' + | 'process heartbeat' + +function createSetupCleanup(log: Pick) { + const releases = new Map unknown>() + let closing = false + let cleanup: Promise | undefined + + async function release(step: CleanupStep): Promise { + const dispose = releases.get(step) + if (!dispose) return + releases.delete(step) + let failed = false + const work = (async () => dispose())().catch(() => { + failed = true + }) + if (!(await settlesWithin(work, CLEANUP_STEP_TIMEOUT_MS))) + log.warn('OpenCode 2 cleanup step timed out', { step }) + else if (failed) log.warn('OpenCode 2 cleanup step failed', { step }) + } + + async function close(): Promise { + closing = true + try { + await release('session events') + await release('adapter') + // Drop the keep-warm hold before closing the pool and vault it uses. + // Wait for any in-flight cache-warming request alongside the other drains. + const cacheKeep = release('cache keep') + // Close the menu and stop migration before releasing the limits and pool + // they can write to. Join transfers, reads and session saves before + // letting go of their shared settings and vault. + for (const phase of CLEANUP_PHASES) { + await Promise.all( + phase.map((step) => + step === 'cache keep' ? cacheKeep : release(step), + ), + ) + } + } finally { + // Keep the process version visible until its vault work has drained or + // reached its deadline. Neither release depends on the other's success. + try { + await release('vault lease') + } finally { + await release('process heartbeat') + } + } + } + + return { + get closing() { + return closing + }, + defer(step: CleanupStep, dispose: () => unknown) { + releases.set(step, dispose) + }, + run: () => (cleanup ??= close()), + } +} /** Test and embedding seams; every field has a production default. */ export interface OpenAIAuthV2Options { @@ -657,9 +733,25 @@ export async function setupOpenAIAuth( ctx: SetupContext, options: OpenAIAuthV2Options = {}, ): Promise { + const log = createLogger('opencode2') + const cleanup = createSetupCleanup(log) + try { + await initializeOpenAIAuth(ctx, options, log, cleanup) + } catch (error) { + await cleanup.run() + throw error + } + return cleanup.run +} + +async function initializeOpenAIAuth( + ctx: SetupContext, + options: OpenAIAuthV2Options, + log: ReturnType, + cleanup: ReturnType, +): Promise { const directory = ctx.location?.directory setupTrace('setup enter', directory) - const log = createLogger('opencode2') const logQ = createLogger('quota') const version = options.version ?? PackageVersion // Before anything resolves a runtime path: where this process keeps its @@ -678,18 +770,12 @@ export async function setupOpenAIAuth( }) setupTrace('after prepareSettingsStartup', directory) const snapshot = settingsStartup.snapshot - const unregisterSettings = snapshot - ? registerSettingsSnapshot(configPath, snapshot) - : undefined - const disposeSettings = () => { - unregisterSettings?.() - snapshot?.dispose() - } - let setupComplete = false - using _settingsRollback = { - [Symbol.dispose]() { - if (!setupComplete) disposeSettings() - }, + if (snapshot) { + cleanup.defer('settings snapshot', () => snapshot.dispose()) + cleanup.defer( + 'settings registration', + registerSettingsSnapshot(configPath, snapshot), + ) } // The logger starts with the environment floor. A saved choice overrides it, // just as it does on OpenCode 1, before setup writes any diagnostic lines. @@ -730,16 +816,10 @@ export async function setupOpenAIAuth( }, log, ) + cleanup.defer('pool hooks', () => installation.dispose()) setupTrace('after installPoolHooks (stand-aside)', directory) - setupComplete = true setupTrace('setup exit (stand-aside)', directory) - return async () => { - try { - await installation.dispose() - } finally { - disposeSettings() - } - } + return } // The vault serves nothing until this host is enrolled through @@ -785,17 +865,12 @@ export async function setupOpenAIAuth( }, paths(), ) + cleanup.defer('vault lease', () => vaultLease.release()) const vault = vaultLease.vault const loadStorage = async () => (await vault.authority()) === 'local' ? loadAccounts(paths()) : loadAccountSettings(paths()) - let closing = false - using _leaseRollback = { - [Symbol.dispose]() { - if (!setupComplete) vaultLease.release() - }, - } setupTrace('before vault.authority', directory) await vault.authority() setupTrace('after vault.authority', directory) @@ -841,6 +916,8 @@ export async function setupOpenAIAuth( vaultFirstRosterBackgroundWaitMs: vaultRosterWaitMs, log: createLogger('pool'), }) + cleanup.defer('limits and pool', () => source.dispose()) + cleanup.defer('pool drain', () => source.settled()) setupTrace('before vault.authority (source)', directory) const authority = await vault.authority() setupTrace('after vault.authority (source)', directory) @@ -856,11 +933,8 @@ export async function setupOpenAIAuth( vault, log: (message) => log.warn(message), }) - using _limitsRollback = { - [Symbol.dispose]() { - if (!setupComplete) void limits.dispose() - }, - } + // The limits source now owns disposal of the pool as well. + cleanup.defer('limits and pool', () => limits.dispose()) setupTrace('before startProcessHeartbeat', directory) const heartbeat = @@ -870,6 +944,7 @@ export async function setupOpenAIAuth( version, logger: createLogger('heartbeat'), }) + if (heartbeat) cleanup.defer('process heartbeat', () => heartbeat.release()) setupTrace('after startProcessHeartbeat', directory) // Only while the migration is switched on. With it off, setup gets here @@ -901,7 +976,7 @@ export async function setupOpenAIAuth( migrate: async (deps) => { const outcome = await migrateToPool(deps) migrationRefused = outcome.status === 'refused' - if (!closing) await source.load() + if (!cleanup.closing) await source.load() return outcome }, // `vaultServes` is false until the vault's first roster read has @@ -910,17 +985,21 @@ export async function setupOpenAIAuth( // so the lifecycle (and a login waiting for it to go idle) is never // held, and the next scheduled run tries again. adopt: async (deps) => { - if (closing) return { status: 'retry', reason: 'unsettled' } + if (cleanup.closing) return { status: 'retry', reason: 'unsettled' } if (!(await settlesWithin(vaultFirstRoster, vaultRosterWaitMs))) return { status: 'retry', reason: 'vault-roster-pending' } - if (closing) return { status: 'retry', reason: 'unsettled' } + if (cleanup.closing) return { status: 'retry', reason: 'unsettled' } const outcome = await adoptHostSlotLogin(deps) - if (!closing) await source.load() + if (!cleanup.closing) await source.load() return outcome }, }) : undefined - lifecycle?.start() + if (lifecycle) { + cleanup.defer('migration lifecycle', () => lifecycle.dispose()) + cleanup.defer('migration drain', () => lifecycle.idle()) + lifecycle.start() + } vaultLease.start() @@ -930,11 +1009,7 @@ export async function setupOpenAIAuth( options.sidebarStateFile, options.sidebarObservationIntervalMs, ) - using _sidebarRollback = { - [Symbol.dispose]() { - if (!setupComplete) void sidebar.release() - }, - } + cleanup.defer('sidebar', () => sidebar.release()) // Disk publication must not hold up the host's location-ready lifecycle. void sidebar.publish() // Thread ids are saved per host session so the prompt cache key survives a @@ -942,6 +1017,8 @@ export async function setupOpenAIAuth( const codex = options.codex ?? new CodexHttpState(undefined, undefined, acquireCodexSessions()) + const sessionStore = codex.store + if (sessionStore) cleanup.defer('session saves', () => sessionStore.settled()) // One keep-warm manager per process and account store; this location lends // it its own pool source, vault, settings and request capture. const cacheKeepSettings = cacheKeepSettingsOf(storage, configPath) @@ -967,14 +1044,10 @@ export async function setupOpenAIAuth( ...options.cacheKeep, }, ) + cleanup.defer('cache keep', () => cacheKeep.release()) snapshot?.onChange(() => { cacheKeep.configure(cacheKeepSettingsOf(storage, configPath)) }) - using _cacheKeepRollback = { - [Symbol.dispose]() { - if (!setupComplete) void cacheKeep.release() - }, - } const openai = createOpenAIAdapter({ cacheWarming: (sessionId) => cacheKeepWarming(paths(), sessionId), limits, @@ -998,6 +1071,7 @@ export async function setupOpenAIAuth( now, log, }) + cleanup.defer('adapter', () => openai.dispose()) setupTrace('before installPoolHooks', directory) const installation = await installPoolHooks( ctx, @@ -1008,12 +1082,14 @@ export async function setupOpenAIAuth( mirror, (sessionID) => cacheKeep.forget(sessionID), ) + cleanup.defer('pool hooks', () => installation.dispose()) setupTrace('after installPoolHooks', directory) openai.attach(installation) setupTrace('before session.hook (prompt)', directory) const turns = await ctx.session.hook('prompt', (draft) => { openai.beginTurn(draft.sessionID) }) + cleanup.defer('prompt hook', () => turns.dispose()) setupTrace('after session.hook (prompt)', directory) /** Waits for a migration run when the install has not migrated yet. */ @@ -1061,9 +1137,11 @@ export async function setupOpenAIAuth( label: 'ChatGPT (openai-auth account pool)', vault: vaultLoginMethod(vault), }) + cleanup.defer('auth methods', () => methods.dispose()) setupTrace('after registerOpenCode2AuthMethods', directory) setupTrace('before registerCodexModelRules', directory) const models = await registerCodexModelRules(ctx) + cleanup.defer('model rules', () => models.dispose()) setupTrace('after registerCodexModelRules', directory) if (options.controlPlane && (!ctx.command || !ctx.location)) throw new Error( @@ -1144,11 +1222,13 @@ export async function setupOpenAIAuth( }), ) : undefined + if (controlPlane) cleanup.defer('control plane', controlPlane) setupTrace('after installControlPlane', directory) // A deleted session's pin, remembered account, mirror and keep-warm target // go with it. const abort = new AbortController() + cleanup.defer('session events', () => abort.abort()) void (async () => { try { for await (const event of ctx.event.subscribe({ signal: abort.signal })) { @@ -1166,51 +1246,5 @@ export async function setupOpenAIAuth( } })() - setupComplete = true setupTrace('setup exit', directory) - return async () => { - closing = true - abort.abort() - openai.dispose() - // Drop this location's hold first, so no warm reads the pool source or - // vault released below. The last hold stops the manager at once; its - // warm in flight is joined within the shutdown limit below. - const cacheKeepReleased = cacheKeep.release() - await controlPlane?.() - lifecycle?.dispose() - await limits.dispose() - await sidebar.release() - await Promise.allSettled([ - installation.dispose(), - turns.dispose(), - methods.dispose(), - models.dispose(), - ]) - // Join account-pool transfers and reads after stopping new slot adoptions. - // Their reloads must finish before releasing this host's state. Also finish - // saving the sessions this location created or deleted, starting a save - // still inside its delay now, so a restart right after still finds their - // thread ids. Preserve the five-second shutdown - // limit for an unresponsive provider, login slot or session-file lock. - let settleTimer: ReturnType | undefined - try { - await Promise.race([ - Promise.all([ - lifecycle?.idle(), - source.settled(), - codex.store?.settled(), - cacheKeepReleased, - ]), - new Promise((resolve) => { - settleTimer = setTimeout(resolve, SETTLE_ON_DISPOSE_MS) - settleTimer.unref?.() - }), - ]) - } finally { - clearTimeout(settleTimer) - disposeSettings() - await vaultLease.release() - await heartbeat?.release() - } - } } From 27ec9c7f1874561678d0144a20c1db9945ac73c1 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:59:06 +0100 Subject: [PATCH 9/9] mason: protect moved OpenCode runtime files on startup Refuse an explicit state override that points back to the tokenless vault left after a completed move. Validate layout markers and direct users to restore a marker for this config folder when state-home files might be the only surviving copies. Use a state-only fixture for the atomic-temp override test so it still checks cleanup with a valid override; the old full-vault fixture would now hit the intentional startup refusal. --- docs/configuration.md | 8 +- packages/opencode/src/core/runtime-layout.ts | 95 +++++++++++++++---- .../opencode/src/tests/runtime-layout.test.ts | 84 +++++++++++++++- 3 files changed, 160 insertions(+), 27 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 5c58aa44..e893c094 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -118,7 +118,7 @@ On OpenCode, `log_level` accepts `"error"`, `"warn"`, `"info"`, `"debug"`, `"tra | Environment variable | Purpose | | --- | --- | | `OPENCODE_OPENAI_AUTH_FILE` | Full path of the config file, which also holds the account store. | -| `OPENCODE_OPENAI_AUTH_STATE_FILE` | Full path of the account state file. The vault folder `openai-auth-vault/` sits next to it. By default the state file is `openai-auth-state.json` in the plugin's state folder (see [Where the files live](#where-the-files-live)). When `OPENCODE_OPENAI_AUTH_FILE` names a custom config file, the default is `.state.json` next to it, or `openai-auth-state.json` when the custom file is named `openai-auth.json`. The plugin never moves a state file you name here. It must not be the config file itself. | +| `OPENCODE_OPENAI_AUTH_STATE_FILE` | Full path of the account state file. The vault folder `openai-auth-vault/` sits next to it. By default the state file is `openai-auth-state.json` in the plugin's state folder (see [Where the files live](#where-the-files-live)). When `OPENCODE_OPENAI_AUTH_FILE` names a custom config file, the default is `.state.json` next to it, or `openai-auth-state.json` when the custom file is named `openai-auth.json`. The plugin never moves a state file you name here. It must not be the config file itself. After the runtime-file move, the old default path in OpenCode's config folder can point to a vault with only leftover enrollment state and no token; remove the override or point it at the state file in the runtime folder. | | `OPENCODE_CONFIG_DIR`, `XDG_CONFIG_HOME` | Where the config directory is, as for OpenCode itself. | | `XDG_STATE_HOME` | Base of the plugin's state folder; `~/.local/state` when unset. | | `OPENCODE_OPENAI_AUTH_LOG_LEVEL`, `OPENCODE_OPENAI_AUTH_LOG_FILE` | Log level and log file; see [Troubleshooting](troubleshooting.md#logging). | @@ -167,7 +167,7 @@ The plugin's state folder is `cortexkit/openai-auth` under `XDG_STATE_HOME`, or Each runtime folder holds `config-dir.json`, which names the config folder it belongs to. If it names a different one, the plugin refuses to start and leaves the folder alone. The plugin creates these folders and files owner-only: mode `0700` for folders and `0600` for files on Linux and macOS, and an access list that grants only your user on Windows. -`OPENCODE_OPENAI_AUTH_STATE_FILE`, and a custom config file named by `OPENCODE_OPENAI_AUTH_FILE`, keep the state file and its vault folder where they say (see the table above), and the plugin never moves or deletes them. +`OPENCODE_OPENAI_AUTH_STATE_FILE`, and a custom config file named by `OPENCODE_OPENAI_AUTH_FILE`, keep the state file and its vault folder where they say (see the table above), and the plugin never moves or deletes them. After the move, an explicit state-file override to the old default in OpenCode's config folder still selects the old vault folder. If that folder contains only the enrollment state the move left behind and the enrolled vault is in the runtime folder, startup refuses with both paths. Remove `OPENCODE_OPENAI_AUTH_STATE_FILE` or set it to `openai-auth-state.json` in the runtime folder. ### The move from OpenCode's config folder @@ -177,7 +177,7 @@ Only an OpenCode started without `OPENCODE_OPENAI_AUTH_STATE_FILE` and without a The move waits while any other OpenCode process could still write the old files, because a sign-in token written to the old folder after the move would be lost. Such a process is one running an older version of the plugin, or one that started while such a process was running. While the move waits, the plugin keeps using the old files and logs once: "openai-auth keeps its files in OpenCode's config folder until every running OpenCode using it has restarted on this version." A process that starts while the move must wait also keeps the old files for its whole life, so restarting OpenCode processes one at a time can keep the move waiting. **To let it happen, close every OpenCode on the machine, then start OpenCode again.** Only OpenCode moves these files; Pi keeps its own files where they are. -If the move fails before writing `layout.json`, for example because the disk is full, the plugin keeps using the old files, logs the error once, and tries again at the next start. If it cannot record that it uses the old files, or cannot use or read its state folder at all, it refuses to start and names the folder and the error, rather than run where other OpenCode processes cannot see it. A malformed `layout.json` also refuses the start: the copies cannot be trusted. The refusal names the marker path and asks you to delete `layout.json` and restart OpenCode. Before doing so, check that the old runtime files are still in OpenCode's config folder. A marker damaged after completed cleanup does not prove the old files remain; keep the runtime folder intact if no old copies exist. +If the move fails before writing `layout.json`, for example because the disk is full, the plugin keeps using the old files, logs the error once, and tries again at the next start. If it cannot record that it uses the old files, or cannot use or read its state folder at all, it refuses to start and names the folder and the error, rather than run where other OpenCode processes cannot see it. A damaged or unrecognised `layout.json` also refuses the start. If the runtime folder holds runtime files, keep them in place and restore a backup of `layout.json` for that OpenCode config folder before restarting. Do not delete the marker: the next start could use the old folder instead. The plugin tells you to delete the marker and restart only if it finds no runtime files in the runtime folder. After the marker is written, an old state file or any vault file whose bytes differ from its new copy is a credential conflict, both during the move's cleanup and when a later start retries cleanup. An old credential file that matches its copy but cannot be removed yet (on Windows, another program may still have it open) is logged once, and the next start tries the removal again. An old state or vault file that reappears after a finished move is also a conflict, even if its bytes match. The one exception is the vault enrollment state file of an approved enrollment: the move removes the old token but leaves that file in the old vault folder, byte for byte as it moved. Later starts accept that file there as long as it still says this OpenCode's enrollment is approved, or blocked only because its token is missing, and no token file is in the old vault folder. An older version that runs after the move rewrites the file that way, and the file holds no secret. Anything else there, such as an enrollment request in progress, a file that cannot be read as an enrollment state, another enrollment's name, or a token file next to it, is a conflict. Disconnect removes the file. The plugin refuses to start and names both paths: keep the newer one, delete the other, and restart OpenCode. It never merges the copies or chooses by timestamp: the old copy may hold the only live successor to a single-use OAuth refresh token. A file named by this process's override remains its own and is not a conflict. Differing or reappeared session files are left alone with a warning; reappeared sessions are also shown once in the Diagnostics section of `/openai`. @@ -192,7 +192,7 @@ A version from before the move looks only in OpenCode's config folder, so after - move `openai-auth-state.json`, `openai-auth-vault/` and the sessions files from the runtime folder back into OpenCode's config folder, and delete `layout.json` from the runtime folder so a later upgrade moves them again; - or set `OPENCODE_OPENAI_AUTH_STATE_FILE` to the state file in the runtime folder, for example `~/.local/state/cortexkit/openai-auth/opencode/openai-auth-state.json`. The older version then reads the state file and the vault folder from there. -Close every OpenCode process before switching versions or moving credentials. Do not run an older version against the old copies while a newer version uses the runtime folder: refreshing either copy can spend the token held by the other. If the old version recreates the state file or vault files in the config folder, a later upgrade refuses to start until you resolve the two-path conflict above. Delete `layout.json` only for the explicit move-back procedure or the malformed-marker recovery, not to bypass a credential conflict. +Close every OpenCode process before switching versions or moving credentials. Do not run an older version against the old copies while a newer version uses the runtime folder: refreshing either copy can spend the token held by the other. If the old version recreates the state file or vault files in the config folder, a later upgrade refuses to start until you resolve the two-path conflict above. Delete `layout.json` only for the explicit move-back procedure or when the damaged-marker message says there are no runtime files in the runtime folder, not to bypass a credential conflict. ## Pi diff --git a/packages/opencode/src/core/runtime-layout.ts b/packages/opencode/src/core/runtime-layout.ts index ba075134..1d407ff2 100644 --- a/packages/opencode/src/core/runtime-layout.ts +++ b/packages/opencode/src/core/runtime-layout.ts @@ -238,7 +238,7 @@ export interface RuntimeLayoutOptions { interface LayoutMarker { version: 1 /** The identity of the config folder the files came from. */ - oldDir?: string + oldDir: string /** Set once the old files were removed or knowingly left in place. */ oldFilesRemoved?: boolean /** @@ -414,6 +414,14 @@ async function decide( ) const fence = options.fence ?? defaultFence(options.version) + const readOwnMarker = async () => { + const found = await readMarker(location, files) + await assertOwnFolder(location, found) + if (found?.oldFilesRemoved && found.keptVaultState) + await refuseKeptVaultOverride(location, files) + return found + } + const stateHome = async (): Promise => { await recordProcessLayout({ key: location.key, @@ -425,8 +433,7 @@ async function decide( } // Read-only first: whose folder this is, and whether the move is done. - let marker = await readMarker(markerPath, stateDir) - await assertOwnFolder(location, marker) + let marker = await readOwnMarker() if (marker?.oldFilesRemoved && !overrideInDestination) { await noticeReappearedFiles(location, files, overrides, marker, log) // A move that stopped right after its last marker write left its @@ -453,7 +460,7 @@ async function decide( ) } catch (error) { // Only an existing marker settles the layout without the lock. - marker = await readMarker(markerPath, stateDir) + marker = await readOwnMarker() if (marker && !overrideInDestination) return stateHome() throw new RuntimeLayoutRefusal(stateDir, errorClass(error)) } @@ -475,8 +482,7 @@ async function decide( } try { - marker = await readMarker(markerPath, stateDir) - await assertOwnFolder(location, marker) + marker = await readOwnMarker() if (!aliased) await writeOwnerNote(location) if (overrideInDestination) { @@ -549,8 +555,7 @@ async function decide( } catch (error) { if (error instanceof RuntimeLayoutRefusal) throw error // Once the marker write began, the marker on disk decides. - if (markerStarted && (await readMarker(markerPath, stateDir))) - return await stateHome() + if (markerStarted && (await readOwnMarker())) return await stateHome() logOnce(`${location.key}\0failed`, () => log.warn( "openai-auth's runtime files stay in OpenCode's config folder: moving them failed; the move is tried again at the next start", @@ -952,6 +957,40 @@ async function vaultModeWithoutToken( } } +/** Refuse an explicit state path that leads back to the enrollment left for older versions. */ +async function refuseKeptVaultOverride( + location: RuntimeLayoutLocation, + files: LayoutFiles, +): Promise { + const override = process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim() + if ( + !override || + !accountPathsCollide(vaultStateDir(override), files.vault.old) + ) + return + + const old = vaultPaths(files.vault.old, 'opencode') + const names = await folderFiles(files.vault.old).catch(() => []) + if (names.length !== 1 || names[0] !== basename(old.statePath)) return + if (!(await vaultModeWithoutToken(old))) return + + const moved = await readClaustrumEnrollmentStatus( + vaultPaths(files.vault.next, 'opencode'), + OPENCODE_ENROLLMENT_NAME, + ).catch(() => undefined) + if ( + moved?.state !== 'approved' || + moved.proposedName !== OPENCODE_ENROLLMENT_NAME + ) + return + + throw new RuntimeLayoutRefusal( + location.stateHomeDir, + 'tokenless-vault-override', + `openai-auth cannot start: OPENCODE_OPENAI_AUTH_STATE_FILE points to ${override}, where the old vault contains only the kept enrollment state. Remove the override or point it at ${files.state.next}, then restart OpenCode.`, + ) +} + /** * The SHA-256 of the enrollment state file this move copied, when that state * keeps the host in vault mode once the old token is gone: approved, or @@ -1021,11 +1060,7 @@ export async function removeMovedVaultStateLeftover( const location = runtimeLayoutLocation() const files = layoutFiles(location) if (resolve(vaultDir) !== resolve(files.vault.next)) return - const stateDir = location.stateHomeDir - const marker = await readMarker( - join(stateDir, RUNTIME_LAYOUT_MARKER_FILE), - stateDir, - ) + const marker = await readMarker(location, files) if (!marker?.keptVaultState || marker.oldDir !== location.key) return const leftover = vaultStateFile(files).old if (!(await isVaultStateLeftover(files, marker.keptVaultState))) return @@ -1410,9 +1445,11 @@ async function noticeReappearedFiles( * briefly, then refuse the start: they prove neither presence nor absence. */ async function readMarker( - path: string, - stateDir: string, + location: RuntimeLayoutLocation, + files: LayoutFiles, ): Promise { + const stateDir = location.stateHomeDir + const path = join(stateDir, RUNTIME_LAYOUT_MARKER_FILE) let text: string | undefined let failure: unknown for (let attempt = 0; attempt < MARKER_READ_ATTEMPTS; attempt++) { @@ -1431,21 +1468,37 @@ async function readMarker( throw new RuntimeLayoutRefusal(stateDir, errorClass(failure)) try { const value = JSON.parse(text) as Partial | null - if (value && typeof value === 'object' && !Array.isArray(value)) + if ( + value && + typeof value === 'object' && + !Array.isArray(value) && + value.version === 1 && + typeof value.oldDir === 'string' && + value.oldDir.length > 0 && + (value.oldFilesRemoved === undefined || + typeof value.oldFilesRemoved === 'boolean') && + (value.keptVaultState === undefined || + (typeof value.keptVaultState === 'string' && + SHA256_HEX.test(value.keptVaultState))) + ) return { version: 1, - ...(typeof value.oldDir === 'string' ? { oldDir: value.oldDir } : {}), + oldDir: value.oldDir, ...(value.oldFilesRemoved === true ? { oldFilesRemoved: true } : {}), - ...(typeof value.keptVaultState === 'string' && - SHA256_HEX.test(value.keptVaultState) + ...(value.keptVaultState ? { keptVaultState: value.keptVaultState } : {}), } } catch {} + // Files in the destination may be the only surviving copies. Their presence + // does not prove the move completed or authorize rebuilding the marker. + const destination = await destinationFiles(files).catch(() => undefined) throw new RuntimeLayoutRefusal( stateDir, 'malformed-marker', - `openai-auth cannot start: ${path} is malformed. The old files are still in OpenCode's config folder. Delete layout.json, then restart OpenCode.`, + destination?.length === 0 + ? `openai-auth cannot start: ${path} is damaged or unrecognised. No runtime files were found in ${stateDir}. Delete layout.json, then restart OpenCode.` + : `openai-auth cannot start: ${path} is damaged or unrecognised. Keep the runtime files in ${stateDir}. Restore a backup of layout.json for this OpenCode config folder before restarting. Do not delete the marker.`, ) } @@ -1458,7 +1511,7 @@ async function assertOwnFolder( marker: LayoutMarker | undefined, ): Promise { const stateDir = location.stateHomeDir - if (marker?.oldDir !== undefined && marker.oldDir !== location.key) + if (marker && marker.oldDir !== location.key) throw foreignFolder(stateDir, location.key) let text: string try { diff --git a/packages/opencode/src/tests/runtime-layout.test.ts b/packages/opencode/src/tests/runtime-layout.test.ts index f71193cf..76db2fc0 100644 --- a/packages/opencode/src/tests/runtime-layout.test.ts +++ b/packages/opencode/src/tests/runtime-layout.test.ts @@ -986,7 +986,7 @@ describe('moving an existing layout', () => { writePrivate(path, text) await expect(prepare()).rejects.toMatchObject({ name: 'RuntimeLayoutRefusal', - message: `openai-auth cannot start: ${path} is malformed. The old files are still in OpenCode's config folder. Delete layout.json, then restart OpenCode.`, + message: `openai-auth cannot start: ${path} is damaged or unrecognised. No runtime files were found in ${runtimeDir()}. Delete layout.json, then restart OpenCode.`, }) expect(present(configDir(), files)).toEqual(files) expect(present(runtimeDir(), files)).toEqual(absent(files)) @@ -1002,6 +1002,42 @@ describe('moving an existing layout', () => { expect(present(configDir(), oldLayout())).toEqual(oldLayout()) }) + it.each([ + ['syntax damage', undefined], + ['unknown version', { version: 2 }], + ['missing oldDir', { oldDir: undefined }], + ['non-boolean cleanup flag', { oldFilesRemoved: 'true' }], + ['invalid kept state hash', { keptVaultState: 'not a hash' }], + ] as const)( + 'damaged marker after a completed move protects the state-home files: %s', + async (_label, fields) => { + const files = oldLayout() + seed(configDir(), files) + expect(await prepare()).toBe('state-home') + const path = join(runtimeDir(), 'layout.json') + const backup = readFileSync(path, 'utf8') + const damaged = fields ? JSON.stringify({ ...marker(), ...fields }) : '{' + writePrivate(path, damaged) + resetProcess() + + await expect(prepare()).rejects.toMatchObject({ + name: 'RuntimeLayoutRefusal', + message: `openai-auth cannot start: ${path} is damaged or unrecognised. Keep the runtime files in ${runtimeDir()}. Restore a backup of layout.json for this OpenCode config folder before restarting. Do not delete the marker.`, + }) + expect(present(configDir(), files)).toEqual(leftAfterMove(files)) + expect(present(runtimeDir(), files)).toEqual(files) + expect(readFileSync(path, 'utf8')).toBe(damaged) + + writePrivate(path, backup) + resetProcess() + expect(await prepare()).toBe('state-home') + expect(getAccountPaths().statePath).toBe( + join(runtimeDir(), 'openai-auth-state.json'), + ) + expect(present(runtimeDir(), files)).toEqual(files) + }, + ) + it('a layout lease lost before the marker writes no marker and refuses to run unregistered', async () => { const files = oldLayout() seed(configDir(), files) @@ -1381,6 +1417,50 @@ const APPROVED_LATER = (oldLayout()[VAULT_STATE] as string).replace( ) describe('an approved vault enrollment and older versions', () => { + it.each(['approved', 'blocked for missing token'])( + 'refuses a state override that selects only the kept enrollment after a completed move: %s', + async (shape) => { + const files = oldLayout() + seed(configDir(), files) + expect(await prepare()).toBe('state-home') + expect(marker()?.oldFilesRemoved).toBe(true) + expect(present(configDir(), files)).toEqual(leftAfterMove(files)) + expect(present(runtimeDir(), files)).toEqual(files) + if (shape !== 'approved') + writePrivate(join(configDir(), VAULT_STATE), BLOCKED_MISSING_TOKEN) + const oldStatePath = join(configDir(), 'openai-auth-state.json') + const newStatePath = join(runtimeDir(), 'openai-auth-state.json') + process.env.OPENCODE_OPENAI_AUTH_STATE_FILE = oldStatePath + resetProcess() + + const result = await prepare().then( + (layout) => ({ layout, statePath: getAccountPaths().statePath }), + (error: unknown) => error, + ) + expect(result).toMatchObject({ + name: 'RuntimeLayoutRefusal', + message: `openai-auth cannot start: OPENCODE_OPENAI_AUTH_STATE_FILE points to ${oldStatePath}, where the old vault contains only the kept enrollment state. Remove the override or point it at ${newStatePath}, then restart OpenCode.`, + }) + + process.env.OPENCODE_OPENAI_AUTH_STATE_FILE = newStatePath + resetProcess() + await prepare() + expect(getAccountPaths().statePath).toBe(newStatePath) + expect(present(runtimeDir(), files)).toEqual(files) + }, + ) + + it('honours the old state path override if the state-home enrollment has no token either', async () => { + seed(configDir(), oldLayout()) + expect(await prepare()).toBe('state-home') + rmSync(join(runtimeDir(), VAULT_TOKEN)) + const oldStatePath = join(configDir(), 'openai-auth-state.json') + process.env.OPENCODE_OPENAI_AUTH_STATE_FILE = oldStatePath + resetProcess() + expect(await prepare()).toBe('state-home') + expect(getAccountPaths().statePath).toBe(oldStatePath) + }) + it('the move removes the old token but leaves the old state, so an older version stays in vault mode', async () => { const files = oldLayout() seed(configDir(), files) @@ -1626,7 +1706,7 @@ describe('the layout lease before every removal', () => { }) it('a finished move leaves atomic-write temps alone while a legacy writer is alive or a path is overridden', async () => { - seed(configDir(), oldLayout()) + writePrivate(join(configDir(), 'openai-auth-state.json'), '{}\n') await prepare() resetProcess() const temp = join(