From e42f6d101663122d239382abefb6977335b272de Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:13:12 -0500 Subject: [PATCH] feat(core): read OpenCode Console usage limits and classify budget refusals (#58694) --- packages/ai/src/provider-error.ts | 1 + packages/ai/test/provider-error.test.ts | 22 +- packages/client/script/build.ts | 2 + packages/client/src/effect/api/api.ts | 10 + .../client/src/effect/generated/client.ts | 10 + .../client/src/promise/generated/client.ts | 16 ++ .../client/src/promise/generated/types.ts | 33 +++ packages/client/test/promise.test.ts | 2 + packages/core/src/console-access.ts | 22 ++ packages/core/src/instance.ts | 2 + packages/core/src/plugin/provider/opencode.ts | 33 +-- packages/core/src/session/to-session-error.ts | 18 +- packages/core/src/usage-limits.ts | 192 +++++++++++++ packages/core/test/session-error.test.ts | 45 +++ packages/core/test/usage-limits.test.ts | 210 ++++++++++++++ packages/protocol/openapi.json | 265 ++++++++++++++++++ packages/protocol/src/api.ts | 3 + packages/protocol/src/client.ts | 1 + packages/protocol/src/groups/usage.ts | 30 ++ packages/schema/src/usage-limits.ts | 76 +++++ packages/server/src/handlers.ts | 2 + packages/server/src/handlers/usage.ts | 25 ++ packages/server/test/usage.test.ts | 88 ++++++ 23 files changed, 1078 insertions(+), 30 deletions(-) create mode 100644 packages/core/src/console-access.ts create mode 100644 packages/core/src/usage-limits.ts create mode 100644 packages/core/test/usage-limits.test.ts create mode 100644 packages/protocol/src/groups/usage.ts create mode 100644 packages/schema/src/usage-limits.ts create mode 100644 packages/server/src/handlers/usage.ts create mode 100644 packages/server/test/usage.test.ts diff --git a/packages/ai/src/provider-error.ts b/packages/ai/src/provider-error.ts index dc63840dd09..c0ecbee2b4a 100644 --- a/packages/ai/src/provider-error.ts +++ b/packages/ai/src/provider-error.ts @@ -126,6 +126,7 @@ const QUOTA_CODES = new Set([ "usage_not_included", "billing_error", "gousagelimiterror", + "budgetlimiterror", "freeusagelimiterror", "creditlimitexceeded", ]) diff --git a/packages/ai/test/provider-error.test.ts b/packages/ai/test/provider-error.test.ts index 4246a1b2fc3..3222e2f1edf 100644 --- a/packages/ai/test/provider-error.test.ts +++ b/packages/ai/test/provider-error.test.ts @@ -313,6 +313,26 @@ describe("provider error classification", () => { }) const cases: ReadonlyArray<[number, { error: { message: string } }]> = [ [429, typed("GoUsageLimitError", "Go usage limit exceeded")], + [429, typed("BudgetLimitError", "A budget policy for this model has been reached.")], + // Google clients get Google's envelope, naming the refusal in its ErrorInfo. + [ + 429, + { + error: { + code: 429, + status: "RESOURCE_EXHAUSTED", + message: "A budget policy for this model has been reached.", + details: [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + reason: "BudgetLimitError", + domain: "opencode.ai", + metadata: { coverage: "models", resetsAt: "2026-11-01T00:00:00.000Z" }, + }, + ], + }, + }, + ], [429, typed("FreeUsageLimitError", "Rate limit exceeded. Please try again later.")], [402, typed("CreditLimitExceeded", "Credit limit exceeded.")], [402, substituted("Insufficient account funds")], @@ -324,7 +344,7 @@ describe("provider error classification", () => { ([status, body]) => classifyProviderFailure({ message: body.error.message, status, rawBody: JSON.stringify(body) })._tag, ), - ).toEqual(Array(6).fill("QuotaExceeded")) + ).toEqual(Array(8).fill("QuotaExceeded")) }) test("classifies Z.ai plan and balance limits as quota rather than throttling", () => { diff --git a/packages/client/script/build.ts b/packages/client/script/build.ts index 3578769e589..5068e32f1fa 100644 --- a/packages/client/script/build.ts +++ b/packages/client/script/build.ts @@ -36,6 +36,7 @@ import { SessionInbox } from "@opencode/schema/session-inbox" import { Shell } from "@opencode/schema/shell" import { Skill } from "@opencode/schema/skill" import { Snapshot } from "@opencode/schema/snapshot" +import { UsageLimits } from "@opencode/schema/usage-limits" import { Vcs } from "@opencode/schema/vcs" import { WebSearch } from "@opencode/schema/websearch" import { Workspace } from "@opencode/schema/workspace" @@ -79,6 +80,7 @@ const effectTypeReferences = [ ...namespaceTypes("Shell", "@opencode/schema/shell", Shell), ...namespaceTypes("Skill", "@opencode/schema/skill", Skill), ...namespaceTypes("Snapshot", "@opencode/schema/snapshot", Snapshot), + ...namespaceTypes("UsageLimits", "@opencode/schema/usage-limits", UsageLimits), ...namespaceTypes("Vcs", "@opencode/schema/vcs", Vcs), ...namespaceTypes("WebSearch", "@opencode/schema/websearch", WebSearch), ...namespaceTypes("Workspace", "@opencode/schema/workspace", Workspace), diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index c3812ccabc6..5fc6760673b 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -40,6 +40,7 @@ import type { Reference } from "@opencode/schema/reference" import type { Worktree } from "@opencode/schema/worktree" import type { Vcs } from "@opencode/schema/vcs" import type { WebSearch } from "@opencode/schema/websearch" +import type { UsageLimits } from "@opencode/schema/usage-limits" import type { Config } from "@opencode/schema/config" export type ServerInfoOutput = { @@ -2329,6 +2330,14 @@ export interface WebsearchApi { readonly query: WebsearchQueryOperation } +export type UsageLimitsInput = { readonly location?: { readonly directory?: string | undefined } | undefined } +export type UsageLimitsOutput = { readonly location: Location.PublicRef; readonly data: UsageLimits.Info | null } +export type UsageLimitsOperation = (input?: UsageLimitsInput) => Effect.Effect + +export interface UsageApi { + readonly limits: UsageLimitsOperation +} + export type ConfigGetInput = { readonly location?: { readonly directory?: string | undefined } | undefined } export type ConfigGetOutput = ReadonlyArray export type ConfigGetOperation = (input?: ConfigGetInput) => Effect.Effect @@ -2381,5 +2390,6 @@ export interface AppApi { readonly debug: DebugApi readonly migration: MigrationApi readonly websearch: WebsearchApi + readonly usage: UsageApi readonly config: ConfigApi } diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index 0068fb8b25a..69c1136c0da 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -274,6 +274,8 @@ import type { WebsearchProvidersOutput, WebsearchQueryInput, WebsearchQueryOutput, + UsageLimitsInput, + UsageLimitsOutput, ConfigGetInput, ConfigGetOutput, ConfigShellsOutput, @@ -1656,6 +1658,13 @@ const adaptGroupWebsearch = (raw: RawClient["server.websearch"]) => ({ query: EndpointWebsearchQuery(raw), }) +const EndpointUsageLimits = (raw: RawClient["server.usage"]) => (input?: UsageLimitsInput) => + preserveEffect()( + raw["usage.limits"]({ query: { location: input?.["location"] } }).pipe(Effect.mapError(mapClientError)), + ) + +const adaptGroupUsage = (raw: RawClient["server.usage"]) => ({ limits: EndpointUsageLimits(raw) }) + const EndpointConfigGet = (raw: RawClient["server.config"]) => (input?: ConfigGetInput) => preserveEffect()( raw["config.get"]({ query: { location: input?.["location"] } }).pipe(Effect.mapError(mapClientError)), @@ -1706,6 +1715,7 @@ const adaptClient = (raw: RawClient) => ({ debug: adaptGroupDebug(raw["server.debug"]), migration: adaptGroupMigration(raw["server.migration"]), websearch: adaptGroupWebsearch(raw["server.websearch"]), + usage: adaptGroupUsage(raw["server.usage"]), config: adaptGroupConfig(raw["server.config"]), }) diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 1b2bdb6344e..4cb350e7b7a 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -272,6 +272,8 @@ import type { WebsearchProvidersOutput, WebsearchQueryInput, WebsearchQueryOutput, + UsageLimitsInput, + UsageLimitsOutput, ConfigGetInput, ConfigGetOutput, ConfigShellsOutput, @@ -2288,6 +2290,20 @@ export function make(options: ClientOptions) { requestOptions, ), }, + usage: { + limits: (input?: UsageLimitsInput, requestOptions?: RequestOptions) => + request( + { + method: "GET", + path: `/api/experimental/usage/limits`, + query: { location: input?.["location"] }, + successStatus: 200, + declaredStatuses: [400, 401, 404, 503], + empty: false, + }, + requestOptions, + ), + }, config: { get: (input?: ConfigGetInput, requestOptions?: RequestOptions) => request( diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index af97646e7b7..188383aa1c9 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -308,6 +308,8 @@ export type WebSearchID = string export type WebSearchResult = { url: string; title?: string; content?: string; time: { published?: number } } +export type UsageLimitsMeter = { percent: number; limited: boolean; resetsAt: number } + export type McpProtocol = "legacy" | "auto" | "2026-07-28" export type ConfigWorktree = { directory: string } @@ -404,6 +406,8 @@ export type SessionMessageCompactionRunning = { summary: string } +export type UsageLimitsBudgetModel = { providerID: ProviderID; modelID: string; name: string; spent?: MoneyUSD } + export type FileSystemEntry = { path: RelativePath; type: "file" | "directory" } export type SessionRevert = { @@ -858,6 +862,8 @@ export type VcsInfo = { provider?: string; branch: VcsBranch } export type WebSearchProvider = { id: WebSearchID; name: string } +export type UsageLimitsGo = { rolling: UsageLimitsMeter; weekly: UsageLimitsMeter; monthly: UsageLimitsMeter } + export type ConfigModelCapabilities = { tools?: boolean input?: Array @@ -940,6 +946,21 @@ export type ModelVariant = { export type PermissionRuleset = Array +export type UsageLimitsBudget = { + id: string + limit: MoneyUSD + spent: MoneyUSD + scope: "each" | "combined" + per: "set" | "model" + coverage: "all" | "models" + models: Array + vendors: Array + inputPriceAtLeast?: MoneyUSDPerMillionTokens + picked: boolean + shared: boolean + resetsAt: number +} + export type SessionMessageUser = { id: SessionMessageID metadata?: { [x: string]: JsonValue } @@ -2364,6 +2385,12 @@ export type ConfigEntry = } | { type: "directory"; path: AbsolutePath } +export type UsageLimitsInfo = { + workspace: { id: string; name?: string; usageURL: string } + go?: UsageLimitsGo + budgets: Array +} + export type SessionInboxUser = { id: SessionMessageID sessionID: SessionID @@ -6056,6 +6083,12 @@ export type WebsearchQueryOutput = { data: { providerID: WebSearchID; results: Array } } +export type UsageLimitsInput = { + readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"] +} + +export type UsageLimitsOutput = { location: LocationPublicRef; data: UsageLimitsInfo | null } + export type ConfigGetInput = { readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"] } diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index 4908e9c11ec..3283ddaaaa1 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -35,6 +35,7 @@ test("exposes every standard HTTP API group", () => { "debug", "migration", "websearch", + "usage", "config", ]) expect(Object.keys(client.debug)).toEqual(["heapDump", "location"]) @@ -47,6 +48,7 @@ test("exposes every standard HTTP API group", () => { expect(Object.keys(client.integration.command)).toEqual(["connect", "status", "cancel"]) expect(Object.keys(client.websearch)).toEqual(["providers", "query"]) expect(Object.keys(client.voice)).toEqual(["models", "session"]) + expect(Object.keys(client.usage)).toEqual(["limits"]) expect(Object.keys(client.file)).toEqual(["read", "list", "find", "write"]) expect(Object.keys(client.vcs)).toEqual(["init", "get", "base", "status", "branch", "diff"]) expect(Object.keys(client.pty)).toEqual(["list", "create", "get", "update", "remove", "connect"]) diff --git a/packages/core/src/console-access.ts b/packages/core/src/console-access.ts new file mode 100644 index 00000000000..e7f185ce2cb --- /dev/null +++ b/packages/core/src/console-access.ts @@ -0,0 +1,22 @@ +export * as ConsoleAccess from "./console-access.js" + +import type { Credential } from "./credential.js" + +export const defaultServer = "https://opencode.ai/console" + +/** The OpenCode Console a credential signed in to. */ +export function server(value: Credential.Value) { + const server = typeof value.metadata?.server === "string" ? value.metadata.server : defaultServer + // Credentials saved before August 2026 store the retired console.opencode.ai host, which maps path-for-path onto + // the default server; rewriting it lets that host be shut down without forcing those users to reconnect. + return server.replace(/^https:\/\/console\.opencode\.ai(?=\/|$)/, defaultServer) +} + +/** Authenticates a Console request as the credential's member, in the workspace the sign-in chose. */ +export function headers(value: Credential.Key | Credential.OAuth): Record { + const orgID = value.metadata?.orgID + return { + authorization: `Bearer ${value.type === "oauth" ? value.access : value.key}`, + ...(typeof orgID === "string" ? { "x-org-id": orgID } : {}), + } +} diff --git a/packages/core/src/instance.ts b/packages/core/src/instance.ts index 9bcde2c5922..8bf922f8b9b 100644 --- a/packages/core/src/instance.ts +++ b/packages/core/src/instance.ts @@ -14,6 +14,7 @@ import { FileSystem } from "./filesystem.js" import { FileSystemSearch } from "./filesystem/search.js" import { Generate } from "./generate.js" import { Voice } from "./voice.js" +import { UsageLimits } from "./usage-limits.js" import { Form } from "./form.js" import { Image } from "./image.js" import { LocationWatcher } from "./filesystem/location-watcher.js" @@ -99,6 +100,7 @@ const nodes = [ Form.node, Generate.node, Voice.node, + UsageLimits.node, ReadToolFileSystem.node, McpTool.node, SessionInstructions.node, diff --git a/packages/core/src/plugin/provider/opencode.ts b/packages/core/src/plugin/provider/opencode.ts index d2e3cee159e..bece15e3b80 100644 --- a/packages/core/src/plugin/provider/opencode.ts +++ b/packages/core/src/plugin/provider/opencode.ts @@ -17,6 +17,7 @@ import type { SessionHttpResponse } from "@opencode/plugin/effect/session" import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http" import { App } from "../../app.js" import { Bus } from "../../bus.js" +import { ConsoleAccess } from "../../console-access.js" import { Credential } from "../../credential.js" import { Integration } from "../../integration.js" import { IntegrationConnection } from "../../integration/connection.js" @@ -30,7 +31,6 @@ import { ConfigProvider } from "@opencode/schema/config/provider" import { Mcp } from "@opencode/schema/mcp" import { Money } from "@opencode/schema/money" -const defaultServer = "https://opencode.ai/console" const clientID = "opencode-cli" const methodID = Integration.MethodID.make("device") // Drop statements whose action or effect is a value this version does not know, so a newer Console can @@ -128,13 +128,13 @@ function oauth(http: HttpClient.HttpClient) { type: "string", format: "uri", hidden: true, - default: defaultServer, + default: ConsoleAccess.defaultServer, }, ], }, authorize: (answer) => Effect.gen(function* () { - const server = yield* normalizeServer(answer.server ?? defaultServer) + const server = yield* normalizeServer(answer.server ?? ConsoleAccess.defaultServer) const device = yield* post( http, `${server}/auth/device/code`, @@ -159,7 +159,7 @@ function oauth(http: HttpClient.HttpClient) { }), refresh: (credential) => Effect.gen(function* () { - const response = yield* send(http, `${serverUrl(credential)}/auth/device/token`, { + const response = yield* send(http, `${ConsoleAccess.server(credential)}/auth/device/token`, { grant_type: "refresh_token", refresh_token: credential.refresh, client_id: clientID, @@ -242,7 +242,7 @@ export const OpencodePlugin = define { - const orgID = value.metadata?.orgID - return { - authorization: `Bearer ${value.type === "oauth" ? value.access : value.key}`, - ...(typeof orgID === "string" ? { "x-org-id": orgID } : {}), - } -} - -function serverUrl(value: Credential.Value) { - const server = typeof value.metadata?.server === "string" ? value.metadata.server : defaultServer - // Credentials saved before August 2026 store the retired console.opencode.ai host, which maps path-for-path onto - // the default server; rewriting it lets that host be shut down without forcing those users to reconnect. - return server.replace(/^https:\/\/console\.opencode\.ai(?=\/|$)/, defaultServer) -} - function withoutCredentials(body: Readonly> | undefined) { return ( body && diff --git a/packages/core/src/session/to-session-error.ts b/packages/core/src/session/to-session-error.ts index 2fa9f70a1b3..51927ec5c05 100644 --- a/packages/core/src/session/to-session-error.ts +++ b/packages/core/src/session/to-session-error.ts @@ -27,6 +27,8 @@ const tokenSharingMessages = { const FREE_USAGE_LIMIT_MESSAGE = "Free usage limit reached. Connect a provider or subscribe to OpenCode Go to keep going, or switch models." +const BUDGET_LIMIT_MESSAGE = "Workspace usage limit reached. Model use is paused until the limit resets." +const MODEL_BUDGET_LIMIT_MESSAGE = "You've reached the spend limit for this model. Switch models to keep going." export function toSessionError(cause: unknown): SessionError.Error { if (cause instanceof AIError) { @@ -36,11 +38,10 @@ export function toSessionError(cause: unknown): SessionError.Error { case "Authentication": return providerError("provider.auth", cause.reason) case "QuotaExceeded": - if (!cause.reason.body?.includes("FreeUsageLimitError")) return providerError("provider.quota", cause.reason) - return { - ...providerError("provider.free-limit", cause.reason), - message: FREE_USAGE_LIMIT_MESSAGE, - } + if (cause.reason.body?.includes("FreeUsageLimitError")) + return { ...providerError("provider.free-limit", cause.reason), message: FREE_USAGE_LIMIT_MESSAGE } + if (cause.reason.body?.includes("BudgetLimitError")) return budgetLimit(cause.reason) + return providerError("provider.quota", cause.reason) case "ContentPolicy": return providerError("provider.content-filter", cause.reason) case "Transport": @@ -101,6 +102,13 @@ export function contentFilterError(summary: string, reason: FinishReasonDetails) } } +// OpenCode Console names what a refusing budget covers, in its envelope's metadata or, for Google clients, ErrorInfo. +function budgetLimit(reason: AIError["reason"]): SessionError.Error { + if (/"coverage"\s*:\s*"models"/.test(reason.body ?? "")) + return { ...providerError("provider.model-budget-limit", reason), message: MODEL_BUDGET_LIMIT_MESSAGE } + return { ...providerError("provider.budget-limit", reason), message: BUDGET_LIMIT_MESSAGE } +} + function providerError(type: string, reason: AIError["reason"]): SessionError.Error { const status = reason.http?.status const retryAfterMs = "retryAfterMs" in reason ? reason.retryAfterMs : undefined diff --git a/packages/core/src/usage-limits.ts b/packages/core/src/usage-limits.ts new file mode 100644 index 00000000000..9d6b0f44dcf --- /dev/null +++ b/packages/core/src/usage-limits.ts @@ -0,0 +1,192 @@ +export * as UsageLimits from "./usage-limits.js" + +import { Model } from "@opencode/schema/model" +import { Money } from "@opencode/schema/money" +import { Provider } from "@opencode/schema/provider" +import { UsageLimits } from "@opencode/schema/usage-limits" +import { makeLocationNode } from "@opencode/util/effect/app-node" +import { httpClient } from "@opencode/util/effect/app-node-platform" +import { Context, Duration, Effect, Layer, Schema } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http" +import { ConsoleAccess } from "./console-access.js" +import type { Credential } from "./credential.js" +import { Integration } from "./integration.js" + +export const Info = UsageLimits.Info +export type Info = UsageLimits.Info + +export class UnavailableError extends Schema.TaggedError()("UsageLimits.UnavailableError", { + message: Schema.String, +}) {} + +export interface Interface { + /** The usage limits of the OpenCode Console workspace this location is signed in to, if it is. */ + readonly get: () => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/UsageLimits") {} + +export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const integrations = yield* Integration.Service + const http = yield* HttpClient.HttpClient + + const get = Effect.fn("UsageLimits.get")(function* () { + const connection = yield* integrations.connection.active(Integration.ID.make("opencode")) + if (!connection) return undefined + const credential = yield* integrations.connection + .resolve(connection) + .pipe(Effect.mapError((error) => new UnavailableError({ message: error.message }))) + if (!credential || credential.type === "external") return undefined + const workspaceID = credential.metadata?.orgID + if (typeof workspaceID !== "string") return undefined + const server = ConsoleAccess.server(credential) + const [budgets, go] = yield* Effect.all( + [readBudgets(http, server, credential), readGo(http, server, credential, workspaceID)], + { concurrency: 2 }, + ).pipe( + Effect.timeoutOrElse({ + duration: Duration.seconds(15), + orElse: () => Effect.fail(new UnavailableError({ message: "OpenCode Console usage limits timed out" })), + }), + ) + return { + workspace: { + id: workspaceID, + ...(typeof credential.metadata?.orgName === "string" ? { name: credential.metadata.orgName } : {}), + usageURL: `${server}/${workspaceID}/activity/overview`, + }, + ...(go === undefined ? {} : { go }), + budgets, + } + }) + + return Service.of({ get }) + }), +) + +export const node = makeLocationNode({ + service: Service, + layer, + deps: [Integration.node, httpClient], +}) + +// One budget as `GET /api/policies/current-budgets` describes it. +const ConsoleBudget = Schema.Struct({ + ruleID: Schema.String, + limitDollars: Schema.Finite, + spentDollars: Schema.Finite, + scope: UsageLimits.Budget.fields.scope, + per: UsageLimits.Budget.fields.per, + coverage: UsageLimits.Budget.fields.coverage, + models: Schema.Array( + Schema.Struct({ + providerID: Schema.String, + modelID: Schema.String, + name: Schema.String, + spentDollars: Schema.optional(Schema.Finite), + }), + ), + vendors: Schema.Array(Schema.Struct({ id: Schema.String, name: Schema.String })), + inputPriceAtLeast: Schema.optional(Schema.Finite), + picked: Schema.Boolean, + shared: Schema.Boolean, + resetsAt: Schema.DateFromString, +}) + +const GoMeter = Schema.Struct({ + status: Schema.Literals(["ok", "rate-limited"]), + percent: Schema.Finite, + resetsAt: Schema.DateFromString, +}) +const GoUsage = Schema.Struct({ usage: Schema.Struct({ rolling: GoMeter, weekly: GoMeter, monthly: GoMeter }) }) + +/** Every budget covering the member. Console refuses a service account's key with 403, and it has no budgets. */ +function readBudgets(http: HttpClient.HttpClient, server: string, credential: Credential.Key | Credential.OAuth) { + return HttpClient.withScope(http) + .execute( + HttpClientRequest.get(`${server}/api/policies/current-budgets`).pipe( + HttpClientRequest.acceptJson, + HttpClientRequest.setHeaders(ConsoleAccess.headers(credential)), + ), + ) + .pipe( + Effect.flatMap((response) => + response.status === 403 + ? Effect.succeed([]) + : HttpClientResponse.filterStatusOk(response).pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Array(ConsoleBudget))), + Effect.map((budgets) => + budgets.map((budget) => ({ + id: budget.ruleID, + limit: Money.USD.make(budget.limitDollars), + spent: Money.USD.make(budget.spentDollars), + scope: budget.scope, + per: budget.per, + coverage: budget.coverage, + models: budget.models.map((model) => ({ + providerID: Provider.ID.make(model.providerID), + modelID: Model.ID.make(model.modelID), + name: model.name, + ...(model.spentDollars === undefined ? {} : { spent: Money.USD.make(model.spentDollars) }), + })), + vendors: budget.vendors.map((vendor) => vendor.name), + ...(budget.inputPriceAtLeast === undefined + ? {} + : { inputPriceAtLeast: Money.USDPerMillionTokens.make(budget.inputPriceAtLeast) }), + picked: budget.picked, + shared: budget.shared, + resetsAt: budget.resetsAt.getTime(), + })), + ), + ), + ), + Effect.scoped, + Effect.mapError( + (error) => new UnavailableError({ message: `OpenCode Console budgets are unavailable: ${error.message}` }), + ), + ) +} + +/** + * The Go allowance, from the inference API that shares the Console's origin. Go refuses (403) a workspace the member + * doesn't subscribe to Go in, which has no allowance to show. + */ +function readGo( + http: HttpClient.HttpClient, + server: string, + credential: Credential.Key | Credential.OAuth, + workspaceID: string, +) { + return HttpClient.withScope(http) + .execute( + HttpClientRequest.get(`${new URL(server).origin}/zen/go/v1/usage`).pipe( + HttpClientRequest.acceptJson, + HttpClientRequest.bearerToken(credential.type === "oauth" ? credential.access : credential.key), + HttpClientRequest.setHeader("x-opencode-org-id", workspaceID), + ), + ) + .pipe( + Effect.flatMap((response) => + response.status === 403 + ? Effect.succeed(undefined) + : HttpClientResponse.filterStatusOk(response).pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(GoUsage)), + Effect.map((body) => ({ + rolling: meter(body.usage.rolling), + weekly: meter(body.usage.weekly), + monthly: meter(body.usage.monthly), + })), + ), + ), + Effect.scoped, + Effect.mapError( + (error) => new UnavailableError({ message: `OpenCode Go usage is unavailable: ${error.message}` }), + ), + ) +} + +function meter(value: typeof GoMeter.Type) { + return { percent: value.percent, limited: value.status === "rate-limited", resetsAt: value.resetsAt.getTime() } +} diff --git a/packages/core/test/session-error.test.ts b/packages/core/test/session-error.test.ts index fcf8fe21083..06256f5a6b7 100644 --- a/packages/core/test/session-error.test.ts +++ b/packages/core/test/session-error.test.ts @@ -130,6 +130,51 @@ describe("toSessionError", () => { expect(toSessionError(other)).toMatchObject({ type: "provider.rate-limit", retryAfterMs: 10_000 }) }) + test("tells a budget on the requested model from one pausing all model use", () => { + const refuse = (body: unknown) => + RequestExecutor.httpFailure({ + message: "A budget policy for this model has been reached.", + url: "https://opencode.ai/inference/openai/v1/chat/completions", + status: 429, + responseBody: JSON.stringify(body), + }) + const modelBody = { + type: "error", + error: { type: "BudgetLimitError", message: "A budget policy for this model has been reached." }, + metadata: { coverage: "models", resetsAt: "2026-11-01T00:00:00.000Z" }, + } + const model = refuse(modelBody) + expect(SessionRunnerRetry.isRetryable(model)).toBe(false) + expect(toSessionError(model)).toEqual({ + type: "provider.model-budget-limit", + message: "You've reached the spend limit for this model. Switch models to keep going.", + status: 429, + response: { body: JSON.stringify(modelBody) }, + }) + + // Google clients get Google's envelope, with the same metadata in its ErrorInfo. + const all = refuse({ + error: { + code: 429, + status: "RESOURCE_EXHAUSTED", + message: "Policy budget exceeded", + details: [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + reason: "BudgetLimitError", + domain: "opencode.ai", + metadata: { coverage: "all", resetsAt: "2026-11-01T00:00:00.000Z" }, + }, + ], + }, + }) + expect(SessionRunnerRetry.isRetryable(all)).toBe(false) + expect(toSessionError(all)).toMatchObject({ + type: "provider.budget-limit", + message: "Workspace usage limit reached. Model use is paused until the limit resets.", + }) + }) + test("preserves the permission rejection type without exposing internal fields", () => { const blocked = new Permission.BlockedError({ rules: [], permission: "external_directory", resources: [] }) expect(toSessionError(blocked)).toEqual({ diff --git a/packages/core/test/usage-limits.test.ts b/packages/core/test/usage-limits.test.ts new file mode 100644 index 00000000000..2593fa169d6 --- /dev/null +++ b/packages/core/test/usage-limits.test.ts @@ -0,0 +1,210 @@ +import { expect } from "bun:test" +import { Credential } from "@opencode/core/credential" +import { Integration } from "@opencode/core/integration" +import { UsageLimits } from "@opencode/core/usage-limits" +import { Model } from "@opencode/schema/model" +import { Money } from "@opencode/schema/money" +import { Provider } from "@opencode/schema/provider" +import { Effect, Exit, Layer } from "effect" +import { HttpClient, type HttpClientRequest, HttpClientResponse } from "effect/http" +import { testEffect } from "./lib/effect" + +const it = testEffect(Layer.empty) + +const unused = () => Effect.die("unused") + +const signedIn = Credential.OAuth.make({ + type: "oauth", + methodID: Integration.MethodID.make("device"), + access: "console-access", + refresh: "console-refresh", + expires: 1, + metadata: { server: "https://dev.opencode.ai/console", orgID: "wrk_anomaly", orgName: "Anomaly" }, +}) + +const budget = { + policyID: "policy_engineering", + ruleID: "rule_astra", + limitDollars: 20, + spentDollars: 15, + scope: "each", + per: "model", + modelCount: 1, + coverage: "models", + models: [ + { + providerID: "opencode", + connectionID: "conn_managed", + modelID: "gpt-6-astra", + name: "GPT-6 Astra", + spentDollars: 15, + }, + ], + vendors: [{ id: "openai", name: "OpenAI" }], + inputPriceAtLeast: 3, + picked: false, + shared: false, + resetsAt: "2026-11-01T00:00:00.000Z", +} + +const meter = (status: string, percent: number) => ({ status, percent, resetsAt: "2026-10-24T17:00:00.000Z" }) + +/** Reads usage limits for a location whose active OpenCode Console connection resolves to `credential`. */ +const read = ( + credential: Credential.Value | undefined, + respond: (url: string) => Response, + requests: HttpClientRequest.HttpClientRequest[] = [], +) => + Effect.flatMap(UsageLimits.Service, (limits) => limits.get()).pipe( + Effect.provide( + UsageLimits.layer.pipe( + Layer.provide( + Layer.merge( + Layer.mock(Integration.Service, { + revision: () => 0, + get: unused, + connection: { + active: () => + Effect.succeed( + credential && { + type: "credential" as const, + id: Credential.ID.make("console"), + label: "Anomaly", + method: "oauth" as const, + }, + ), + resolve: () => Effect.succeed(credential), + key: unused, + external: unused, + activate: unused, + update: unused, + remove: unused, + status: unused, + }, + oauth: { connect: unused, status: unused, complete: unused, cancel: unused }, + command: { connect: unused, status: unused, cancel: unused }, + }), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request: HttpClientRequest.HttpClientRequest) => + Effect.sync(() => { + requests.push(request) + return HttpClientResponse.fromWeb(request, respond(request.url)) + }), + ), + ), + ), + ), + ), + ), + ) + +it.effect("reads the member's Go allowance and budgets from the Console they signed in to", () => + Effect.gen(function* () { + const requests: HttpClientRequest.HttpClientRequest[] = [] + const limits = yield* read( + signedIn, + (url) => + url.endsWith("/zen/go/v1/usage") + ? Response.json({ + usage: { rolling: meter("ok", 42), weekly: meter("ok", 18), monthly: meter("rate-limited", 100) }, + }) + : Response.json([budget]), + requests, + ) + + expect(limits).toEqual({ + workspace: { + id: "wrk_anomaly", + name: "Anomaly", + usageURL: "https://dev.opencode.ai/console/wrk_anomaly/activity/overview", + }, + go: { + rolling: { percent: 42, limited: false, resetsAt: Date.parse("2026-10-24T17:00:00.000Z") }, + weekly: { percent: 18, limited: false, resetsAt: Date.parse("2026-10-24T17:00:00.000Z") }, + monthly: { percent: 100, limited: true, resetsAt: Date.parse("2026-10-24T17:00:00.000Z") }, + }, + budgets: [ + { + id: "rule_astra", + limit: Money.USD.make(20), + spent: Money.USD.make(15), + scope: "each", + per: "model", + coverage: "models", + models: [ + { + providerID: Provider.ID.make("opencode"), + modelID: Model.ID.make("gpt-6-astra"), + name: "GPT-6 Astra", + spent: Money.USD.make(15), + }, + ], + vendors: ["OpenAI"], + inputPriceAtLeast: Money.USDPerMillionTokens.make(3), + picked: false, + shared: false, + resetsAt: Date.parse("2026-11-01T00:00:00.000Z"), + }, + ], + }) + // Console reads the workspace from x-org-id; inference, which serves Go, from x-opencode-org-id. + expect( + requests + .map((request) => ({ + url: request.url, + authorization: request.headers.authorization, + workspace: Object.entries(request.headers).filter(([name]) => name.endsWith("org-id")), + })) + .toSorted((a, b) => a.url.localeCompare(b.url)), + ).toEqual([ + { + url: "https://dev.opencode.ai/console/api/policies/current-budgets", + authorization: "Bearer console-access", + workspace: [["x-org-id", "wrk_anomaly"]], + }, + { + url: "https://dev.opencode.ai/zen/go/v1/usage", + authorization: "Bearer console-access", + workspace: [["x-opencode-org-id", "wrk_anomaly"]], + }, + ]) + }), +) + +it.effect("has no Go allowance or budgets to show where Console refuses them", () => + Effect.gen(function* () { + // Go refuses a workspace without the member's subscription; Console refuses budgets to a service account's key. + const limits = yield* read(signedIn, () => Response.json({ type: "error" }, { status: 403 })) + + expect(limits).toEqual({ + workspace: { + id: "wrk_anomaly", + name: "Anomaly", + usageURL: "https://dev.opencode.ai/console/wrk_anomaly/activity/overview", + }, + budgets: [], + }) + }), +) + +it.effect("has nothing to show for a location that isn't signed in to OpenCode Console", () => + Effect.gen(function* () { + expect(yield* read(undefined, () => Response.json([budget]))).toBeUndefined() + }), +) + +it.effect("reports a Console that can't answer as unavailable", () => + Effect.gen(function* () { + // Go has nothing to show, so only the Console's failure can fail the read. + const exit = yield* read(signedIn, (url) => + url.endsWith("/current-budgets") + ? new Response("upstream down", { status: 502 }) + : Response.json({ type: "error" }, { status: 403 }), + ).pipe(Effect.exit) + + expect(Exit.isFailure(exit) && Exit.findErrorOption(exit)).toMatchObject({ + value: { _tag: "UsageLimits.UnavailableError" }, + }) + }), +) diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 7b080544830..0899debbbc8 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -13926,6 +13926,116 @@ } } }, + "/api/experimental/usage/limits": { + "get": { + "tags": ["usage"], + "operationId": "experimental.usage.limits", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.PublicRef" + }, + "data": { + "anyOf": [ + { + "$ref": "#/components/schemas/UsageLimits.Info" + }, + { + "type": "null" + } + ] + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + }, + "404": { + "description": "LocationNotFoundError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LocationNotFoundErrorEncoded" + } + } + } + }, + "503": { + "description": "ServiceUnavailableError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableErrorEncoded" + } + } + } + } + }, + "description": "Return the OpenCode Go allowance and Console budgets of the OpenCode Console workspace the location is signed in to, or null when it isn't signed in.", + "summary": "Get usage limits" + } + }, "/api/config": { "get": { "tags": ["config"], @@ -20899,6 +21009,157 @@ "required": ["_tag", "message"], "additionalProperties": false }, + "UsageLimits.Budget": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "limit": { + "$ref": "#/components/schemas/Money.USD" + }, + "spent": { + "$ref": "#/components/schemas/Money.USD" + }, + "scope": { + "type": "string", + "enum": ["each", "combined"] + }, + "per": { + "type": "string", + "enum": ["set", "model"] + }, + "coverage": { + "type": "string", + "enum": ["all", "models"] + }, + "models": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UsageLimits.BudgetModel" + } + }, + "vendors": { + "type": "array", + "items": { + "type": "string" + } + }, + "inputPriceAtLeast": { + "$ref": "#/components/schemas/Money.USDPerMillionTokens" + }, + "picked": { + "type": "boolean" + }, + "shared": { + "type": "boolean" + }, + "resetsAt": { + "type": "number", + "description": "Milliseconds since the Unix epoch" + } + }, + "required": [ + "id", + "limit", + "spent", + "scope", + "per", + "coverage", + "models", + "vendors", + "picked", + "shared", + "resetsAt" + ], + "additionalProperties": false + }, + "UsageLimits.BudgetModel": { + "type": "object", + "properties": { + "providerID": { + "$ref": "#/components/schemas/Provider.ID" + }, + "modelID": { + "type": "string" + }, + "name": { + "type": "string" + }, + "spent": { + "$ref": "#/components/schemas/Money.USD" + } + }, + "required": ["providerID", "modelID", "name"], + "additionalProperties": false + }, + "UsageLimits.Go": { + "type": "object", + "properties": { + "rolling": { + "$ref": "#/components/schemas/UsageLimits.Meter" + }, + "weekly": { + "$ref": "#/components/schemas/UsageLimits.Meter" + }, + "monthly": { + "$ref": "#/components/schemas/UsageLimits.Meter" + } + }, + "required": ["rolling", "weekly", "monthly"], + "additionalProperties": false + }, + "UsageLimits.Info": { + "type": "object", + "properties": { + "workspace": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "usageURL": { + "type": "string" + } + }, + "required": ["id", "usageURL"], + "additionalProperties": false + }, + "go": { + "$ref": "#/components/schemas/UsageLimits.Go" + }, + "budgets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UsageLimits.Budget" + } + } + }, + "required": ["workspace", "budgets"], + "additionalProperties": false + }, + "UsageLimits.Meter": { + "type": "object", + "properties": { + "percent": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "limited": { + "type": "boolean" + }, + "resetsAt": { + "type": "number", + "description": "Milliseconds since the Unix epoch" + } + }, + "required": ["percent", "limited", "resetsAt"], + "additionalProperties": false + }, "V2EventEncoded": { "type": "string", "contentMediaType": "application/json" @@ -21450,6 +21711,10 @@ "name": "websearch", "description": "Location-scoped web search routes." }, + { + "name": "usage", + "description": "Experimental usage limit routes." + }, { "name": "config", "description": "Location-scoped configuration routes." diff --git a/packages/protocol/src/api.ts b/packages/protocol/src/api.ts index 4a7d793a02d..0ca19e81b94 100644 --- a/packages/protocol/src/api.ts +++ b/packages/protocol/src/api.ts @@ -27,6 +27,7 @@ import { Authorization } from "./middleware/authorization.js" import { makeLocationGroup } from "./groups/location.js" import { IntegrationGroup } from "./groups/integration.js" import { WebSearchGroup } from "./groups/websearch.js" +import { UsageGroup } from "./groups/usage.js" import { makeMcpGroup } from "./groups/mcp.js" import { CredentialGroup } from "./groups/credential.js" import { ProjectGroup } from "./groups/project.js" @@ -42,6 +43,7 @@ type LocationGroups = | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware + | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware | HttpApiGroup.AddMiddleware @@ -193,6 +195,7 @@ const makeApiFromGroup = < .add(DebugGroup) .add(MigrationGroup) .add(WebSearchGroup.middleware(locationMiddleware)) + .add(UsageGroup.middleware(locationMiddleware)) .add(ConfigGroup.middleware(locationMiddleware)) .annotateMerge( OpenApi.annotations({ diff --git a/packages/protocol/src/client.ts b/packages/protocol/src/client.ts index a428ec758e9..57f1cb6c7c2 100644 --- a/packages/protocol/src/client.ts +++ b/packages/protocol/src/client.ts @@ -48,6 +48,7 @@ export const groupNames = { "server.provider": "provider", "server.integration": "integration", "server.websearch": "websearch", + "server.usage": "usage", "server.credential": "credential", "server.form": "form", "server.permission": "permission", diff --git a/packages/protocol/src/groups/usage.ts b/packages/protocol/src/groups/usage.ts new file mode 100644 index 00000000000..5c0528d98af --- /dev/null +++ b/packages/protocol/src/groups/usage.ts @@ -0,0 +1,30 @@ +import { Location } from "@opencode/schema/location" +import { UsageLimits } from "@opencode/schema/usage-limits" +import { Schema } from "effect" +import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api" +import { ServiceUnavailableError } from "../errors.js" +import { LocationQuery, locationQueryOpenApi } from "./location.js" + +export const UsageGroup = HttpApiGroup.make("server.usage") + .add( + HttpApiEndpoint.get("usage.limits", "/api/experimental/usage/limits", { + query: LocationQuery, + success: Location.response(Schema.NullOr(UsageLimits.Info)), + error: ServiceUnavailableError, + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "experimental.usage.limits", + summary: "Get usage limits", + description: + "Return the OpenCode Go allowance and Console budgets of the OpenCode Console workspace the location is signed in to, or null when it isn't signed in.", + }), + ), + ) + .annotateMerge( + OpenApi.annotations({ + title: "usage", + description: "Experimental usage limit routes.", + }), + ) diff --git a/packages/schema/src/usage-limits.ts b/packages/schema/src/usage-limits.ts new file mode 100644 index 00000000000..c8b6566439b --- /dev/null +++ b/packages/schema/src/usage-limits.ts @@ -0,0 +1,76 @@ +export * as UsageLimits from "./usage-limits.js" + +import { Schema } from "effect" +import { Model } from "./model.js" +import { Money } from "./money.js" +import { Provider } from "./provider.js" +import { optional } from "./schema.js" + +const Percent = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 100 })) +const Instant = Schema.Finite.annotate({ description: "Milliseconds since the Unix epoch" }) + +/** One window of the OpenCode Go allowance. */ +export interface Meter extends Schema.Schema.Type {} +export const Meter = Schema.Struct({ + /** How much of the window's allowance is used. */ + percent: Percent, + /** Go refuses requests until the window resets. */ + limited: Schema.Boolean, + resetsAt: Instant, +}).annotate({ identifier: "UsageLimits.Meter" }) + +/** The OpenCode Go allowance of a workspace the member subscribes to Go in. */ +export interface Go extends Schema.Schema.Type {} +export const Go = Schema.Struct({ + rolling: Meter, + weekly: Meter, + monthly: Meter, +}).annotate({ identifier: "UsageLimits.Go" }) + +/** A model a budget covers, by the IDs OpenCode knows it by. */ +export interface BudgetModel extends Schema.Schema.Type {} +export const BudgetModel = Schema.Struct({ + providerID: Provider.ID, + modelID: Model.ID, + name: Schema.String, + /** What a per-model budget's member has spent on this model this month. */ + spent: Money.USD.pipe(optional), +}).annotate({ identifier: "UsageLimits.BudgetModel" }) + +/** A monthly spend limit the OpenCode Console workspace sets on the member. */ +export interface Budget extends Schema.Schema.Type {} +export const Budget = Schema.Struct({ + id: Schema.String, + limit: Money.USD, + /** The member's spend this month, or the pooled spend of a combined budget; per model, the most on one model. */ + spent: Money.USD, + /** `each` limits every member separately; `combined` pools everyone's spend against one limit. */ + scope: Schema.Literals(["each", "combined"]), + /** `set` counts spend across the budget's models; `model` limits each model separately. */ + per: Schema.Literals(["set", "model"]), + /** `all` covers every model and billable service; `models` covers only `models`. */ + coverage: Schema.Literals(["all", "models"]), + models: Schema.Array(BudgetModel), + /** The vendors whose models the budget counts, by name; empty when it doesn't count by vendor. */ + vendors: Schema.Array(Schema.String), + /** The input price per 1M tokens from which the budget counts a model, when it sets one. */ + inputPriceAtLeast: Money.USDPerMillionTokens.pipe(optional), + /** The budget counts models picked one by one, rather than by vendor or price. */ + picked: Schema.Boolean, + /** Everyone in the workspace pools spend against it, so reaching it pauses model use for all of them. */ + shared: Schema.Boolean, + resetsAt: Instant, +}).annotate({ identifier: "UsageLimits.Budget" }) + +/** The usage limits of the OpenCode Console workspace a location is signed in to. */ +export interface Info extends Schema.Schema.Type {} +export const Info = Schema.Struct({ + workspace: Schema.Struct({ + id: Schema.String, + name: Schema.String.pipe(optional), + /** The member's usage page in OpenCode Console. */ + usageURL: Schema.String, + }), + go: Go.pipe(optional), + budgets: Schema.Array(Budget), +}).annotate({ identifier: "UsageLimits.Info" }) diff --git a/packages/server/src/handlers.ts b/packages/server/src/handlers.ts index 1e20913605c..6a2fd06aae8 100644 --- a/packages/server/src/handlers.ts +++ b/packages/server/src/handlers.ts @@ -23,6 +23,7 @@ import { ReferenceHandler } from "./handlers/reference" import { LocationHandler } from "./handlers/location" import { IntegrationHandler } from "./handlers/integration" import { WebSearchHandler } from "./handlers/websearch" +import { UsageHandler } from "./handlers/usage" import { McpHandler } from "./handlers/mcp" import { CredentialHandler } from "./handlers/credential" import { ProjectHandler } from "./handlers/project" @@ -47,6 +48,7 @@ export const handlers = Layer.mergeAll( ProviderHandler, IntegrationHandler, WebSearchHandler, + UsageHandler, McpHandler, CredentialHandler, ProjectHandler, diff --git a/packages/server/src/handlers/usage.ts b/packages/server/src/handlers/usage.ts new file mode 100644 index 00000000000..e70592c1b31 --- /dev/null +++ b/packages/server/src/handlers/usage.ts @@ -0,0 +1,25 @@ +import { UsageLimits } from "@opencode/core/usage-limits" +import { ServiceUnavailableError } from "@opencode/protocol/errors" +import { Effect } from "effect" +import { HttpApiBuilder } from "effect/http-api" +import { Api } from "../api" +import { awaitPlugins, response } from "../location" + +export const UsageHandler = HttpApiBuilder.group(Api, "server.usage", (handlers) => + Effect.gen(function* () { + return handlers.handle( + "usage.limits", + Effect.fn("server.usage.limits")(function* () { + // The OpenCode Console plugin registers the sign-in method that refreshes an expired credential. + yield* awaitPlugins + const limits = yield* UsageLimits.Service + return yield* response( + limits.get().pipe( + Effect.map((info) => info ?? null), + Effect.mapError((error) => new ServiceUnavailableError({ message: error.message, service: "opencode" })), + ), + ) + }), + ) + }), +) diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.ts new file mode 100644 index 00000000000..9557417d27e --- /dev/null +++ b/packages/server/test/usage.test.ts @@ -0,0 +1,88 @@ +import fs from "node:fs/promises" +import path from "node:path" +import { expect } from "bun:test" +import { UsageLimits } from "@opencode/core/usage-limits" +import { Money } from "@opencode/schema/money" +import { makeLocationNode } from "@opencode/util/effect/app-node" +import { Effect, Layer } from "effect" +import { tmpdir } from "../../core/test/fixture/tmpdir" +import { it } from "../../core/test/lib/effect" +import { ServerFetch } from "../src/fetch" + +/** Requests a location's usage limits from a server whose UsageLimits answers with `get`. */ +const request = (get: UsageLimits.Interface["get"]) => + Effect.gen(function* () { + const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-usage-endpoint-"))) + const global = path.join(tmp.path, "global") + yield* Effect.promise(() => fs.mkdir(global)) + const handler = yield* ServerFetch.make( + { + database: { path: ":memory:" }, + config: { directory: global }, + fs: { filewatcher: false }, + models: { fetch: false }, + }, + { + overrides: [ + UsageLimits.node.replace( + makeLocationNode({ + service: UsageLimits.Service, + layer: Layer.succeed(UsageLimits.Service, UsageLimits.Service.of({ get })), + deps: [], + }), + ), + ], + }, + ) + const url = new URL("/api/experimental/usage/limits", "http://opencode.local") + url.searchParams.set("location[directory]", tmp.path) + const response = yield* Effect.promise(() => handler(new Request(url))) + return { status: response.status, body: yield* Effect.promise(() => response.json()) } + }) + +it.live("returns the usage limits of the OpenCode Console workspace a location is signed in to", () => + Effect.gen(function* () { + const limits: UsageLimits.Info = { + workspace: { id: "wrk_anomaly", usageURL: "https://opencode.ai/console/wrk_anomaly/activity/overview" }, + budgets: [ + { + id: "rule_monthly", + limit: Money.USD.make(50), + spent: Money.USD.make(12.5), + scope: "each", + per: "set", + coverage: "all", + models: [], + vendors: [], + picked: false, + shared: false, + resetsAt: 1793491200000, + }, + ], + } + const result = yield* request(() => Effect.succeed(limits)) + + expect(result.status).toBe(200) + expect(result.body).toMatchObject({ data: limits }) + }), +) + +it.live("returns null for a location that isn't signed in to OpenCode Console", () => + Effect.gen(function* () { + const result = yield* request(() => Effect.succeed(undefined)) + + expect(result.status).toBe(200) + expect(result.body).toMatchObject({ data: null }) + }), +) + +it.live("reports usage limits Console can't provide as unavailable", () => + Effect.gen(function* () { + const result = yield* request(() => + Effect.fail(new UsageLimits.UnavailableError({ message: "OpenCode Console budgets are unavailable" })), + ) + + expect(result.status).toBe(503) + expect(result.body).toMatchObject({ message: "OpenCode Console budgets are unavailable", service: "opencode" }) + }), +)