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
64 changes: 64 additions & 0 deletions packages/core/src/balance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
export * as Balance from "./balance"

import { Effect, Schema } from "effect"
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http"

/**
* The workspace's balance and spend, read from the console for `/status`.
*
* `GET <console>/usage/summary?tz=<IANA zone>` with the same workspace API key the Redrob provider
* already sends for inference. The figures are the workspace's, across every device and app, which is
* what the local session totals cannot say.
*
* Every failure is quiet: no key, a refused key (401), a bad zone (400), the rate limit (429), a console
* that does not have the route yet (404), a timeout or a body that does not parse all return
* `undefined`, and the caller shows the billing link it showed before. Nothing here logs, and the key
* never leaves the request header.
*/

/** `/status` waits for this, so it stays short: a slow console must not hold the dialog. */
const TIMEOUT = "5 seconds"

const Period = Schema.Struct({
since: Schema.String,
spend: Schema.Finite,
requestCount: Schema.Finite,
}).annotate({ identifier: "ConsoleUsagePeriod" })

export const Summary = Schema.Struct({
currency: Schema.String,
balance: Schema.Finite,
complimentary: Schema.Boolean,
plan: Schema.optional(Schema.String),
tz: Schema.String,
today: Period,
month: Period,
}).annotate({ identifier: "ConsoleUsageSummary" })
export type Summary = Schema.Schema.Type<typeof Summary>

export type Input = {
/** The console API base, `CONSOLE_URL` or the provider's configured `baseURL`. */
url: string
key: string
tz: string
}

const decode = Schema.decodeUnknownOption(Schema.fromJsonString(Summary))

const read = Effect.fn("Balance.read")(function* (input: Input) {
const http = yield* HttpClient.HttpClient
const url = `${input.url.replace(/\/+$/, "")}/usage/summary?${new URLSearchParams({ tz: input.tz })}`
const response = yield* http.execute(
HttpClientRequest.get(url).pipe(HttpClientRequest.acceptJson, HttpClientRequest.bearerToken(input.key)),
)
if (response.status !== 200) return undefined
const parsed = decode(yield* response.text)
return parsed._tag === "Some" ? parsed.value : undefined
})

export const summary = (input: Input): Effect.Effect<Summary | undefined> =>
read(input).pipe(
Effect.timeout(TIMEOUT),
Effect.provide(FetchHttpClient.layer),
Effect.catchCause(() => Effect.succeed(undefined)),
)
87 changes: 87 additions & 0 deletions packages/core/test/balance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { Balance } from "@redrob-code/core/balance"

/**
* A stand-in console on loopback. Each test picks the reply by the key it sends, so the request the
* module builds (path, query, bearer header) is checked on every call.
*/
const body = {
currency: "USD",
balance: 20.368355,
complimentary: false,
plan: "free",
tz: "Asia/Seoul",
today: { since: "2026-11-12T15:00:00.000Z", spend: 0, requestCount: 0 },
month: { since: "2026-10-31T15:00:00.000Z", spend: 147.07, requestCount: 16764 },
}

const seen: { path: string; tz: string | null; auth: string | null }[] = []
let server: ReturnType<typeof Bun.serve>
let url: string

beforeAll(() => {
server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
async fetch(request) {
const parsed = new URL(request.url)
const auth = request.headers.get("authorization")
seen.push({ path: parsed.pathname, tz: parsed.searchParams.get("tz"), auth })
if (parsed.pathname !== "/api/backend/v1/usage/summary") return new Response("not found", { status: 404 })
switch (auth) {
case "Bearer ok":
return Response.json(body)
case "Bearer slow":
await Bun.sleep(7_000)
return Response.json(body)
case "Bearer garbled":
return new Response("{not json", { status: 200 })
case "Bearer partial":
return Response.json({ currency: "USD", balance: 1 })
case "Bearer limited":
return Response.json({ message: "slow down" }, { status: 429, headers: { "retry-after": "30" } })
default:
return Response.json({ message: "invalid api key" }, { status: 401 })
}
},
})
url = `http://127.0.0.1:${server.port}/api/backend/v1`
})

afterAll(() => server.stop(true))

const run = (key: string, base = url) => Effect.runPromise(Balance.summary({ url: base, key, tz: "Asia/Seoul" }))

