From 775fff8d994590544f4344d8b5742b98c9f3fc83 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:08:53 +0100 Subject: [PATCH 1/2] mason: recover OC2 vault HTTP 401s and pair routing waits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the installer’s same-account retry hook with the exact attributed HTTP response and common-auth’s existing rotation check. Terminal 401s retain one receipt report path and do not become quota limits. Pair reported routing holds and placement retries on wake, cancellation, and turn clear. --- .../tests/opencode2-routing-client.test.ts | 132 ++++++++++ .../src/tests/opencode2-vault-report.test.ts | 234 +++++++++++++++++- packages/opencode/src/v2/adapter.ts | 222 +++++++++++++++-- packages/opencode/src/v2/setup.ts | 19 +- 4 files changed, 581 insertions(+), 26 deletions(-) diff --git a/packages/opencode/src/tests/opencode2-routing-client.test.ts b/packages/opencode/src/tests/opencode2-routing-client.test.ts index d7cd6e81..41115a17 100644 --- a/packages/opencode/src/tests/opencode2-routing-client.test.ts +++ b/packages/opencode/src/tests/opencode2-routing-client.test.ts @@ -490,6 +490,138 @@ test('aborting the HTTP request during the first placement wait stops before ano } }) +test.each(['resumed', 'cancelled', 'abandoned'] as const)( + 'short placement-refusal retry pairs the wait when %s', + async (outcome) => { + const at = 1_900_000_000_000 + const report = mock((_report: Record) => {}) + const env = await placementRequest( + [shortPlacementRefusal, { account_id: 'account-b' }], + { report, now: () => at }, + ) + try { + const sent = env.send() + const { wake } = await env.waitBeforeSend(sent) + const start = { + kind: 'wait', + phase: 'start', + reason: 'account_free', + next_ms: at + 3000, + wait_id: expect.any(String), + attempt: 1, + message: 'Waiting for an account to come free', + } + expect(report.mock.calls.map(([value]) => value)).toEqual([start]) + if (outcome === 'resumed') { + wake() + expect(await sent).toBe('Bearer vault:b-token') + } else { + if (outcome === 'cancelled') env.controller.abort() + else env.openai.beginTurn(env.request.sessionID) + await expect(sent).rejects.toMatchObject( + outcome === 'cancelled' + ? { name: 'AbortError' } + : placementRefusalError, + ) + wake() + expect(env.accountFor).toHaveBeenCalledTimes(1) + expect(env.providerFetch).not.toHaveBeenCalled() + } + expect(report.mock.calls.map(([value]) => value)).toEqual([ + start, + { ...report.mock.calls[0]![0], phase: 'end', outcome }, + ]) + } finally { + await env.dispose() + } + }, +) + +test.each(['resumed', 'cancelled', 'abandoned'] as const)( + 'routing same-account hold pairs the wait when %s', + async (outcome) => { + let now = 1_900_000_000_000 + const at = now + const reports: Record[] = [] + Reflect.set(globalThis, key, () => ({ + accountFor: async () => ({ account_id: 'account-b' }), + report: (report: Record) => { + if (report.kind === 'wait') reports.push(report) + }, + })) + const env = fixture(true, 'ordered', () => now) + const host = fakeOpenCode2Host() + const installation = await installPoolHooks(host.ctx, env.openai.adapter, { + warn() {}, + }) + env.openai.attach(installation) + const { sessionID } = env.request + const requestScope = scope(sessionID) + const send = () => + host.fire('http.request', { + ...requestScope, + request: new Request('https://codex.test/responses', { + headers: { authorization: `Bearer ${placeholderSecret('openai')}` }, + }), + }) + try { + const { request } = await send() + const response = await host.fire('http.response', { + ...requestScope, + request, + response: new Response('{}', { + status: 403, + headers: { 'retry-after-ms': '3000' }, + }), + }) + await response.response.text() + const retry = await host.fire('retry', { + ...requestScope, + attempt: 1, + decision: { retry: false }, + error: { type: 'api', status: 403, message: '{}' }, + }) + const decision: { retry: boolean; delay?: number } = retry.decision + expect(decision).toEqual({ retry: true, delay: 3000 }) + expect(reports).toEqual([ + { + kind: 'wait', + phase: 'start', + reason: 'account_limit', + next_ms: at + 3000, + wait_id: expect.any(String), + attempt: 1, + message: 'Waiting for the account limit to reset', + }, + ]) + if (outcome === 'resumed') { + now += 3000 + expect((await send()).request.headers.get('authorization')).toBe( + 'Bearer vault:b-token', + ) + expect(env.authorized).toEqual(['vault:b', 'vault:b']) + } else { + if (outcome === 'cancelled') + await host.publish('session.status', { + sessionID, + status: { type: 'idle' }, + }) + else env.openai.beginTurn(sessionID) + expect(env.authorized).toEqual(['vault:b']) + } + expect(reports).toEqual([ + reports[0]!, + { ...reports[0], phase: 'end', outcome }, + ]) + env.openai.beginTurn(sessionID) + expect(reports).toHaveLength(2) + } finally { + await installation.dispose() + env.openai.dispose() + } + }, +) + test('capacity placement re-asks with the same id, reports account_free, and uses a fresh id next turn', async () => { const start = Date.now() let now = start diff --git a/packages/opencode/src/tests/opencode2-vault-report.test.ts b/packages/opencode/src/tests/opencode2-vault-report.test.ts index e004f325..12d946fd 100644 --- a/packages/opencode/src/tests/opencode2-vault-report.test.ts +++ b/packages/opencode/src/tests/opencode2-vault-report.test.ts @@ -3,13 +3,12 @@ // receipt; a 401 on a local pool account is the pool's own business. The vault // rotates a refreshable credential on every report it applies. The shared vault // consumer also refuses a report for a send it never authorized, so this check -// is the first of two layers: without it the adapter would still log a false -// "vault account answered 401" warning and re-read the vault's account list. +// is the first of two layers and avoids reading the vault's roster for a local 401. // // The vault here is a stand-in that records every call the adapter makes to // it; the adapter runs behind the real installer on a fake OpenCode 2 host. -import { describe, expect, it, spyOn } from 'bun:test' +import { describe, expect, it, mock, spyOn } from 'bun:test' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -17,6 +16,7 @@ import { ClaustrumConsumer, type ClaustrumScopedAttempt, } from '@cortexkit/common-auth/claustrum' +import { createSessionActivityStore } from '@cortexkit/common-auth/limits' import { installOpenCode2Auth, placeholderSecret, @@ -27,10 +27,16 @@ import { type AccountStorage, OpenAiVault, } from '@cortexkit/openai-auth-core/internal' +import type { OpenCodeLimitSource } from '../core/limit-source' import type { PoolView } from '../core/pool-account-source' import { createOpenAIAdapter, type PoolAccess } from '../v2/adapter' import { SessionPins } from '../v2/pins' +import { installPoolHooks } from '../v2/setup' import { fakeOpenCode2Host, scope } from './fixtures/opencode2-host' +import { + restoreRoutingAccessor, + routingKey, +} from './fixtures/opencode2-routing' const PLACEHOLDER = placeholderSecret('openai') const HOUR = 3600_000 @@ -192,6 +198,228 @@ describe('vault failure reports on OpenCode 2', () => { }) }) +async function recoveryFixture() { + const requestScope = scope('session-401') + const report = mock((_payload: unknown) => {}) + Reflect.set(globalThis, routingKey, () => ({ report })) + let current: ClaustrumScopedAttempt | undefined = receipt() + const authorize = mock(async () => current) + const reportFailure = mock( + async (_receipt: ClaustrumScopedAttempt, _status: number) => {}, + ) + const enqueue = mock(() => {}) + const dropSignal = mock(() => {}) + const debug = mock(() => {}) + const binding = { + account: { namespace: 'vault', accountId: VAULT_ROUTE, incarnation: '1' }, + } + const registry = {} + const limits = { + activity: createSessionActivityStore(), + forRequest: async () => undefined, + bindings: () => [binding], + accountKey: (id: string) => + id === VAULT_ROUTE ? binding.account : undefined, + marks: () => new Map(), + owner: () => ({ + registry, + enqueue, + dropSignal, + observe: () => ({ binding, registry, baseRevision: 1 }), + afterProbe() {}, + }), + } as unknown as OpenCodeLimitSource + const openai = createOpenAIAdapter({ + source: poolSource, + storage: async () => ({ + version: 1, + accounts: [], + routing: { mode: 'fallback-first' }, + }), + pins: new SessionPins(), + limits, + log: { debug, warn() {} }, + vault: { + routes: () => [ + { + id: VAULT_ROUTE, + credentialId: VAULT_ROUTE, + kind: 'oauth', + identity: 'chatgpt-vault', + quota: healthyQuota(), + }, + ], + identities: () => new Set(['chatgpt-vault']), + enrolled: () => true, + authority: async () => 'vault', + snapshot: () => undefined, + authorize, + reportFailure, + recordSnapshot: async () => {}, + reportUsage() {}, + requestReading() {}, + grantReach: () => undefined, + name: 'openai-auth-opencode', + }, + }) + const host = fakeOpenCode2Host() + const installation = await installPoolHooks(host.ctx, openai.adapter, { + warn() {}, + }) + openai.attach(installation) + const dispatched: Request[] = [] + return { + authorize, + reportFailure, + report, + enqueue, + dropSignal, + debug, + dispatched, + setReceipt(next: ClaustrumScopedAttempt | undefined) { + current = next + }, + async send(label: string) { + const draft = await host.fire('http.request', { + ...requestScope, + request: new Request('https://codex.test/responses', { + method: 'POST', + body: JSON.stringify({ + model: 'gpt-5.5', + input: [{ role: 'user', content: label }], + }), + headers: { authorization: `Bearer ${PLACEHOLDER}` }, + }), + }) + dispatched.push(draft.request) + return draft.request + }, + async answer(request: Request) { + const { response } = await host.fire('http.response', { + ...requestScope, + request, + // A misleading body must not promote a credential refusal to a quota mark. + response: Response.json( + { + error: { type: 'usage_limit_reached', message: 'private details' }, + }, + { status: 401 }, + ), + }) + return response + }, + async retry(attempt: number, retry = false) { + const result = await host.fire('retry', { + ...requestScope, + attempt, + decision: retry ? { retry: true, delay: 1 } : { retry: false }, + error: { type: 'api', status: 401, message: 'HTTP 401' }, + }) + return result.decision + }, + async dispose() { + await installation.dispose() + openai.dispose() + restoreRoutingAccessor() + }, + } +} + +it('retries the attributable vault HTTP 401 once with a rotated receipt, even with another send in flight', async () => { + const env = await recoveryFixture() + try { + const first = await env.send('first') + env.setReceipt({ + ...receipt(), + recordVersion: 8, + accessToken: 'overlapping-token', + }) + const overlap = await env.send('overlap') + expect(overlap.headers.get('authorization')).toBe( + 'Bearer overlapping-token', + ) + // Version 8 is a rotation for the failed request, not for the newer in-flight send. + expect((await env.answer(first)).status).toBe(401) + expect(await env.retry(1)).toEqual({ retry: true, delay: 0 }) + expect(env.authorize).toHaveBeenCalledTimes(3) + expect(env.reportFailure).not.toHaveBeenCalled() + + const replay = await env.send('first') + expect(replay.headers.get('authorization')).toBe('Bearer overlapping-token') + expect(replay.headers.get('chatgpt-account-id')).toBe('chatgpt-vault') + expect(await replay.text()).toBe(await first.text()) + expect(env.authorize).toHaveBeenCalledTimes(3) + + env.setReceipt({ + ...receipt(), + recordVersion: 9, + accessToken: 'third-token', + }) + const terminal = await env.answer(replay) + expect(terminal.status).toBe(401) + expect(await terminal.json()).toEqual({ + error: { + message: 'request refused: no account with a usable credential', + }, + }) + expect(await env.retry(2, true)).toEqual({ retry: false }) + expect(env.authorize).toHaveBeenCalledTimes(3) + expect(env.dispatched).toEqual([first, overlap, replay]) + expect(env.reportFailure.mock.calls).toEqual([ + [expect.objectContaining({ recordVersion: 8 }), 401], + ]) + expect(env.enqueue).not.toHaveBeenCalled() + expect(env.dropSignal).not.toHaveBeenCalled() + expect(env.debug).not.toHaveBeenCalledWith( + 'pool row refused the request', + expect.anything(), + ) + const reports = env.report.mock.calls.map(([value]) => value) + expect(reports).toEqual([ + expect.objectContaining({ + kind: 'billing', + status: 401, + outcome: 'failed', + }), + expect.objectContaining({ + kind: 'billing', + status: 401, + outcome: 'failed', + }), + ]) + } finally { + await env.dispose() + } +}) + +it.each([ + ['unchanged receipt', receipt()], + ['failed re-authorization', undefined], + [ + 'different login', + { ...receipt(), recordVersion: 8, credentialId: 'different-login' }, + ], +] as const)( + 'vault HTTP 401 with %s is terminal and reports the sent receipt once', + async (_label, next) => { + const env = await recoveryFixture() + try { + const request = await env.send('no replay') + env.setReceipt(next) + const terminal = await env.answer(request) + expect(terminal.status).toBe(401) + expect(await env.retry(1, true)).toEqual({ retry: false }) + expect(env.authorize).toHaveBeenCalledTimes(2) + expect(env.dispatched).toEqual([request]) + expect(env.reportFailure.mock.calls).toEqual([ + [expect.objectContaining({ recordVersion: 7 }), 401], + ]) + } finally { + await env.dispose() + } + }, +) + describe('OpenCode 2 reply usage', () => { async function setup() { const directory = mkdtempSync(join(tmpdir(), 'opencode2-usage-')) diff --git a/packages/opencode/src/v2/adapter.ts b/packages/opencode/src/v2/adapter.ts index dda97bb6..40b35865 100644 --- a/packages/opencode/src/v2/adapter.ts +++ b/packages/opencode/src/v2/adapter.ts @@ -38,7 +38,10 @@ // attempt is reported to the vault against that record version. import { randomUUID } from 'node:crypto' -import type { ClaustrumScopedAttempt } from '@cortexkit/common-auth/claustrum' +import { + type ClaustrumScopedAttempt, + decideScopedRetryAfter401, +} from '@cortexkit/common-auth/claustrum' import { createRequestHistory, type LimitCandidate, @@ -173,6 +176,7 @@ export const DEFAULT_LIMIT_MARK_MS = 60_000 /** The WebSocket handshake supplies no request signal to cancel a capacity wait. */ const CAPACITY_WAIT_WITHOUT_SIGNAL_MS = 600_000 +const VAULT_HTTP_401 = 'vault_http_401' /** * The size every request counts for in sticky placement. OpenCode 2 hands @@ -692,11 +696,17 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { end: NonNullable> } >() + type EndWait = NonNullable> + const activeWaits = new Map>() + const routingHoldEnds = new WeakMap() + const routingWakeEnds = new WeakMap() + const clearedRoutingHolds = new WeakSet() const startWait = ( input: ChooseAccountInput, reason: 'account_limit' | 'account_free' | 'quota_reading', at: number, delayMs: number, + onEnd?: EndWait, ) => { if (!hasVaultRoutingAccessor()) return undefined const attempt = (waitCounts.get(input.sessionID) ?? 0) + 1 @@ -709,10 +719,21 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { : { nextMs: at + delayMs }), attempt, }) - if (end) waitCounts.set(input.sessionID, attempt) - return end + if (!end) return undefined + waitCounts.set(input.sessionID, attempt) + const waits = activeWaits.get(input.sessionID) ?? new Set() + activeWaits.set(input.sessionID, waits) + const finish: EndWait = (outcome) => { + if (!waits.delete(finish)) return + if (waits.size === 0) activeWaits.delete(input.sessionID) + end(outcome) + onEnd?.(outcome) + } + waits.add(finish) + return finish } const clearTurn = (sessionId: string) => { + for (const end of activeWaits.get(sessionId) ?? []) end('abandoned') waitCounts.delete(sessionId) for (const key of pendingWaits.keys()) if (JSON.parse(key)[0] === sessionId) pendingWaits.delete(key) @@ -797,6 +818,27 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { } const receiptKey = (scope: AccountRequest) => `${scope.sessionID}\u0000${scope.kind}\u0000${scope.accountId}` + // The installer carries the exact response marker into the retry hook, which + // otherwise has no request or attempt handle. The marker is not a quota signal. + const authMarkers = new WeakMap, LimitSignal>() + const seen401s = new WeakSet>() + const terminal401s = new WeakSet>() + // HTTP attempt-end runs before the host asks whether to retry. Keep a + // successful rotation only as long as that installer-owned marker survives. + const rotatedReceipts = new WeakMap< + LimitSignal, + { receipt: ClaustrumScopedAttempt; freeQuota: boolean; signal: AbortSignal } + >() + const authRetries = new Map< + string, + { + marker: LimitSignal + receipt: ClaustrumScopedAttempt + freeQuota: boolean + signal: AbortSignal + } + >() + const retriedWithRotation = new WeakSet() // The row each session's latest agent-loop request went to, which its // title, compaction and generate requests follow in the ordered modes. const sessionAccounts = deps.sessionAccounts ?? new SessionAccounts() @@ -1020,6 +1062,8 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { const chooseAccount = async ( input: ChooseAccountInput & { signal?: AbortSignal }, ): Promise => { + if (input.rerouteFrom?.limit.reason === VAULT_HTTP_401) + return { hostRetry: 'veto' } let ready: OpenAiLimitsRequest | undefined const modeAuthority = await vault?.authority() const storage = getResolvedSettingsView( @@ -1071,9 +1115,11 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { let at = now() let targets = 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) { routingWakes.delete(checkpoint) + routingWakeEnds.get(checkpoint)?.('resumed') const accountId = checkpoint.accountKey.accountId const receipt = vaultMode && @@ -1228,8 +1274,27 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { ? vaultRoutingPlacementRetryMs(answer) : undefined if (delayMs === undefined) throw routingRefusal() - await waitForRoutingRetry(delayMs, capacitySignal) - capacitySignal?.throwIfAborted() + const cleared = new AbortController() + const signal = capacitySignal + ? AbortSignal.any([capacitySignal, cleared.signal]) + : cleared.signal + const end = startWait( + input, + 'account_free', + now(), + delayMs, + (outcome) => { + if (outcome === 'abandoned') cleared.abort(routingRefusal()) + }, + ) + try { + await waitForRoutingRetry(delayMs, signal) + signal.throwIfAborted() + end?.('resumed') + } catch (error) { + end?.(input.signal?.aborted ? 'cancelled' : 'abandoned') + throw error + } at = now() targets = currentTargets(storage, at, vaultMode) continue @@ -1335,6 +1400,24 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { blockers: [], } routingWakes.set(checkpoint, receipt) + const end = startWait( + input, + 'account_limit', + checkpoint.decidedAt, + delayMs, + (outcome) => { + routingHoldEnds.delete(signal) + routingWakeEnds.delete(checkpoint) + if (outcome !== 'resumed') { + routingWakes.delete(checkpoint) + clearedRoutingHolds.add(checkpoint) + } + }, + ) + if (end) { + routingHoldEnds.set(signal, end) + routingWakeEnds.set(checkpoint, end) + } return { hold: { delayMs, @@ -2029,6 +2112,8 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { const { accountId } = request interrupted.delete(requestKey(request)) const choiceKey = receiptKey(request) + const authRetry = authRetries.get(choiceKey) + authRetries.delete(choiceKey) const keptChoice = keptChoices.get(choiceKey) keptChoices.delete(choiceKey) const commitChoice = () => { @@ -2110,13 +2195,27 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { }) } // In vault mode no pool row is sent with, so only the vault is asked. - const row = - vault && (await vault.authority()) !== 'local' - ? undefined - : source.peek().rows.find((candidate) => candidate.id === accountId) + const inVault = vault && (await vault.authority()) !== 'local' + if (authRetry) { + const route = inVault + ? vault.routes().find(({ id }) => id === accountId) + : undefined + if ( + route?.kind !== 'oauth' || + authRetry.signal.aborted || + (route.credentialId !== undefined && + route.credentialId !== authRetry.receipt.credentialId) || + (route.identity !== undefined && + route.identity !== authRetry.receipt.accountIdentity) + ) + throw refuse() + } + const row = inVault + ? undefined + : source.peek().rows.find((candidate) => candidate.id === accountId) if (!row && vault) { const key = receiptKey(request) - const choice = receipts.get(key) + const choice = authRetry ?? receipts.get(key) const receipt = choice?.receipt ?? (await vault.authorize(accountId)) receipts.delete(key) if (!receipt) { @@ -2134,6 +2233,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { receipt, ...(choice?.freeQuota ? { freeQuota: true } : {}), } + if (authRetry) retriedWithRotation.add(data) await prepareFeedback(data) commitChoice() return { @@ -2186,6 +2286,14 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { > = { providerID: OPENAI_PROVIDER_ID, async retrySameAccount(input) { + if (input.limit?.reason === VAULT_HTTP_401) { + const rotated = rotatedReceipts.get(input.limit) + rotatedReceipts.delete(input.limit) + if (!rotated || rotated.signal.aborted || input.continuation) + return undefined + authRetries.set(receiptKey(input), { ...rotated, marker: input.limit }) + return { accountId: input.accountId } + } if (input.continuation !== 'interrupted-read') return undefined const previous = interrupted.get(requestKey(input)) interrupted.delete(requestKey(input)) @@ -2255,8 +2363,22 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { } return { accountId: input.accountId } }, - dropSameAccountRetry() {}, - dropChoice(input) { + dropSameAccountRetry(input) { + if (input.limit?.reason !== VAULT_HTTP_401) return + rotatedReceipts.delete(input.limit) + const key = receiptKey(input) + if (authRetries.get(key)?.marker === input.limit) authRetries.delete(key) + }, + dropChoice( + input: Parameters>[0] & { + duringTransportSelection?: boolean + }, + ) { + const signal = input.rerouteFrom?.limit + // The installer releases the old choice just before rechecking a hold's + // checkpoint. Only a release outside transport selection ends that wait. + if (signal && input.duringTransportSelection === false) + routingHoldEnds.get(signal)?.('cancelled') const key = receiptKey(input) dropRequestHandoff(key) keptChoices.get(key)?.drop() @@ -2265,6 +2387,55 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { }, chooseAccount, accountHeaders, + async answeredBy({ request, response, attempt }) { + const data = attempt.data + if ( + response.status !== 401 || + seen401s.has(attempt) || + attempt.transport !== 'http' || + data?.kind !== 'vault' || + request.headers.get('authorization') !== + `Bearer ${data.receipt.accessToken}` + ) + return undefined + seen401s.add(attempt) + terminal401s.add(attempt) + if ( + !vault || + data.receipt.fromKeptReceipt || + retriedWithRotation.has(data) || + attemptsWithOutput.has(attempt) || + request.signal.aborted + ) + return undefined + const current = await vault.authorize(data.routeId, { + signal: request.signal, + }) + if ( + !request.signal.aborted && + decideScopedRetryAfter401('opencode2-http', data.receipt, current, log) + ) { + const marker: LimitSignal = { status: 401, reason: VAULT_HTTP_401 } + rotatedReceipts.set(marker, { + receipt: current, + freeQuota: data.freeQuota === true, + signal: request.signal, + }) + authMarkers.set(attempt, marker) + terminal401s.delete(attempt) + } + return undefined + }, + rewriteResponse({ attempt, response }) { + if (!terminal401s.has(attempt)) return undefined + void response.body?.cancel().catch(() => {}) + return Response.json( + { error: { message: NO_ACCOUNT_REFUSAL } }, + { status: 401 }, + ) + }, + responseRetry: ({ attempt }) => + terminal401s.has(attempt) ? 'veto' : undefined, async rewriteRequest({ request, sessionID, kind, attempt }) { const url = deps.codexEndpoint ? codexRequestURL(request.url, deps.codexEndpoint()) @@ -2310,6 +2481,8 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { }, async limitFromResponse({ status, headers, body, attempt }) { if (status < 400) return undefined + if (status === 401 && attempt.data?.kind === 'vault') + return authMarkers.get(attempt) const receivedAt = attempt.data?.kind === 'vault' && hasVaultRoutingAccessor() && @@ -2482,6 +2655,8 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { return verdict }, limitFromError(error: HostError, attempt) { + if (error.status === 401 && attempt.data?.kind === 'vault') + return undefined const parsed = parseJson(error.message) const at = now() const reading = quotaFor( @@ -2551,11 +2726,8 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { } return limit }, - // A 401 on a send the vault authorized is reported to the vault against - // the record version in that send's receipt; no other status is - // reported. Only an HTTP response gives a status here: OpenCode 2 runs no - // plugin hook for a WebSocket handshake the server refuses. async onAttemptEnd(attempt, outcome) { + authMarkers.delete(attempt) const record = attempt.data?.kind === 'vault' && hasVaultRoutingAccessor() ? billing.get(attempt) @@ -2599,7 +2771,11 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { }, ) } - state.owner?.afterProbe(state.probe, clean, Boolean(outcome.limit)) + state.owner?.afterProbe( + state.probe, + clean, + Boolean(outcome.limit && outcome.limit.reason !== VAULT_HTTP_401), + ) } if ( data && @@ -2638,6 +2814,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { data?.kind === 'vault' && hasVaultRoutingAccessor() && outcome.limit && + outcome.limit.reason !== VAULT_HTTP_401 && routingLimitBodies?.has(attempt) && !routingLimitsHandled?.has(attempt) ) { @@ -2697,10 +2874,9 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { ...response, failed: routingFailures.has(attempt), }) - if (data?.kind !== 'vault' || outcome.status !== 401) return - log?.warn('a vault account answered 401; reporting it to the vault', { - accountId: attempt.accountId, - }) + if (data?.kind !== 'vault' || !terminal401s.has(attempt)) return + // The vault consumer drops an outage-cached receipt without sending an + // authentication failure report to the vault. await vault?.reportFailure(data.receipt, 401) }, } @@ -2801,10 +2977,13 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { } }, dispose: () => { + for (const waits of activeWaits.values()) + for (const end of waits) end('abandoned') unplacedTurns.clear() heldTurns.clear() waitCounts.clear() pendingWaits.clear() + authRetries.clear() billingCounts.clear() }, attach(installation) { @@ -2814,6 +2993,7 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { // The installer waits for this listener before it asks the host to // retry, so the mark is in place when `chooseAccount` runs again. installation.on('limit', (event) => { + if (event.limit.reason === VAULT_HTTP_401) return markLimited(event.accountId, event.limit, event.handle) log?.debug('pool row refused the request', { accountId: event.accountId, diff --git a/packages/opencode/src/v2/setup.ts b/packages/opencode/src/v2/setup.ts index 92766fc5..6bc7e639 100644 --- a/packages/opencode/src/v2/setup.ts +++ b/packages/opencode/src/v2/setup.ts @@ -262,7 +262,11 @@ export async function installPoolHooks( // installOpenCode2Auth supplies an Attempt to the rewrite callbacks before it // constructs the final Request. Async-local storage carries that handle to // this hook's final snapshot without sharing a latest attempt across requests. - type HookObservation = { attempt?: Attempt; signal?: AbortSignal } + type HookObservation = { + attempt?: Attempt + signal?: AbortSignal + transportSelection: boolean + } const observing = new AsyncLocalStorage() // Receive/retry hooks have no request object to identify the send they answer. // They answer the last handshake or send for this session, so remember its @@ -316,7 +320,10 @@ export async function installPoolHooks( // The WebSocket handshake exposes no abort signal, so a placement // retry there can only rely on its bounded delay. const signal = request?.request.signal - const observation: HookObservation = { signal } + const observation: HookObservation = { + signal, + transportSelection: Boolean(request || handshake), + } if (handshake) sockets.delete(`${handshake.sessionID}:${handshake.kind}`) try { @@ -513,6 +520,14 @@ export async function installPoolHooks( const choice = { ...input, signal: observing.getStore()?.signal } return adapter.chooseAccount(choice) }, + dropChoice: (input) => { + const choice = { + ...input, + duringTransportSelection: + observing.getStore()?.transportSelection === true, + } + return adapter.dropChoice?.(choice) + }, answeredBy: async (input) => { const answered = await adapter.answeredBy?.(input) const data = From f67f3b9d540f2f7371607e59b77e254f29e6b2ad Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:10:58 +0100 Subject: [PATCH 2/2] docs(opencode2): name the routing wait and the kept receipt in two comments --- packages/opencode/src/v2/adapter.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/v2/adapter.ts b/packages/opencode/src/v2/adapter.ts index 40b35865..238ef997 100644 --- a/packages/opencode/src/v2/adapter.ts +++ b/packages/opencode/src/v2/adapter.ts @@ -2375,8 +2375,9 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { }, ) { const signal = input.rerouteFrom?.limit - // The installer releases the old choice just before rechecking a hold's - // checkpoint. Only a release outside transport selection ends that wait. + // When routing told a request to wait on its account, the installer + // releases the old choice just before it checks whether that wait should + // continue. Only a release outside transport selection ends the wait. if (signal && input.duringTransportSelection === false) routingHoldEnds.get(signal)?.('cancelled') const key = receiptKey(input) @@ -2875,8 +2876,8 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { failed: routingFailures.has(attempt), }) if (data?.kind !== 'vault' || !terminal401s.has(attempt)) return - // The vault consumer drops an outage-cached receipt without sending an - // authentication failure report to the vault. + // When this receipt was the last good token kept while the vault was + // unreachable, the vault consumer drops it instead of reporting the 401. await vault?.reportFailure(data.receipt, 401) }, }