Repository navigation
feat(core): auto-balance opencode go accounts by usage - #65717
xirothedev wants to merge 12 commits into
Conversation
There was a problem hiding this comment.
I couldn't test this end to end because it needs several real OpenCode Go accounts. The changed core tests pass (127/127) and tsc --noEmit is clean in packages/core. I checked the failure and timeout paths by reading the code.
Public API impact (backwards compatible):
- Adds the config key
experimental.auto_balance_accounts(boolean, optional). - Adds an optional
sourcestring to thetui.toast.showevent payload. The generated client types are regenerated. - Inside core,
UsageLimits.Interfacegets a new requiredgo(credential)method andreadGois now exported. Any other implementation or mock ofUsageLimits.Servicemust addgo, which is why the unrelated tests changed.
Concerns, most important first:
- Request latency. When the toggle is on, every OpenCode Go model resolution (each turn, title, compaction and so on) can make network calls before the request starts. Failures and timeouts are deliberately not cached. So if the usage endpoint is slow or down, every request can wait up to 15s and then fall back anyway. Please cache failures briefly, use a much shorter budget, or fetch usage outside the request path.
- Placement. Go-specific logic (a hardcoded
"opencode-go"check, Console usage calls and a TUI toast) now lives in the genericModelResolver.prepare, which pulls in Config, UsageLimits and Bus as dependencies. It would fit better in the OpenCode provider plugin (plugin/provider/opencode.ts) or behind a hook. Also, nothing in core publishes TUI events today. - Product decision. Rotating between several paid Go subscriptions to spread usage under their limits is something maintainers should confirm they want to support.
- Tests. The test changes include formatting-only churn in
provider-chatgpt.test.tsandgenerate.test.ts. They also contain long one-line layer overrides, heavyas anymocks andDate.now()-based fixtures. See the inline comments.
The linked issue #5391 (multiple auth profiles per provider) is already closed as completed. This PR adds a feature on top of that rather than fixing it.
Related: #11830
| }), | ||
| Effect.result, | ||
| ) | ||
| if (result._tag === "Success") { |
There was a problem hiding this comment.
Only successful results are cached. With auto-balance on, an unreachable or slow /go endpoint means every model resolution, for every turn, waits up to 15s for each credential before falling back to the active account. Please cache failures for a short time as well, and/or use a much shorter timeout here, because this now sits on the request path.
| const active = yield* integrations.connection.active(integrationID) | ||
| let connection = active | ||
| // Auto-balance OpenCode Go accounts when enabled and more than one is available. | ||
| const entries = yield* config.entries() |
There was a problem hiding this comment.
This adds provider-specific behaviour to the generic resolver: a hardcoded opencode-go check, Console usage lookups and publishing a TuiEvent from core. It also makes ModelResolver depend on Config, UsageLimits and Bus. That last part is why every test that builds ModelResolver.layer had to change. Could the account choice live with the OpenCode provider plugin (plugin/provider/opencode.ts) instead, so the resolver stays provider-agnostic?
| const minScore = Math.min(...scored.map((item) => item.score)) | ||
| const best = scored.filter((item) => item.score === minScore) | ||
| // Duplicate usage (same percent & reset) means indistinguishable accounts: fall back to the selected/default. | ||
| const duplicate = |
There was a problem hiding this comment.
The choice is made again on every resolution. Within one session, consecutive turns, titles and compactions can go to different accounts whenever cached usage changes. That can surprise users and makes per-session usage and billing harder to follow. Should the choice stick for a session, or at least for a period of time, rather than for each request?
|
|
||
| const unsub = input.sdk.event.listen((event) => { | ||
| if (event.type === "tui.toast.show") { | ||
| if ((event.data as { source?: string }).source !== "opencode-go-auto-balance") return |
There was a problem hiding this comment.
The app has never shown tui.toast.show events, and this adds a special case keyed on the opencode-go-auto-balance string (plus a cast, because source is optional). A one-off feature string hardcoded in the app's general event listener is fragile. If the app should show server toasts, it should handle them generally. Otherwise this part could be left out of this PR.
| ) | ||
| }) | ||
|
|
||
| describe("ModelResolver auto-balance", () => { |
There was a problem hiding this comment.
The auto-balance tests are fine in scope, but they mock Integration.Service almost entirely with any casts. They also return lastResolved, which is whichever credential resolve saw last. Since prepare calls resolve for every candidate, this only works because of the order calls happen in. Please assert on the selected credential more directly, for example from the resolved model's auth. Separately, please drop the formatting-only changes in provider-chatgpt.test.ts and generate.test.ts, and format the one-line layer overrides in provider-poe/provider-snowflake-cortex.
There was a problem hiding this comment.
The new commit only merges dev, and it breaks a test. ModelResolver > applies provider timeouts to resolved image, video, and decision models came in from dev (#64692). It builds ModelResolver.layer without the new Config, UsageLimits and Bus services, so it now fails with Service not found: @opencode/Config. It passes on dev. I ran the five changed core test files: 131 pass, 1 fail.
The public API impact is unchanged from my last review: a new experimental.auto_balance_accounts config key and an optional source field on tui.toast.show. Both are backwards compatible.
None of my earlier points are addressed yet. The formatting churn in provider-chatgpt.test.ts is gone because the merge took dev's version, but the rest of that thread still stands.
packages/core/test/model-resolver.test.ts:1653: This test came in fromdevwith the merge. It now fails withService not found: @opencode/ConfigbecauseModelResolver.layerneeds Config, UsageLimits and Bus after this PR, and the test doesn't provide them. It passes ondev. Every test that buildsModelResolver.layerhas to add these mocks, which is the dependency cost I raised earlier. Keeping the resolver free of these dependencies would avoid it.
Issue for this PR
Closes #5391
Related: #11830
Type of change
What does this PR do?
When
experimental.auto_balance_accountsis enabled, OpenCode Go model resolution picks the credential with the lowest monthly usage rate per remaining reset window, instead of always using the manually active account. This only applies when resolvingopencode-gomodels and when there are at least 2 scorable credential connections.Details:
monthly.percent / max(1, monthly.resetsAt - now), lower is better. Accounts with any limited window (rolling/weekly/monthly) or unavailable/unscrorable usage are skipped. If usage is duplicate/indistinguishable or nothing is scorable, it falls back to the active/default connection.UsageLimits.Service.go(...)(cached 5 minutes per credential, 15s timeout, failures/timeouts not cached). Lookups are run concurrently.tui.toast.showwithsource: "opencode-go-auto-balance"; the TUI shows it and the app client filters/displays only that sourced toast.I couldn't test against real multiple Go accounts in this environment; I verified with unit/type checks and the added model-resolver tests.
How did you verify your code works?
bun run check(repo / pre-push checks) passedpackages/core:bun run typecheckpassedpackages/core:bun test test/model-resolver.test.tspassedpackages/app:bun run typecheckpassedpackages/client)Screenshots / recordings
N/A (no UI layout change; toast behavior uses existing toast surfaces).
Checklist
Added by the opencode bot (AI-generated).
Related: #11830
Public API: adds config key
experimental.auto_balance_accountsand optionalsourceon thetui.toast.showevent (backwards compatible)