describe("Balance.summary", () => {
test("reads the console's summary with the key as a bearer token and the zone as a query", async () => {
seen.length = 0
expect(await run("ok")).toEqual(body)
expect(seen).toEqual([{ path: "/api/backend/v1/usage/summary", tz: "Asia/Seoul", auth: "Bearer ok" }])
})

test("tolerates a trailing slash on the base URL", async () => {
expect(await run("ok", `${url}/`)).toEqual(body)
})

test("a refused key, the rate limit and a missing route fall back quietly", async () => {
expect(await run("wrong")).toBeUndefined()
expect(await run("limited")).toBeUndefined()
expect(await run("ok", `http://127.0.0.1:${server.port}/old`)).toBeUndefined()
})

test("a body that does not parse or misses fields falls back", async () => {
expect(await run("garbled")).toBeUndefined()
expect(await run("partial")).toBeUndefined()
})

test("an unreachable console falls back", async () => {
expect(await run("ok", "http://127.0.0.1:1/api/backend/v1")).toBeUndefined()
})

test("a console slower than the timeout falls back", async () => {
const start = Date.now()
expect(await run("slow")).toBeUndefined()
expect(Date.now() - start).toBeLessThan(6_500)
}, 10_000)
})
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { described } from "./metadata"
import { QueryBoolean } from "./query"
import { ProviderV2 } from "@redrob-code/core/provider"
import { ModelV2 } from "@redrob-code/core/model"
import { Balance } from "@redrob-code/core/balance"

