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: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 6 additions & 6 deletions docs/limit-policy-conformance.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/core/src/limit-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ export function classifyOpenAiLimitBody(input: {
? openAiSignalWindows(
{
window: reason ?? 'rate_limit',
resetAt: failed ? undefined : resetAt,
resetAt,
},
input.now,
input.reading,
Expand Down
26 changes: 25 additions & 1 deletion packages/core/src/tests/limit-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
101 changes: 94 additions & 7 deletions packages/opencode/src/tests/opencode2-vault.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
placeholderSecret,
} from '@cortexkit/common-auth/opencode2'
import {
OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE,
OpenAiVault,
VAULT_MODE_REFUSALS,
type VaultModeRefusal,
Expand Down Expand Up @@ -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> | void> = []
Expand All @@ -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()) {
Expand Down Expand Up @@ -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<ReturnType<typeof start>>['host']

it('vault activation is registered and returns only the host placeholder without a pool write', async () => {
Expand Down Expand Up @@ -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}`,
Expand All @@ -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
Expand Down Expand Up @@ -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')
})

Expand Down
22 changes: 19 additions & 3 deletions packages/opencode/src/tests/release.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down Expand Up @@ -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('')
Expand Down Expand Up @@ -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'}`,
Expand Down
Loading
Loading