Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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

Expand Down
50 changes: 49 additions & 1 deletion packages/opencode/src/tests/opencode2-http-shape.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ function request(body: Record<string, unknown>) {
async function send(
host: Awaited<ReturnType<typeof start>>,
body: Record<string, unknown>,
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
}
Expand Down Expand Up @@ -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 = {
Expand Down
159 changes: 158 additions & 1 deletion packages/opencode/src/tests/opencode2-routing-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<typeof setTimeout>,
{ 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<typeof setTimeout> | 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<void>()
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<string, unknown>) => {
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<void>((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(
Expand Down
36 changes: 36 additions & 0 deletions packages/opencode/src/tests/opencode2-wire.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Loading
Loading