From fb1e86d0dd4e65f7e28b7556608800f2a263bf7c Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:30:51 +0100 Subject: [PATCH 1/3] mason: stop Pi from retrying after output The locked Pi agent resends a failed turn after a text delta when the provider message contains 503. After publication, replace its terminal error text without changing pre-output routing or pi-ai transport retries. The late quota witness still requires one send and no wait or decision, but now expects the fixed terminal error instead of the provider wording because exposing that wording can trigger a host retry. --- ARCHITECTURE.md | 2 +- packages/pi/src/runtime.ts | 20 ++- packages/pi/src/tests/after-output.test.ts | 185 +++++++++++++++++++++ packages/pi/src/tests/quota-wait.test.ts | 3 +- 4 files changed, 203 insertions(+), 7 deletions(-) create mode 100644 packages/pi/src/tests/after-output.test.ts diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index baf91ec9..9a0ce787 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -87,7 +87,7 @@ OpenCode 1 sends over HTTP by default. With `webSockets` on, a session reuses a - On OpenCode 1's WebSocket path, a failed attempt surfaces as a retryable error only while no output frame has arrived (`emittedOutput` in `ws.ts`). OpenCode then sends the request again, and routing can move it to another account. After output, the stream ends with the fixed `TERMINAL_AFTER_OUTPUT_MESSAGE`, which OpenCode does not retry. - On OpenCode 2, an attempt refused before output can retry on another account. After output, the turn continues only when the reply was cut mid-read (an HTTP body read failure, or a WebSocket that dropped with no terminal frame), on the same account, after routing and quota are checked again. The host then keeps the shown output. A limit, payment refusal, error status, account change or mixed session still ends the turn. -- Pi sends again only when an attempt failed before streaming its first event. +- Pi holds lifecycle events until an attempt produces text, reasoning or a tool-call event, or ends. Before output, account routing and the host's retry policy still apply. After output, a failed primary or helper stream ends with fixed text instead of the provider's error, so Pi's agent does not resend it. This does not change pi-ai's internal WebSocket retry for `previous_response_not_found`. ## Accounts and the pool migration diff --git a/packages/pi/src/runtime.ts b/packages/pi/src/runtime.ts index ef78591e..19ea6f25 100644 --- a/packages/pi/src/runtime.ts +++ b/packages/pi/src/runtime.ts @@ -166,6 +166,11 @@ export interface PiOpenAIRuntimeDeps { /** How many vault tokens are remembered, so a WebSocket frame finds its account. */ const VAULT_TOKENS_KEPT = 64 +// Pi's agent retries by matching the error text, so provider details must not +// appear in the terminal error of an attempt that has already published output. +const TERMINAL_AFTER_OUTPUT_MESSAGE = + 'The response ended early after part of it had already been shown. It was not sent again, because repeating it would duplicate that output and re-run any tools it had started.' + /** An attempt as the router sees it, with the events it produced so far. */ interface StreamAttempt extends RouteAttempt { /** The events through the first output or terminal event, held until selection. */ @@ -1182,10 +1187,10 @@ export class PiOpenAIRuntime { if (event.type === 'error') { failed = true // pi-ai reuses this message in earlier start/delta events; a clone leaves those aliases raw. - event.error.errorMessage = redactCredentialText( - event.error.errorMessage ?? '', - token, - ) + event.error.errorMessage = + outputStarted && event.reason !== 'aborted' + ? TERMINAL_AFTER_OUTPUT_MESSAGE + : redactCredentialText(event.error.errorMessage ?? '', token) } yield event } @@ -1204,7 +1209,12 @@ export class PiOpenAIRuntime { ) } catch (error) { billing?.end(outputStarted, false, status) - yield errorEvent(model, redactCredentialError(error, token).message) + yield errorEvent( + model, + outputStarted + ? TERMINAL_AFTER_OUTPUT_MESSAGE + : redactCredentialError(error, token).message, + ) } finally { billing?.end(outputStarted, stopped && !failed, status) } diff --git a/packages/pi/src/tests/after-output.test.ts b/packages/pi/src/tests/after-output.test.ts new file mode 100644 index 00000000..1aac3785 --- /dev/null +++ b/packages/pi/src/tests/after-output.test.ts @@ -0,0 +1,185 @@ +import { expect, test } from 'bun:test' +import { writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { + type AgentSession, + createAgentSession, + DefaultResourceLoader, + SessionManager, + SettingsManager, +} from '@earendil-works/pi-coding-agent' +import { chatgptAccessToken } from '../../../core/src/tests/fixtures/mock-claustrum.ts' +import { createPiOpenAIRuntime, registerPiProvider } from '../index.ts' +import { isolatePiAgentDir } from './test-isolation.ts' + +const agentDir = isolatePiAgentDir() +const access = chatgptAccessToken('native-after-output') +const afterOutput = + 'The response ended early after part of it had already been shown. It was not sent again, because repeating it would duplicate that output and re-run any tools it had started.' +const partialText = 'Already shown' +const textStart = + 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"m","role":"assistant","status":"in_progress","content":[]}}' +const output = [ + textStart, + `data: {"type":"response.output_text.delta","output_index":0,"item_id":"m","delta":"${partialText}"}`, +] +const failure = + 'data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"503 for account Secret Name 17"}}}' +const completion = + 'data: {"type":"response.completed","response":{"id":"r","status":"completed","usage":{"input_tokens":1,"output_tokens":0,"total_tokens":1}}}' + +function sse(frames: string[]): Response { + return new Response([...frames, ''].join('\n\n'), { + headers: { 'content-type': 'text/event-stream' }, + }) +} + +async function withPiSession( + firstReply: string[], + run: (session: AgentSession, sends: string[]) => Promise, +) { + const dir = agentDir() + const runtime = createPiOpenAIRuntime({ + configPath: join(dir, 'pool.json'), + statePath: join(dir, 'pool-state.json'), + }) + writeFileSync( + join(dir, 'auth.json'), + JSON.stringify({ + 'openai-codex': { + type: 'oauth', + access, + refresh: 'unused-refresh', + expires: Date.now() + 3_600_000, + }, + }), + { mode: 0o600 }, + ) + const settingsManager = SettingsManager.inMemory({ + defaultProvider: 'openai-codex', + defaultModel: 'gpt-6.1-sol', + transport: 'sse', + retry: { + enabled: true, + baseDelayMs: 1, + maxRetries: 1, + provider: { maxRetries: 0 }, + }, + }) + const resourceLoader = new DefaultResourceLoader({ + cwd: dir, + agentDir: dir, + settingsManager, + noExtensions: true, + extensionFactories: [(pi) => registerPiProvider(pi, runtime)], + }) + const sends: string[] = [] + const fetch = globalThis.fetch + globalThis.fetch = Object.assign( + async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input instanceof Request ? input.url : input) + if (url.endsWith('/wham/usage')) + return Response.json({ + rate_limit: { + primary_window: { + used_percent: 10, + limit_window_seconds: 18_000, + reset_at: Math.floor(Date.now() / 1_000) + 7_200, + }, + secondary_window: { + used_percent: 10, + limit_window_seconds: 604_800, + reset_at: Math.floor(Date.now() / 1_000) + 86_400, + }, + }, + }) + if (!url.endsWith('/codex/responses')) + throw new Error(`Unexpected test request: ${url}`) + sends.push(new Headers(init?.headers).get('authorization') ?? '') + return sse(sends.length === 1 ? firstReply : [completion]) + }, + fetch, + ) + let session: AgentSession | undefined + try { + runtime.main.observeToken(access) + await runtime.main.pending() + await resourceLoader.reload() + const created = await createAgentSession({ + cwd: dir, + agentDir: dir, + settingsManager, + resourceLoader, + sessionManager: SessionManager.inMemory(dir), + noTools: 'all', + }) + session = created.session + expect(created.extensionsResult.errors).toEqual([]) + await session.bindExtensions({}) + expect(session.model?.id).toBe('gpt-6.1-sol') + await run(session, sends) + } finally { + session?.dispose() + await Promise.all([runtime.pool.dispose(), runtime.vault.dispose()]) + globalThis.fetch = fetch + } +} + +test('Pi agent does not resend a retryable failure after a text delta', async () => { + await withPiSession([...output, failure], async (session, sends) => { + const deltas: string[] = [] + session.subscribe((event) => { + if ( + event.type === 'message_update' && + event.assistantMessageEvent.type === 'text_delta' + ) + deltas.push(event.assistantMessageEvent.delta) + }) + await session.prompt('Hello') + expect(deltas).toEqual([partialText]) + expect(sends).toEqual([`Bearer ${access}`]) + expect(session.messages.at(-1)).toMatchObject({ + role: 'assistant', + stopReason: 'error', + errorMessage: afterOutput, + }) + }) +}) + +test('Pi agent still retries a provider error before any output', async () => { + await withPiSession([textStart, failure], async (session, sends) => { + const retries: string[] = [] + session.subscribe((event) => { + if (event.type === 'auto_retry_start') retries.push(event.errorMessage) + }) + await session.prompt('Hello') + expect(retries).toEqual(['503 for account Secret Name 17']) + expect(sends).toEqual([`Bearer ${access}`, `Bearer ${access}`]) + expect(session.messages.at(-1)).toMatchObject({ + role: 'assistant', + stopReason: 'stop', + }) + }) +}) + +test('Pi uncached stream replaces the provider error after a text delta', async () => { + await withPiSession([...output, failure], async (session, sends) => { + if (!session.model) throw new Error('Expected a Codex model') + const stream = session.modelRuntime.streamSimple( + session.model, + { messages: [{ role: 'user', content: 'Summarize', timestamp: 0 }] }, + { + cacheRetention: 'none', + sessionId: session.sessionId, + transport: 'sse', + }, + ) + const seen: string[] = [] + for await (const event of stream) { + if (event.type === 'text_delta') seen.push(event.delta) + if (event.type === 'error') seen.push(event.error.errorMessage ?? '') + } + expect(seen).toEqual([partialText, afterOutput]) + expect(sends).toEqual([`Bearer ${access}`]) + }) +}) diff --git a/packages/pi/src/tests/quota-wait.test.ts b/packages/pi/src/tests/quota-wait.test.ts index 3e85e435..17a158fe 100644 --- a/packages/pi/src/tests/quota-wait.test.ts +++ b/packages/pi/src/tests/quota-wait.test.ts @@ -751,7 +751,8 @@ describe('Pi bounded quota waits', () => { ]) expect(events[2]).toMatchObject({ type: 'text_delta', delta: 'hello' }) expect(events.at(-1)).toMatchObject({ type: 'error' }) - expect(text(events)).toContain('late quota limit') + expect(text(events)).toContain('It was not sent again') + expect(text(events)).not.toContain('late quota limit') expect(sends).toEqual([MAIN]) expect(waits).toBe(0) expect(decisions).toEqual([]) From 04d4ae5dd2b5a1fcd8b38da5ffda2502a125049d Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:35:52 +0100 Subject: [PATCH 2/3] mason: replay OC2 HTTP effort history and bound signal-less capacity waits --- .../src/tests/opencode2-http-shape.test.ts | 50 +++- .../tests/opencode2-routing-client.test.ts | 159 ++++++++++++- .../opencode/src/tests/opencode2-wire.test.ts | 36 +++ packages/opencode/src/v2/adapter.ts | 220 ++++++++++-------- packages/opencode/src/v2/codex-wire.ts | 50 ++-- 5 files changed, 396 insertions(+), 119 deletions(-) diff --git a/packages/opencode/src/tests/opencode2-http-shape.test.ts b/packages/opencode/src/tests/opencode2-http-shape.test.ts index 7c1b852a..97cc1fe6 100644 --- a/packages/opencode/src/tests/opencode2-http-shape.test.ts +++ b/packages/opencode/src/tests/opencode2-http-shape.test.ts @@ -85,8 +85,9 @@ function request(body: Record) { async function send( host: Awaited>, body: Record, + kind: RequestKind = 'primary', ) { - const draft = { ...scope(), request: request(body) } + const draft = { ...scope('ses_1', kind), request: request(body) } await host.fire('http.request', draft) return draft.request } @@ -126,6 +127,53 @@ describe('OpenCode 2 HTTP shape', () => { expect(continued.input.at(-1)).toEqual(output) }) + it('replays every HTTP effort change at its own user message, including a return to the opening effort', async () => { + const host = await start() + const [one, two, three, four] = ['one', 'two', 'three', 'four'].map(user) + const high = { type: 'configuration_update', reasoning: { effort: 'high' } } + const xhigh = { + type: 'configuration_update', + reasoning: { effort: 'xhigh' }, + } + const low = { type: 'configuration_update', reasoning: { effort: 'low' } } + const dispatch = async ( + effort: string, + input: unknown[], + kind: RequestKind = 'primary', + model = 'gpt-6.2-sol', + ) => { + const reasoning = { effort, summary: 'auto' } + const sent = await send(host, { model, input, reasoning }, kind) + const body = await sent.json() + return JSON.stringify({ input: body.input, reasoning: body.reasoning }) + } + const expected = (input: unknown[], effort = 'low') => + JSON.stringify({ input, reasoning: { effort, summary: 'auto' } }) + + expect(await dispatch('low', [one])).toBe(expected([one])) + expect(await dispatch('high', [one, two])).toBe(expected([one, high, two])) + const replay = [one, two, three] + for (const kind of ['title', 'compaction', 'generate'] as const) { + expect(await dispatch('xhigh', replay, kind)).toBe( + expected(replay, 'xhigh'), + ) + } + // The host owns gpt-6-sol effort changes. It also owns the updates in an + // already-pinned request that carries its own configuration update. + const native = [one, xhigh, two, three] + expect(await dispatch('high', native, 'primary', 'gpt-6-sol')).toBe( + expected(native, 'high'), + ) + expect(await dispatch('low', native)).toBe(expected(native)) + + expect(await dispatch('xhigh', replay)).toBe( + expected([one, high, two, xhigh, three]), + ) + expect(await dispatch('low', [...replay, four])).toBe( + expected([one, high, two, xhigh, three, low, four]), + ) + }) + it('restores replayed call status on GPT-6.2 HTTP without changing GPT-6.1 input', async () => { const host = await start() const call = { diff --git a/packages/opencode/src/tests/opencode2-routing-client.test.ts b/packages/opencode/src/tests/opencode2-routing-client.test.ts index c5c1de7f..d7cd6e81 100644 --- a/packages/opencode/src/tests/opencode2-routing-client.test.ts +++ b/packages/opencode/src/tests/opencode2-routing-client.test.ts @@ -7,10 +7,14 @@ import { placeholderSecret, } from '@cortexkit/common-auth/opencode2' import * as routingClient from '@cortexkit/common-auth/routing-accessor' -import { VAULT_MODE_REFUSALS } from '@cortexkit/openai-auth-core/internal' +import { + VAULT_MODE_REFUSALS, + VAULT_ROUTING_REFUSAL_MESSAGE, +} from '@cortexkit/openai-auth-core/internal' import type { OpenCodeLimitSource } from '../core/limit-source' import type { OpenAIAttemptData } from '../v2/adapter' import { SessionAccounts } from '../v2/session-accounts' +import { installPoolHooks } from '../v2/setup' import { fakeOpenCode2Host, scope } from './fixtures/opencode2-host' import { fixture, @@ -564,6 +568,159 @@ test('capacity placement stops and reports cancellation on HTTP abort', async () } }) +function capacityClock(start: number) { + let now = start + const realSetTimeout = globalThis.setTimeout + const realClearTimeout = globalThis.clearTimeout + const pending = new Map< + ReturnType, + { at: number; run: () => void } + >() + const set = spyOn(globalThis, 'setTimeout').mockImplementation((( + run: () => void, + delay?: number, + ...args: unknown[] + ) => { + if (delay === undefined || delay < 60_000) + return realSetTimeout(run, delay, ...args) + const timer = realSetTimeout(() => {}, delay) + realClearTimeout(timer) + pending.set(timer, { at: now + delay, run }) + return timer + }) as typeof setTimeout) + const clear = spyOn(globalThis, 'clearTimeout').mockImplementation( + (timer) => { + const handle = timer as ReturnType | undefined + if (handle !== undefined) pending.delete(handle) + realClearTimeout(handle) + }, + ) + return { + now: () => now, + advance(ms: number) { + now += ms + for (const [timer, { at, run }] of pending) { + if (at > now) continue + pending.delete(timer) + run() + } + }, + restore() { + set.mockRestore() + clear.mockRestore() + }, + } +} + +test.each(['first ask', 'announced sleep', 'HTTP request signal'] as const)( + 'capacity placement at the ten-minute deadline: %s', + async (scenario) => { + // These times are independent of the adapter's deadline constant. + const start = Date.now() + const clock = capacityClock(start) + const http = scenario === 'HTTP request signal' + const firstAsk = scenario === 'first ask' + const entered = Promise.withResolvers() + const late = Promise.withResolvers<{ account_id: string }>() + const account = { account_id: 'account-b' } + const accountFor = mock(async () => { + if (accountFor.mock.calls.length > 1) return account + if (firstAsk) { + entered.resolve() + return late.promise + } + return { + refused: { code: 'concurrency_full', resets_at_ms: start + 1_200_000 }, + } + }) + const report = mock((payload: Record) => { + if (payload.kind === 'wait' && payload.phase === 'start') + entered.resolve() + }) + Reflect.set(globalThis, key, () => ({ accountFor, report })) + const env = fixture(true, 'sticky-balanced', clock.now) + const host = fakeOpenCode2Host() + const controller = new AbortController() + const providerSend = mock(() => {}) + const installation = await installPoolHooks(host.ctx, env.openai.adapter, { + warn() {}, + info() {}, + }) + env.openai.attach(installation) + try { + const requestScope = scope(env.request.sessionID) + const headers = { authorization: `Bearer ${placeholderSecret('openai')}` } + const hook = http + ? host.fire('http.request', { + ...requestScope, + request: new Request('https://codex.test/responses', { + headers, + signal: controller.signal, + }), + }) + : host.fire('experimental.ws.handshake', { + ...requestScope, + url: 'wss://chatgpt.com/backend-api/codex/responses', + headers, + }) + const outcome = hook.then(providerSend, (error: unknown) => error) + const observe = () => + Promise.race([ + outcome, + new Promise((resolve) => setImmediate(() => resolve('pending'))), + ]) + expect(await Promise.race([entered.promise, outcome])).toBeUndefined() + clock.advance(599_999) + expect(await observe()).toBe('pending') + clock.advance(1) + if (http) { + expect(await observe()).toBe('pending') + controller.abort() + expect(await observe()).toHaveProperty('name', 'AbortError') + } else { + const error = await observe() + expect(error).toBeInstanceOf(OpenCode2AuthError) + expect(error).toMatchObject({ + kind: 'no-account', + message: VAULT_ROUTING_REFUSAL_MESSAGE, + }) + } + + late.resolve(account) + clock.advance(600_000) + await new Promise((resolve) => setImmediate(resolve)) + expect(accountFor).toHaveBeenCalledTimes(1) + expect(providerSend).not.toHaveBeenCalled() + expect(env.authorized).toEqual([]) + expect(env.openai.activeAccount(env.request.sessionID)).toBeUndefined() + const waits = report.mock.calls + .map(([payload]) => payload) + .filter((payload) => payload.kind === 'wait') + if (firstAsk) expect(waits).toEqual([]) + else { + const started = waits[0]! + expect(started).toMatchObject({ + phase: 'start', + reason: 'account_free', + }) + expect(waits).toEqual([ + started, + { + ...started, + phase: 'end', + outcome: http ? 'cancelled' : 'abandoned', + }, + ]) + } + } finally { + controller.abort() + await installation.dispose() + env.openai.dispose() + clock.restore() + } + }, +) + test('capacity placement does not use a credential that changed while waiting', async () => { const now = Date.now() const env = await placementRequest( diff --git a/packages/opencode/src/tests/opencode2-wire.test.ts b/packages/opencode/src/tests/opencode2-wire.test.ts index 1629c9d7..987ced1d 100644 --- a/packages/opencode/src/tests/opencode2-wire.test.ts +++ b/packages/opencode/src/tests/opencode2-wire.test.ts @@ -247,6 +247,42 @@ describe('mid-conversation effort on WebSocket frames', () => { expect(restarted.input).toEqual([user('two')]) expect(restarted.prompt_cache_key).not.toBe(THREAD) }) + + it('keeps the WebSocket opening pin and single-update rule after HTTP effort replays', async () => { + const effort = testEffort() + const one = user('one') + const two = user('two') + const three = user('three') + const opening = await rewriteCodexHttpRequest( + httpBody('low', [one]), + SESSION, + effort, + false, + ) + expect((await opening!.json()).reasoning.effort).toBe('low') + await rewriteCodexHttpRequest( + httpBody('high', [one, two]), + SESSION, + effort, + false, + ) + // Shortening HTTP history removes the user message that carried the + // change. HTTP starts a new pin without changing the WebSocket pin. + const rebased = await rewriteCodexHttpRequest( + httpBody('xhigh', [three]), + SESSION, + effort, + false, + ) + expect((await rebased!.json()).reasoning.effort).toBe('xhigh') + + expect( + effortEdit(frame('xhigh', [one, two, three]), SESSION, effort), + ).toEqual({ + reasoning: { effort: 'low', summary: 'auto' }, + input: [one, two, update('xhigh'), three], + }) + }) }) describe('mid-conversation effort and Responses Lite on HTTP', () => { diff --git a/packages/opencode/src/v2/adapter.ts b/packages/opencode/src/v2/adapter.ts index 20a5caaa..dda97bb6 100644 --- a/packages/opencode/src/v2/adapter.ts +++ b/packages/opencode/src/v2/adapter.ts @@ -171,6 +171,9 @@ export const OPENAI_HOST_RETRY_LIMIT = 10 */ 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 + /** * The size every request counts for in sticky placement. OpenCode 2 hands * the hooks no request body before the account is chosen, so each session @@ -1114,109 +1117,132 @@ export function createOpenAIAdapter(deps: OpenAIAdapterDeps): OpenAIAdapter { pins.get(input.sessionID) const newTurn = primary && unplacedTurns.delete(input.sessionID) const place = newTurn || current === undefined - for (let retried = false; ; retried = true) { - const routes = (vault?.routes() ?? []) - .filter((route) => route.kind === 'oauth') - .map((route) => ({ ...route, quota: route.quota })) - // Missing or expired readings do not establish that a floor was breached. - const floorSettings = storage && { - ...storage, - quota: { ...storage.quota, failClosedOnUnknownQuota: false }, - } - const floors = poolKillswitchVerdicts(routes, floorSettings, at) - const eligible = routes.filter( - (route) => floors.get(route.id) !== false, - ) - let account = current - if (place) { - if (!eligible.some((route) => route.identity && route.credentialId)) { - placementBlocked = true - break + const routingRefusal = () => + new OpenCode2AuthError({ + kind: 'no-account', + providerID: OPENAI_PROVIDER_ID, + sessionID: input.sessionID, + requestKind: input.kind, + message: VAULT_ROUTING_REFUSAL_MESSAGE, + }) + const deadline = + place && !input.signal ? new AbortController() : undefined + const capacitySignal = input.signal ?? deadline?.signal + let capacityTimer: ReturnType | undefined + try { + for (let retried = false; ; retried = true) { + const routes = (vault?.routes() ?? []) + .filter((route) => route.kind === 'oauth') + .map((route) => ({ ...route, quota: route.quota })) + // Missing or expired readings do not establish that a floor was breached. + const floorSettings = storage && { + ...storage, + quota: { ...storage.quota, failClosedOnUnknownQuota: false }, } - const activity = limits?.activity.get(input.sessionID) - let capacityWaited = false - const answer = await chooseVaultRouting({ - vaultMode, - fresh: true, - sessionId: input.sessionID, - request: { modelId: input.modelID, kind: input.kind }, - routes, - routing: routingInput(routes, storage, at, floors), - warmAccountId: current, - wait: { - activity, - accountKey: - activity && limits?.accountKey(activity.accountKey.accountId), - maxSameAccountWait: storage?.routing?.maxSameAccountWait, - }, - capacityWait: { - signal: input.signal, - now, - sleep: async (delayMs, signal) => { - capacityWaited = true - const end = startWait(input, 'account_free', now(), delayMs) - try { - // Platform timers fire early on delays longer than 2^31-1 ms. - let remaining = delayMs - do { - const next = Math.min(2_147_483_647, remaining) - await waitForRoutingRetry(next, signal) - remaining -= next - } while (remaining > 0) - end?.('resumed') - } catch (error) { - end?.(signal?.aborted ? 'cancelled' : 'abandoned') - throw error - } - }, - }, - }) - if (capacityWaited) { - at = now() - targets = 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) - const live = vault?.routes().find((route) => route.id === answer) - if ( - !offered || - !live || - live.identity !== offered.identity || - live.credentialId !== offered.credentialId || - poolKillswitchVerdicts([live], floorSettings, at).get( - answer, - ) === false - ) - throw vaultRefusal() - routedTarget = { ...live, quota: live.quota } + const floors = poolKillswitchVerdicts(routes, floorSettings, at) + const eligible = routes.filter( + (route) => floors.get(route.id) !== false, + ) + let account = current + if (place) { + if ( + !eligible.some((route) => route.identity && route.credentialId) + ) { + placementBlocked = true break } + const activity = limits?.activity.get(input.sessionID) + let capacityWaited = false + // Start at the first ask, not at the first reported sleep. Keep the + // same deadline if routing asks us to retry placement. + if (deadline && capacityTimer === undefined) { + capacityTimer = setTimeout( + () => deadline.abort(routingRefusal()), + CAPACITY_WAIT_WITHOUT_SIGNAL_MS, + ) + capacityTimer.unref() + } + const answer = await chooseVaultRouting({ + vaultMode, + fresh: true, + sessionId: input.sessionID, + request: { modelId: input.modelID, kind: input.kind }, + routes, + routing: routingInput(routes, storage, at, floors), + warmAccountId: current, + wait: { + activity, + accountKey: + activity && limits?.accountKey(activity.accountKey.accountId), + maxSameAccountWait: storage?.routing?.maxSameAccountWait, + }, + capacityWait: { + signal: capacitySignal, + now, + sleep: async (delayMs, signal) => { + capacityWaited = true + const end = startWait(input, 'account_free', now(), delayMs) + try { + // Platform timers fire early on delays longer than 2^31-1 ms. + let remaining = delayMs + do { + const next = Math.min(2_147_483_647, remaining) + await waitForRoutingRetry(next, signal) + remaining -= next + } while (remaining > 0) + end?.('resumed') + } catch (error) { + end?.(input.signal?.aborted ? 'cancelled' : 'abandoned') + throw error + } + }, + }, + }) + deadline?.signal.throwIfAborted() + if (capacityWaited) { + at = now() + targets = 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) + const live = vault + ?.routes() + .find((route) => route.id === answer) + if ( + !offered || + !live || + live.identity !== offered.identity || + live.credentialId !== offered.credentialId || + poolKillswitchVerdicts([live], floorSettings, at).get( + answer, + ) === false + ) + throw vaultRefusal() + routedTarget = { ...live, quota: live.quota } + break + } + } + if (typeof answer === 'string') account = answer + else if (answer) { + const delayMs = !retried + ? vaultRoutingPlacementRetryMs(answer) + : undefined + if (delayMs === undefined) throw routingRefusal() + await waitForRoutingRetry(delayMs, capacitySignal) + capacitySignal?.throwIfAborted() + at = now() + targets = currentTargets(storage, at, vaultMode) + continue + } } - if (typeof answer === 'string') account = answer - else if (answer) { - const delayMs = !retried - ? vaultRoutingPlacementRetryMs(answer) - : undefined - if (delayMs === undefined) - throw new OpenCode2AuthError({ - kind: 'no-account', - providerID: OPENAI_PROVIDER_ID, - sessionID: input.sessionID, - requestKind: input.kind, - message: VAULT_ROUTING_REFUSAL_MESSAGE, - }) - await waitForRoutingRetry(delayMs, input.signal) - input.signal?.throwIfAborted() - at = now() - targets = currentTargets(storage, at, vaultMode) - continue + if (account !== undefined) { + routedTarget = eligible.find((route) => route.id === account) + if (!routedTarget) throw vaultRefusal() } + break } - if (account !== undefined) { - routedTarget = eligible.find((route) => route.id === account) - if (!routedTarget) throw vaultRefusal() - } - break + } finally { + if (capacityTimer !== undefined) clearTimeout(capacityTimer) } } const firstReading = diff --git a/packages/opencode/src/v2/codex-wire.ts b/packages/opencode/src/v2/codex-wire.ts index b328dc5a..cc1603ab 100644 --- a/packages/opencode/src/v2/codex-wire.ts +++ b/packages/opencode/src/v2/codex-wire.ts @@ -5,6 +5,8 @@ // frame's `client_metadata`, never in a handshake header. import { + applyMidConversationEffort, + type CodexEffortState, type CodexRequestRuntime, type CodexSessionMetadata, type FrameTurn, @@ -151,23 +153,15 @@ export type WireForm = 'http' | 'ws' * The backend keys its prompt cache on the request-level * `reasoning.effort`, so a session that changes effort part-way would have * the whole conversation read again uncached. Instead the request-level - * value stays at the effort the session opened with, and the new effort goes - * in as `{type: 'configuration_update', reasoning: {effort}}` immediately - * before the user message that starts the current turn (the last user - * message of the input). Only the agent loop's requests (`kind` `primary`) - * take part; a session's first one with an effort pins it. - * - * The rule only ever adds to what the host built: it sets the request-level - * effort back to the pinned value and inserts the one item. It never drops, - * reorders or edits anything else, and never touches `previous_response_id`. - * Given the session's pinned effort, the result depends on the body alone. + * value stays pinned and each effort change goes in as a `configuration_update` + * immediately before its user message. Only primary requests take part. * * Per form: * - * - HTTP: every request replays the whole conversation, so the item rides - * on every request after a change, before the turn's user message; the - * tool steps of a turn keep it at the same place, so their prefix stays - * cached from one step to the next. + * - HTTP: the host replays the whole input but not the plugin's edits, so + * rebuild all updates at their original message positions on every replay. + * If the host rewrites the history, the HTTP pin can start over without + * changing the WebSocket's opening effort. * - WebSocket: the host chains turns with `previous_response_id` and sends * only the new input items, comparing against its own request as it was * before this rewrite. The server keeps the items it has seen, the @@ -185,7 +179,10 @@ export type WireForm = 'http' | 'ws' * keeps reporting the request-level (pinned) effort, as on OpenCode 1. */ export class MidConversationEffort { - readonly #pinned = new Map() + readonly #pinned = new Map< + string, + { opening: string; http: CodexEffortState } + >() constructor(readonly http = new CodexHttpState()) {} /** @@ -210,8 +207,18 @@ export class MidConversationEffort { this.#pin(scope.sessionID, effort) return false } - if (effort === pinned) return false - const input = Array.isArray(body.input) ? body.input : undefined + const rawInput = body.input + const input = Array.isArray(rawInput) ? rawInput : undefined + // Leave requests already carrying host updates on the existing path; + // inserting plugin history there could duplicate the host's updates. + if (form === 'http' && !input?.some(isConfigurationUpdate)) { + applyMidConversationEffort(body, pinned.http) + return ( + body.input !== rawInput || + (body.reasoning !== reasoning && effort !== pinned.http.pinnedEffort) + ) + } + if (effort === pinned.opening) return false // With nothing to sit in front of, an update would be the whole request; // let the request-level value stand, as OpenCode 1 does. if (!input || input.length === 0) return false @@ -223,10 +230,10 @@ export class MidConversationEffort { // apply, so with no user message to place it before, the host's // request-level effort stands. if (form === 'http') return false - body.reasoning = { ...reasoning, effort: pinned } + body.reasoning = { ...reasoning, effort: pinned.opening } return true } - body.reasoning = { ...reasoning, effort: pinned } + body.reasoning = { ...reasoning, effort: pinned.opening } // A full resend after a new user turn moves the single item to the newest // user message, so the tail after the old change point is read uncached. if (!isConfigurationUpdate(input[at - 1])) @@ -243,7 +250,10 @@ export class MidConversationEffort { } #pin(sessionID: string, effort: string) { - this.#pinned.set(sessionID, effort) + this.#pinned.set(sessionID, { + opening: effort, + http: { pinnedEffort: effort }, + }) while (this.#pinned.size > MAX_PINNED_SESSIONS) { const oldest = this.#pinned.keys().next().value if (oldest === undefined) break From 3cdc95b0e4a892573bb5b46b681fc887a08152c5 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:38:04 +0100 Subject: [PATCH 3/3] docs: explain pi-ai's previous_response_not_found recovery --- ARCHITECTURE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 9a0ce787..1008ca4b 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -87,7 +87,7 @@ OpenCode 1 sends over HTTP by default. With `webSockets` on, a session reuses a - On OpenCode 1's WebSocket path, a failed attempt surfaces as a retryable error only while no output frame has arrived (`emittedOutput` in `ws.ts`). OpenCode then sends the request again, and routing can move it to another account. After output, the stream ends with the fixed `TERMINAL_AFTER_OUTPUT_MESSAGE`, which OpenCode does not retry. - On OpenCode 2, an attempt refused before output can retry on another account. After output, the turn continues only when the reply was cut mid-read (an HTTP body read failure, or a WebSocket that dropped with no terminal frame), on the same account, after routing and quota are checked again. The host then keeps the shown output. A limit, payment refusal, error status, account change or mixed session still ends the turn. -- Pi holds lifecycle events until an attempt produces text, reasoning or a tool-call event, or ends. Before output, account routing and the host's retry policy still apply. After output, a failed primary or helper stream ends with fixed text instead of the provider's error, so Pi's agent does not resend it. This does not change pi-ai's internal WebSocket retry for `previous_response_not_found`. +- Pi holds lifecycle events until an attempt produces text, reasoning or a tool-call event, or ends. Before output, account routing and the host's retry policy still apply. After output, a failed primary or helper stream ends with fixed text instead of the provider's error, so Pi's agent does not resend it. This does not change pi-ai's own WebSocket recovery: when the server no longer has the previous response a follow-up frame chains from (`previous_response_not_found`), pi-ai resends the full conversation itself before any output. ## Accounts and the pool migration