const ConsoleStateResponse = Schema.Struct({
consoleManagedProviders: Schema.mutable(Schema.Array(Schema.String)),
Expand Down Expand Up @@ -99,6 +100,11 @@ export class WorktreeApiError extends Schema.ErrorClass<WorktreeApiError>("Workt
},
{ httpApiStatus: 400 },
) {}
/** The caller's IANA zone, so "today" and "this month" are the user's own. */
export const ConsoleUsageQuery = Schema.Struct({
...WorkspaceRoutingQueryFields,
tz: Schema.String,
})
export const SessionListQuery = Schema.Struct({
...WorkspaceRoutingQueryFields,
roots: Schema.optional(QueryBoolean),
Expand All @@ -121,6 +127,7 @@ export const ExperimentalPaths = {
console: "/experimental/console",
consoleOrgs: "/experimental/console/orgs",
consoleSwitch: "/experimental/console/switch",
consoleUsage: "/experimental/console/usage",
tool: "/experimental/tool",
toolIDs: "/experimental/tool/ids",
worktree: "/experimental/worktree",
Expand Down Expand Up @@ -167,6 +174,17 @@ export const ExperimentalApi = HttpApi.make("experimental")
description: "Get the available Console orgs across logged-in accounts, including the current active org.",
}),
),
HttpApiEndpoint.get("consoleUsage", ExperimentalPaths.consoleUsage, {
query: ConsoleUsageQuery,
success: described(Schema.NullOr(Balance.Summary), "Console balance and spend, or null"),
}).annotateMerge(
OpenApi.annotations({
identifier: "experimental.console.usage",
summary: "Get Console balance and spend",
description:
"The Redrob workspace's balance and today's and this month's spend across every device, read from the Console with the Redrob provider's key. Null when there is no key or the Console does not answer.",
}),
),
HttpApiEndpoint.post("consoleSwitch", ExperimentalPaths.consoleSwitch, {
query: WorkspaceRoutingQuery,
payload: ConsoleSwitchPayload,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@ import type { SessionID } from "@/session/schema"
import { ToolJsonSchema } from "@/tool/json-schema"
import { ToolRegistry } from "@/tool/registry"
import { Worktree } from "@/worktree"
import { Provider } from "@/provider/provider"
import { Balance } from "@redrob-code/core/balance"
import { CONSOLE_URL } from "@redrob-code/core/plugin/provider/redrob-constants"
import { ProviderV2 } from "@redrob-code/core/provider"
import { Effect, Option } from "effect"
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse"
import { HttpApiBuilder, HttpApiError } from "effect/unstable/httpapi"
import { InstanceHttpApi } from "../api"
import {
ConsoleSwitchPayload,
ConsoleUsageQuery,
SessionListQuery,
ToolListQuery,
UsageQuery,
Expand All @@ -41,6 +46,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper
const sessions = yield* Session.Service
const background = yield* BackgroundJob.Service
const flags = yield* RuntimeFlags.Service
const providers = yield* Provider.Service

const capabilities = Effect.fn("ExperimentalHttpApi.capabilities")(function* () {
return {
Expand Down Expand Up @@ -191,6 +197,19 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper
return yield* sessions.usage({ day: ctx.query.day, month: ctx.query.month })
})

const consoleUsage = Effect.fn("ExperimentalHttpApi.consoleUsage")(function* (ctx: {
query: typeof ConsoleUsageQuery.Type
}) {
// The key and base URL the Redrob provider sends inference with, resolved the way the SDK gets
// them (`options.apiKey`, else the merged credential). "public" is the keyless placeholder.
const info = (yield* providers.list())[ProviderV2.ID.redrob]
const options = (info?.options ?? {}) as { apiKey?: unknown; baseURL?: unknown }
const key = typeof options.apiKey === "string" ? options.apiKey : info?.key
if (!key || key === "public") return null
const url = typeof options.baseURL === "string" && options.baseURL ? options.baseURL : CONSOLE_URL
return (yield* Balance.summary({ url, key, tz: ctx.query.tz })) ?? null
})

const resource = Effect.fn("ExperimentalHttpApi.resource")(function* () {
return yield* mcp.resources()
})
Expand All @@ -200,6 +219,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper
.handle("console", getConsole)
.handle("consoleOrgs", listConsoleOrgs)
.handle("consoleSwitch", switchConsole)
.handle("consoleUsage", consoleUsage)
.handle("tool", tool)
.handle("toolIDs", toolIDs)
.handle("worktree", worktree)
Expand Down
10 changes: 10 additions & 0 deletions packages/redrob/test/server/httpapi-exercise/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,16 @@ const scenarios: Scenario[] = [
check(body === false, "background route should be a no-op without running subagents")
}),
http.protected.get("/experimental/resource", "experimental.resource.list").json(),
http.protected
.get("/experimental/console/usage", "experimental.console.usage")
.at((ctx) => ({
path: `/experimental/console/usage?${new URLSearchParams({ tz: "Asia/Seoul" })}`,
headers: ctx.headers(),
}))
.json(200, (body) => {
// The exerciser has no Redrob key, so the route answers null rather than reaching the console.
check(body === null, "console usage should be null without a Redrob key")
}),
http.protected
.get("/experimental/usage", "experimental.usage.get")
.at((ctx) => ({
Expand Down
38 changes: 38 additions & 0 deletions packages/sdk/js/src/v2/gen/sdk.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ import type {
ExperimentalConsoleListOrgsErrors,
ExperimentalConsoleListOrgsResponses,
ExperimentalConsoleSwitchOrgResponses,
ExperimentalConsoleUsageErrors,
ExperimentalConsoleUsageResponses,
ExperimentalControlPlaneMoveSessionErrors,
ExperimentalControlPlaneMoveSessionResponses,
ExperimentalExtensionsCallErrors,
Expand Down Expand Up @@ -945,6 +947,42 @@ export class Console extends HeyApiClient {
})
}

/**
* Get Console balance and spend
*
* The Redrob workspace's balance and today's and this month's spend across every device, read from the Console with the Redrob provider's key. Null when there is no key or the Console does not answer.
*/
public usage<ThrowOnError extends boolean = false>(
parameters: {
directory?: string
workspace?: string
tz: string
},
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams(
[parameters],
[
{
args: [
{ in: "query", key: "directory" },
{ in: "query", key: "workspace" },
{ in: "query", key: "tz" },
],
},
],
)
return (options?.client ?? this.client).get<
ExperimentalConsoleUsageResponses,
ExperimentalConsoleUsageErrors,
ThrowOnError
>({
url: "/experimental/console/usage",
...options,
...params,
})
}

/**
* Switch active Console org
*
Expand Down
46 changes: 46 additions & 0 deletions packages/sdk/js/src/v2/gen/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2322,6 +2322,22 @@ export type EffectHttpApiErrorInternalServerError = {
_tag: "InternalServerError"
}

export type ConsoleUsagePeriod = {
since: string
spend: number
requestCount: number
}

export type ConsoleUsageSummary = {
currency: string
balance: number
complimentary: boolean
plan?: string
tz: string
today: ConsoleUsagePeriod
month: ConsoleUsagePeriod
}

export type ToolListItem = {
id: string
description: string
Expand Down Expand Up @@ -8510,6 +8526,36 @@ export type ExperimentalConsoleListOrgsResponses = {
export type ExperimentalConsoleListOrgsResponse =
ExperimentalConsoleListOrgsResponses[keyof ExperimentalConsoleListOrgsResponses]

export type ExperimentalConsoleUsageData = {
body?: never
path?: never
query: {
directory?: string
workspace?: string
tz: string
}
url: "/experimental/console/usage"
}

export type ExperimentalConsoleUsageErrors = {
/**
* Bad request
*/
400: BadRequestError
}

export type ExperimentalConsoleUsageError = ExperimentalConsoleUsageErrors[keyof ExperimentalConsoleUsageErrors]

export type ExperimentalConsoleUsageResponses = {
/**
* Console balance and spend, or null
*/
200: ConsoleUsageSummary
}

export type ExperimentalConsoleUsageResponse =
ExperimentalConsoleUsageResponses[keyof ExperimentalConsoleUsageResponses]

export type ExperimentalConsoleSwitchOrgData = {
body?: {
accountID: string
Expand Down
Loading
Loading