diff --git a/apps/server/package.json b/apps/server/package.json index 9e05831bee12..d3765b52c5d2 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -66,6 +66,7 @@ "diff": "8.0.3", "effect": "catalog:", "ffi-rs": "1.3.2", + "jsonc-parser": "3.3.1", "node-pty": "^1.2.0-beta.15", "playwright-core": "1.64.1", "proper-lockfile": "4.1.2", diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index 63154f4e9949..b14bf7a5ffa9 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -136,6 +136,10 @@ export const codexRoutesSpendNativeQuota = ( ): boolean => account.requiresOpenaiAuth && account.account?.type !== "apiKey" && routesToNativeOpenai(config); +/** Shown when a custom model provider serves the instance; its gateway reports the accounts. */ +export const CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE = + "Not applicable: this instance routes through a custom model provider, not OpenAI quota."; + const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const; const CODEX_CATALOG_REFRESH_TIMEOUT_MS = 3_000; const CODEX_CONFIG_PROBE_TIMEOUT_MS = 3_000; @@ -1133,7 +1137,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu // Sign-in guidance still applies when Codex itself says it needs an OpenAI login. const usageLimits = !snapshot.nativeUsage && !accountStatus.message - ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }) + ? makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + // A gateway route reports its pooled accounts itself; say so rather than vanish. + ...(snapshot.endpoint ? { message: CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE } : {}), + }) : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits ? makeUnavailableUsageLimits({ checkedAt, diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 021c3ddb5703..7f18ac8ae267 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -49,6 +49,7 @@ import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; import { + CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE, checkCodexProviderStatus, mapCodexModelCapabilities, type CodexAppServerProviderSnapshot, @@ -734,6 +735,25 @@ it.layer( }), ); + it.effect("says why usage is not applicable for a gateway-routed instance", () => + Effect.gen(function* () { + const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => + Effect.succeed( + makeCodexProbeSnapshot({ + account: { account: null, requiresOpenaiAuth: false }, + endpoint: "http://127.0.0.1:3425", + nativeUsage: false, + }), + ), + ); + assert.strictEqual(status.usageLimits?.unavailable?.reason, "unsupported"); + assert.strictEqual( + status.usageLimits?.unavailable?.message, + CODEX_CUSTOM_PROVIDER_USAGE_MESSAGE, + ); + }), + ); + it.effect("offers cyber access only on catalog models that advertise it", () => Effect.gen(function* () { const catalogModel = (slug: string, cyber?: Array<"standard" | "daybreakBlue">) => ({ diff --git a/apps/server/src/usage/UsageLimitSources.test.ts b/apps/server/src/usage/UsageLimitSources.test.ts index fc8a93f9e1bc..60a225c2b933 100644 --- a/apps/server/src/usage/UsageLimitSources.test.ts +++ b/apps/server/src/usage/UsageLimitSources.test.ts @@ -1,4 +1,5 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { ProviderDriverKind, @@ -105,6 +106,7 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () => HttpClient.make(() => Effect.die("Unexpected network request")), ), NodeCrypto.layer, + NodeServices.layer, ]), ), ); @@ -171,6 +173,7 @@ it.effect("reads a management key from its secret provider", () => { ), ), NodeCrypto.layer, + NodeServices.layer, ]), ); }); diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts index d6f867d621d2..4e45ab799013 100644 --- a/apps/server/src/usage/UsageLimitSources.ts +++ b/apps/server/src/usage/UsageLimitSources.ts @@ -16,7 +16,9 @@ import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; import * as Semaphore from "effect/Semaphore"; @@ -29,6 +31,7 @@ import { resolveSettingsSecrets } from "../secrets/settingsSecretValue.ts"; import * as Settings from "../serverSettings.ts"; import { windowLimitsModel } from "../provider/claudeUsageLimits.ts"; import { makeCliproxyApi } from "./cliproxyApi.ts"; +import { discoverGatewayOrigins, gatewayOrigin, makeMagpieApi } from "./magpieQuotas.ts"; export class UsageLimitSources extends Context.Service< UsageLimitSources, @@ -61,6 +64,9 @@ function missingManagementKey(config: UsageLimitSourceConfig): string { /** @public */ export const make = Effect.gen(function* () { const api = yield* makeCliproxyApi; + const magpie = yield* makeMagpieApi; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const settingsService = yield* Settings.ServerSettingsService; const secrets = yield* SecretResolver.SecretResolver; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; @@ -95,12 +101,15 @@ export const make = Effect.gen(function* () { checkedAt, } as const; const managementKey = yield* readManagementKey(config); - if (managementKey.length === 0) { + // A Magpie gateway on loopback answers without a key. + if (config.kind === "cliproxy" && managementKey.length === 0) { return { ...base, accounts: [], error: missingManagementKey(config) }; } - const accounts = yield* api - .readAccounts({ url: config.url, managementKey }) - .pipe(Effect.result); + const accounts = yield* ( + config.kind === "magpie" + ? magpie.readAccounts({ url: config.url, managementKey }) + : api.readAccounts({ url: config.url, managementKey }) + ).pipe(Effect.result); if (accounts._tag === "Failure") { yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure }); return { ...base, accounts: [], error: accounts.failure.detail }; @@ -108,6 +117,62 @@ export const make = Effect.gen(function* () { return { ...base, accounts: accounts.success }; }); + // Gateways the enabled instances already route through, read without + // configuration. An origin that does not answer the quotas route is not a + // Magpie gateway and is dropped quietly; nobody configured it. + const discoverMagpieSources = Effect.fn("UsageLimitSources.discoverMagpieSources")( + function* ( + settings: ServerSettings | null, + configured: ReadonlyArray, + ) { + if (!settings) return []; + const explicit = new Set( + Object.values(settings.usageLimitSources) + .filter((config) => config.enabled && config.kind === "magpie") + .map((config) => gatewayOrigin(config.url)), + ); + const origins = (yield* discoverGatewayOrigins(settings, process.env).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + )).filter((origin) => !explicit.has(origin)); + const reads = yield* Effect.forEach( + origins, + (origin) => + magpie.readAccounts({ url: origin, managementKey: "" }).pipe( + Effect.map((accounts) => ({ origin, accounts })), + Effect.option, + ), + { concurrency: 4 }, + ); + const checkedAt = DateTime.formatIso(yield* DateTime.now); + // A forward and the gateway it reaches report the same accounts: show one. + const seen = new Set(configured.map((source) => accountSet(source.accounts))); + const discovered: UsageLimitSourceSnapshot[] = []; + for (const read of reads) { + if (read._tag === "None") continue; + const key = accountSet(read.value.accounts); + if (seen.has(key)) continue; + seen.add(key); + discovered.push({ + id: `magpie:${new URL(read.value.origin).host}` as UsageLimitSourceId, + kind: "magpie", + label: "Magpie", + origin: read.value.origin, + endpoint: read.value.origin, + checkedAt, + accounts: read.value.accounts, + }); + } + return discovered.length > 1 + ? discovered.map((source) => ({ + ...source, + label: `Magpie · ${source.id.slice("magpie:".length)}`, + })) + : discovered; + }, + Effect.orElseSucceed((): ReadonlyArray => []), + ); + const publish = Effect.fn("UsageLimitSources.publish")(function* ( next: ReadonlyArray, ) { @@ -131,7 +196,7 @@ export const make = Effect.gen(function* () { ([id, config]) => readSource(id as UsageLimitSourceId, config), { concurrency: 4 }, ); - yield* publish(snapshots); + yield* publish([...snapshots, ...(yield* discoverMagpieSources(settings, snapshots))]); }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true })); // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption. @@ -142,7 +207,7 @@ export const make = Effect.gen(function* () { Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })), ); const config = settings.usageLimitSources[input.sourceId]; - if (!config?.enabled) { + if (!config?.enabled || config.kind !== "cliproxy") { return yield* new UsageLimitSourceError({ detail: "The usage limit source is missing or disabled.", }); @@ -209,6 +274,13 @@ export const make = Effect.gen(function* () { } satisfies UsageLimitSources["Service"]; }); +function accountSet(accounts: ReadonlyArray<{ readonly id: string }>): string { + return accounts + .map((account) => account.id) + .sort() + .join("\n"); +} + export const layer = Layer.effect(UsageLimitSources, make).pipe( Layer.provide(SecretResolverLayer.layer), ); diff --git a/apps/server/src/usage/magpieQuotas.test.ts b/apps/server/src/usage/magpieQuotas.test.ts new file mode 100644 index 000000000000..1776dc2ce9b6 --- /dev/null +++ b/apps/server/src/usage/magpieQuotas.test.ts @@ -0,0 +1,279 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import { ProviderDriverKind, ProviderInstanceId, type ServerSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as TestClock from "effect/testing/TestClock"; +import * as FileSystem from "effect/FileSystem"; +import { HttpClient, HttpClientResponse } from "effect/http"; + +import { codexPlanLabel } from "../provider/CodexProvider.ts"; +import { + codexBaseUrl, + discoverGatewayOrigins, + gatewayOrigin, + isPrivateOrigin, + magpieQuotasToAccounts, + makeMagpieApi, + openCodeBaseUrls, +} from "./magpieQuotas.ts"; + +const checkedAt = "2026-11-18T22:00:00.000Z"; + +/** The shapes a Magpie gateway answers with, one per kind of entry it reports. */ +const entries = [ + { + provider: "claude", + name: "Claude Code", + kind: "subscription", + plan: "max", + user: "first@example.com", + windows: [ + { name: "5 hours", used: 70, remaining: 30, resetsAt: "2026-11-19T01:40:00Z" }, + { name: "7 days", used: 82, remaining: 18, resetsAt: "2026-11-22T02:00:00Z" }, + { name: "7 days · Fable", used: 57, remaining: 43, resetsAt: "2026-11-22T02:00:00Z" }, + ], + readAt: "2026-11-18T21:59:00Z", + }, + { + provider: "codex", + name: "Codex", + kind: "subscription", + plan: "pro", + user: "first@example.com", + windows: [ + { name: "5 hours", used: 12, resetsAt: "2026-11-18T23:00:00Z" }, + { name: "7 days", used: 100, resetsAt: "2026-11-21T17:48:40Z" }, + ], + }, + { + provider: "codex", + name: "Codex", + kind: "subscription", + plan: "team", + user: "first@example.com · Team", + error: "Payment Required", + }, + { + provider: "magpie-go", + name: "Magpie Go", + kind: "plan", + user: "oc-key", + error: + "this key has no OpenCode Go subscription: Go belongs to the member who subscribed, in that workspace", + }, + { provider: "claude", user: "second@example.com", error: "upstream timed out" }, +]; + +describe("magpieQuotasToAccounts", () => { + const accounts = magpieQuotasToAccounts(entries, checkedAt); + + it("maps every pooled account with windows that line up with the native probes", () => { + const claude = accounts[0]!; + expect(claude.driver).toBe("claudeAgent"); + expect(claude.email).toBe("first@example.com"); + expect(claude.plan).toBe("Claude Max"); + expect(claude.usageLimits.windows).toEqual([ + { + id: "five_hour", + kind: "session", + label: "Session", + usedPercent: 70, + windowDurationMins: 300, + resetsAt: "2026-11-19T01:40:00.000Z", + }, + { + id: "seven_day", + kind: "weekly", + label: "Weekly", + usedPercent: 82, + windowDurationMins: 7 * 24 * 60, + resetsAt: "2026-11-22T02:00:00.000Z", + }, + // Same id the Claude probe gives its model-scoped weekly window. + expect.objectContaining({ id: "seven_day_fable", label: "Weekly · Fable" }), + ]); + const codex = accounts[1]!; + expect(codex.plan).toBe(codexPlanLabel("pro")); + expect(codex.usageLimits.windows.map((window) => [window.id, window.kind])).toEqual([ + ["primary", "session"], + ["secondary", "weekly"], + ]); + }); + + it("marks standing refusals not applicable and passing failures as failed reads", () => { + const [, , team, go, timedOut] = accounts; + expect(team!.email).toBe("first@example.com · Team"); + expect(team!.usageLimits.unavailable).toEqual({ + reason: "unsupported", + message: "Payment Required.", + }); + expect(go!.driver).toBe("opencode"); + expect(go!.email).toBeUndefined(); + expect(go!.usageLimits.unavailable).toEqual({ + reason: "unsupported", + message: "This key has no OpenCode Go subscription.", + }); + expect(timedOut!.usageLimits.unavailable?.reason).toBe("probeFailed"); + }); +}); + +describe("gateway discovery", () => { + it("reads the selected Codex provider's base URL, honouring a launch override", () => { + const toml = [ + 'model_provider = "magpie_asus"', + "[model_providers.openai]", + 'base_url = "https://api.openai.com/v1"', + "[model_providers.magpie_asus]", + 'name = "Magpie"', + 'base_url = "http://127.0.0.1:13425/v1"', + "[model_providers.magpie_asus.auth]", + 'command = "/bin/cat"', + ].join("\n"); + expect(codexBaseUrl(toml, "")).toBe("http://127.0.0.1:13425/v1"); + expect(codexBaseUrl(toml, "-c model_provider=openai")).toBe("https://api.openai.com/v1"); + expect(codexBaseUrl("model = 'x'", undefined)).toBeUndefined(); + expect( + codexBaseUrl( + "model_provider = 'm'\n[model_providers.m]\nbase_url = 'http://127.0.0.1:1/v1'", + "", + ), + ).toBe("http://127.0.0.1:1/v1"); + }); + + it("reads OpenCode provider base URLs from JSONC", () => { + const jsonc = `{ + // comments are allowed + "provider": { + "magpie": { "options": { "baseURL": "http://127.0.0.1:3425/v1" } }, + "other": { "options": {} }, + }, + }`; + expect(openCodeBaseUrls(jsonc)).toEqual(["http://127.0.0.1:3425/v1"]); + expect(openCodeBaseUrls("not json")).toEqual([]); + }); + + it("only probes hosts the user runs", () => { + expect(gatewayOrigin("http://127.0.0.1:3425/v1")).toBe("http://127.0.0.1:3425"); + expect(gatewayOrigin("file:///tmp/x")).toBeNull(); + for (const origin of [ + "http://127.0.0.1:3425", + "http://localhost:3425", + "http://192.168.0.27:3425", + "http://100.85.225.50:3425", + "https://box.tail138dbd.ts.net", + ]) { + expect(isPrivateOrigin(origin), origin).toBe(true); + } + for (const origin of ["https://api.openai.com", "https://fcm.example.com", "http://8.8.8.8"]) { + expect(isPrivateOrigin(origin), origin).toBe(false); + } + }); + + it.effect("collects distinct private gateway origins across enabled instances", () => + Effect.gen(function* () { + const files: Record = { + "/codex-home/config.toml": + 'model_provider = "m"\n[model_providers.m]\nbase_url = "http://127.0.0.1:13425/v1"\n', + "/home/u/.config/opencode/opencode.jsonc": + '{ "provider": { "magpie": { "options": { "baseURL": "http://127.0.0.1:13425/v1" } } } }', + "/claude/settings.json": '{ "env": { "ANTHROPIC_BASE_URL": "http://127.0.0.1:3425" } }', + "/off/config.toml": + 'model_provider = "m"\n[model_providers.m]\nbase_url = "http://127.0.0.1:9999/v1"\n', + }; + const instance = (driver: string, config: unknown, enabled = true) => ({ + driver: ProviderDriverKind.make(driver), + enabled, + config, + }); + const settings = { + providerInstances: { + [ProviderInstanceId.make("codex")]: instance("codex", { homePath: "/codex-home" }), + [ProviderInstanceId.make("opencode")]: instance("opencode", {}), + [ProviderInstanceId.make("claude")]: instance("claudeAgent", { + launchArgs: "--settings /claude/settings.json", + }), + [ProviderInstanceId.make("off")]: instance("codex", { homePath: "/off" }, false), + }, + } as unknown as Pick; + const origins = yield* discoverGatewayOrigins(settings, { HOME: "/home/u" }).pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ + // A file the fixture lacks reads as empty, as a missing one does. + readFileString: (path) => Effect.succeed(files[path] ?? ""), + }), + ), + Effect.provide(NodeServices.layer), + ); + expect(origins).toEqual(["http://127.0.0.1:13425", "http://127.0.0.1:3425"]); + }), + ); +}); + +describe("makeMagpieApi", () => { + const run = (managementKey: string, status = 200) => { + const seen: Array<{ url: string; authorization: string | undefined }> = []; + const http = HttpClient.make((request) => + Effect.sync(() => { + seen.push({ url: request.url, authorization: request.headers.authorization }); + return HttpClientResponse.fromWeb( + request, + Response.json({ object: "list", data: entries.slice(0, 1) }, { status }), + ); + }), + ); + return makeMagpieApi.pipe( + Effect.flatMap((api) => api.readAccounts({ url: "http://127.0.0.1:3425/v1", managementKey })), + Effect.result, + Effect.map((result) => ({ result, seen })), + Effect.provideService(HttpClient.HttpClient, http), + ); + }; + + it.effect("reads the quotas route at the gateway origin, keyless on loopback", () => + Effect.gen(function* () { + const { result, seen } = yield* run(""); + expect(seen).toEqual([ + { url: "http://127.0.0.1:3425/v1/magpie/quotas", authorization: undefined }, + ]); + expect(result._tag === "Success" && result.success.map((account) => account.id)).toEqual([ + "claude:first@example.com", + ]); + }), + ); + + it.effect("gives up on a gateway whose body never finishes", () => + Effect.gen(function* () { + const http = HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(new ReadableStream({ start() {} }), { + headers: { "content-type": "application/json" }, + }), + ), + ), + ); + const fiber = yield* makeMagpieApi.pipe( + Effect.flatMap((api) => + api.readAccounts({ url: "http://127.0.0.1:3425", managementKey: "" }), + ), + Effect.result, + Effect.provideService(HttpClient.HttpClient, http), + Effect.forkChild, + ); + yield* TestClock.adjust("5 seconds"); + const result = yield* Fiber.join(fiber); + expect(result._tag === "Failure" && result.failure.detail).toMatch(/did not answer/); + }), + ); + + it.effect("sends a configured gateway key and explains a refusal", () => + Effect.gen(function* () { + const { result, seen } = yield* run("gateway-key", 401); + expect(seen[0]!.authorization).toBe("Bearer gateway-key"); + expect(result._tag === "Failure" && result.failure.detail).toMatch(/refused the key/); + }), + ); +}); diff --git a/apps/server/src/usage/magpieQuotas.ts b/apps/server/src/usage/magpieQuotas.ts new file mode 100644 index 000000000000..0098b6ee46c1 --- /dev/null +++ b/apps/server/src/usage/magpieQuotas.ts @@ -0,0 +1,373 @@ +/** + * Magpie gateway quotas: `GET /v1/magpie/quotas` reports every pooled account. + * Gateways are found from the base URLs enabled instances already use; an + * origin that does not answer the route is not a gateway and is dropped. + */ +import * as NodeOS from "node:os"; + +import { + ProviderDriverKind, + UsageLimitSourceError, + type ServerProviderUsageWindow, + type ServerSettings, + type UsageLimitSourceAccount, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { parse as parseJsonc } from "jsonc-parser"; + +import { + clampPercent, + makeUnavailableUsageLimits, + makeUsageLimits, +} from "@t3tools/provider-core/server/usageLimits"; + +import { codexPlanLabel } from "../provider/CodexProvider.ts"; + +const QuotaWindow = Schema.Struct({ + name: Schema.String, + used: Schema.Finite, + resetsAt: Schema.optional(Schema.NullOr(Schema.String)), +}); +const QuotaEntry = Schema.Struct({ + provider: Schema.String, + name: Schema.optional(Schema.String), + kind: Schema.optional(Schema.String), + plan: Schema.optional(Schema.String), + user: Schema.optional(Schema.String), + windows: Schema.optional(Schema.Array(QuotaWindow)), + readAt: Schema.optional(Schema.String), + error: Schema.optional(Schema.String), +}); +const QuotasResponse = Schema.Struct({ data: Schema.Array(QuotaEntry) }); +const isProviderDriverKind = Schema.is(ProviderDriverKind); +const isUsageLimitSourceError = Schema.is(UsageLimitSourceError); +export type MagpieQuotaEntry = typeof QuotaEntry.Type; + +const MINUTES: Record = { + minute: 1, + hour: 60, + day: 24 * 60, + week: 7 * 24 * 60, + month: 30 * 24 * 60, +}; + +/** Magpie's provider names → the driver whose icon and pool the account joins. */ +function driverFor(provider: string): ProviderDriverKind | null { + switch (provider) { + case "claude": + return ProviderDriverKind.make("claudeAgent"); + case "codex": + return ProviderDriverKind.make("codex"); + case "magpie-go": + case "opencode-go": + case "opencode": + return ProviderDriverKind.make("opencode"); + default: + return isProviderDriverKind(provider) ? provider : null; + } +} + +function slug(value: string): string { + return value + .toLowerCase() + .replace(/[^a-z0-9]+/g, "_") + .replace(/^_|_$/g, ""); +} + +/** + * `5 hours`, `7 days`, `7 days · Fable` → a window whose id matches what the + * driver's own probe would publish (Claude `five_hour`/`seven_day`, Codex + * `primary`/`secondary`), so a native read and a gateway read of the same + * account land on the same row. + */ +function magpieWindow( + driver: ProviderDriverKind, + window: typeof QuotaWindow.Type, +): ServerProviderUsageWindow { + const [span = window.name, ...scopeParts] = window.name.split("·").map((part) => part.trim()); + const scope = scopeParts.join(" · "); + const match = /^(\d+(?:\.\d+)?)\s*(minute|hour|day|week|month)s?$/i.exec(span); + const mins = match ? Number(match[1]) * MINUTES[match[2]!.toLowerCase()]! : undefined; + const kind: ServerProviderUsageWindow["kind"] = + mins === undefined + ? "other" + : mins >= MINUTES.month! + ? "monthly" + : mins >= MINUTES.week! + ? "weekly" + : "session"; + const baseLabel = + kind === "session" + ? "Session" + : kind === "weekly" + ? "Weekly" + : kind === "monthly" + ? "Monthly" + : span; + const baseId = + driver === "claudeAgent" && mins === 5 * 60 + ? "five_hour" + : driver === "claudeAgent" && mins === MINUTES.week + ? "seven_day" + : driver === "codex" && kind === "weekly" + ? "secondary" + : driver === "codex" && kind !== "other" + ? "primary" + : slug(span) || "window"; + const parsedReset = window.resetsAt ? DateTime.make(window.resetsAt) : Option.none(); + const resetsAt = Option.isSome(parsedReset) ? DateTime.formatIso(parsedReset.value) : undefined; + return { + id: scope ? `${baseId}_${slug(scope)}` : baseId, + kind, + label: scope ? `${baseLabel} · ${scope}` : baseLabel, + usedPercent: clampPercent(window.used), + ...(mins !== undefined ? { windowDurationMins: mins } : {}), + ...(resetsAt ? { resetsAt } : {}), + }; +} + +function planLabel(driver: ProviderDriverKind, entry: MagpieQuotaEntry): string | undefined { + if (!entry.plan) return entry.kind === "plan" ? entry.name : undefined; + if (driver === "codex") return codexPlanLabel(entry.plan) ?? entry.plan; + if (driver === "claudeAgent") { + return `Claude ${entry.plan.charAt(0).toUpperCase()}${entry.plan.slice(1)}`; + } + return entry.plan; +} + +/** + * A vendor refusal that will not clear by itself (no subscription on the key, + * a lapsed workspace) is "not applicable", not a failure to retry. + */ +function isStandingRefusal(error: string): boolean { + return /payment required|no .*subscription|not subscribed|no active (plan|subscription)/i.test( + error, + ); +} + +/** Magpie's sentences run long; the first clause names the reason. */ +function shortReason(error: string): string { + const first = error.split(/[:;]\s/)[0]!.trim(); + const sentence = first.charAt(0).toUpperCase() + first.slice(1); + return sentence.endsWith(".") ? sentence : `${sentence}.`; +} + +export function magpieQuotasToAccounts( + entries: ReadonlyArray, + checkedAt: string, +): ReadonlyArray { + const accounts: UsageLimitSourceAccount[] = []; + const seen = new Set(); + for (const entry of entries) { + const driver = driverFor(entry.provider); + if (!driver) continue; + const user = entry.user?.trim() || entry.name?.trim() || entry.provider; + const id = `${entry.provider}:${user}`; + if (seen.has(id)) continue; + seen.add(id); + const windows = (entry.windows ?? []).map((window) => magpieWindow(driver, window)); + const plan = planLabel(driver, entry); + const usageLimits = entry.error + ? makeUnavailableUsageLimits({ + checkedAt: entry.readAt ?? checkedAt, + reason: isStandingRefusal(entry.error) ? "unsupported" : "probeFailed", + message: shortReason(entry.error), + }) + : makeUsageLimits({ checkedAt: entry.readAt ?? checkedAt, windows }); + accounts.push({ + id, + driver, + // Only a real address is an email; Go keys carry a key name instead. + ...(/^[^\s@]+@[^\s@]+$/.test(user.split(" · ")[0]!) ? { email: user } : {}), + ...(plan ? { plan } : {}), + usageLimits, + }); + } + return accounts; +} + +export const makeMagpieApi = Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + const readAccounts = Effect.fn("MagpieApi.readAccounts")(function* (config: { + readonly url: string; + readonly managementKey: string; + }): Effect.fn.Return, UsageLimitSourceError> { + const origin = gatewayOrigin(config.url); + if (!origin) { + return yield* new UsageLimitSourceError({ detail: "The Magpie gateway URL is not valid." }); + } + const request = HttpClientRequest.get(`${origin}/v1/magpie/quotas`).pipe( + config.managementKey ? HttpClientRequest.bearerToken(config.managementKey) : (r) => r, + ); + // One deadline covers headers and body: a stalled body must not hold the refresh lock. + const body = yield* client.execute(request).pipe( + Effect.flatMap((response) => + response.status === 401 || response.status === 403 + ? Effect.fail( + new UsageLimitSourceError({ + detail: "The Magpie gateway refused the key. Add the gateway key to this source.", + }), + ) + : HttpClientResponse.filterStatusOk(response).pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(QuotasResponse)), + Effect.mapError( + () => + new UsageLimitSourceError({ + detail: "The Magpie gateway did not report quotas.", + }), + ), + ), + ), + Effect.timeout("5 seconds"), + Effect.mapError((error) => + isUsageLimitSourceError(error) + ? error + : new UsageLimitSourceError({ detail: "The Magpie gateway did not answer." }), + ), + ); + return magpieQuotasToAccounts(body.data, DateTime.formatIso(yield* DateTime.now)); + }); + return { readAccounts }; +}); + +/** `http://127.0.0.1:3425/v1` → `http://127.0.0.1:3425`; anything not http(s) is no gateway. */ +export function gatewayOrigin(url: string | undefined): string | null { + if (!url) return null; + try { + const parsed = new URL(url.trim()); + return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null; + } catch { + return null; + } +} + +/** + * Discovery only knocks on hosts the user runs: loopback, private and + * tailnet ranges. A vendor API an instance also names never gets the probe. + */ +export function isPrivateOrigin(origin: string): boolean { + const host = new URL(origin).hostname.replace(/^\[|\]$/g, "").toLowerCase(); + if (host === "localhost" || host === "::1" || host.endsWith(".local")) return true; + if (host.endsWith(".ts.net") || (host.includes(":") && /^f[cd]/.test(host))) return true; + const octets = host.split(".").map(Number); + if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet))) return false; + const [a = -1, b = -1] = octets; + return ( + a === 127 || + a === 10 || + (a === 192 && b === 168) || + (a === 172 && b >= 16 && b <= 31) || + (a === 100 && b >= 64 && b <= 127) + ); +} + +/** The selected provider's `base_url` in a Codex `config.toml`, or a `-c model_provider=` override. */ +export function codexBaseUrl(toml: string, launchArgs: string | undefined): string | undefined { + const override = /model_provider\s*=\s*"?([\w.-]+)"?/.exec(launchArgs ?? "")?.[1]; + const provider = override ?? /^\s*model_provider\s*=\s*["']([^"']+)["']/m.exec(toml)?.[1]; + if (!provider) return undefined; + let inSection = false; + for (const line of toml.split(/\r?\n/)) { + const header = /^\s*\[([^\]]+)\]\s*$/.exec(line)?.[1]?.trim(); + if (header !== undefined) { + inSection = header === `model_providers.${provider}`; + continue; + } + if (!inSection) continue; + const value = /^\s*base_url\s*=\s*["']([^"']+)["']/.exec(line)?.[1]; + if (value) return value; + } + return undefined; +} + +/** Every `provider.*.options.baseURL` in an OpenCode config file. */ +export function openCodeBaseUrls(jsonc: string): ReadonlyArray { + const parsed: unknown = parseJsonc(jsonc); + if (typeof parsed !== "object" || parsed === null) return []; + const providers = (parsed as { provider?: unknown }).provider; + if (typeof providers !== "object" || providers === null) return []; + return Object.values(providers).flatMap((entry) => { + const baseURL = (entry as { options?: { baseURL?: unknown } } | null)?.options?.baseURL; + return typeof baseURL === "string" ? [baseURL] : []; + }); +} + +function settingsArg(launchArgs: string | undefined): string | undefined { + return /--settings(?:=|\s+)(\S+)/.exec(launchArgs ?? "")?.[1]; +} + +function instanceConfig(value: unknown): Record { + return typeof value === "object" && value !== null ? (value as Record) : {}; +} + +function stringField(record: Record, key: string): string | undefined { + const value = record[key]; + return typeof value === "string" && value.trim() ? value.trim() : undefined; +} + +/** + * Distinct gateway origins the enabled provider instances send requests to. + * A file that is missing or unreadable contributes nothing. + */ +export const discoverGatewayOrigins = Effect.fn("discoverGatewayOrigins")(function* ( + settings: Pick, + env: NodeJS.ProcessEnv, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = env.HOME || env.USERPROFILE || NodeOS.homedir(); + const read = (file: string) => fs.readFileString(file).pipe(Effect.orElseSucceed(() => "")); + const urls: string[] = []; + for (const instance of Object.values(settings.providerInstances)) { + if (instance.enabled === false) continue; + const config = instanceConfig(instance.config); + const launchArgs = stringField(config, "launchArgs"); + // A secret-provider reference is not a plain path or URL; skip it. + const envValue = (name: string) => { + const value = instance.environment?.find((variable) => variable.name === name)?.value; + return (typeof value === "string" && value) || env[name]; + }; + switch (instance.driver) { + case "codex": { + const codexHome = + stringField(config, "homePath") ?? envValue("CODEX_HOME") ?? path.join(home, ".codex"); + const url = codexBaseUrl(yield* read(path.join(codexHome, "config.toml")), launchArgs); + if (url) urls.push(url); + break; + } + case "opencode": { + const configHome = envValue("XDG_CONFIG_HOME") || path.join(home, ".config"); + const explicit = envValue("OPENCODE_CONFIG"); + const files = explicit + ? [explicit] + : ["opencode.jsonc", "opencode.json"].map((name) => + path.join(configHome, "opencode", name), + ); + for (const file of files) urls.push(...openCodeBaseUrls(yield* read(file))); + break; + } + case "claudeAgent": { + const fromEnv = envValue("ANTHROPIC_BASE_URL"); + if (fromEnv) urls.push(fromEnv); + const files = [settingsArg(launchArgs), stringField(config, "homePath")] + .filter((file): file is string => Boolean(file)) + .map((file) => (file.endsWith(".json") ? file : path.join(file, "settings.json"))); + for (const file of files) { + const parsed: unknown = parseJsonc(yield* read(file)); + const url = (parsed as { env?: { ANTHROPIC_BASE_URL?: unknown } } | null)?.env + ?.ANTHROPIC_BASE_URL; + if (typeof url === "string") urls.push(url); + } + break; + } + } + } + const origins = urls.map(gatewayOrigin).filter((origin): origin is string => !!origin); + return [...new Set(origins)].filter(isPrivateOrigin); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 8ec1c7a02afc..33cb123307cf 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -2,8 +2,11 @@ import { CHATGPT_USAGE_URL, collectLimitAccounts, collectExternalUsageLinks, + collectAccountOwners, collectLimitNotices, - collectLimitPools, + collectLimitOwnerGroups, + collectNotApplicable, + UNASSIGNED_OWNER, cursorUsageWindowDetails, displayLimitWindows, formatResetsIn, @@ -18,7 +21,7 @@ import { } from "@t3tools/shared/usageLimits"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; -import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; +import { AlertTriangleIcon, CircleSlashIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; import { createContext, Fragment, @@ -585,13 +588,23 @@ function PoolWindowCard({ ); } -function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) { +function PoolSection({ + pool, + now, + nested, +}: { + readonly pool: LimitPool; + readonly now: number; + /** Under an owner heading, the provider heading drops a level. */ + readonly nested: boolean; +}) { const color = barColor(pool.driver); const label = providerClients.get(pool.driver)?.label ?? String(pool.driver); const windows = displayLimitWindows(pool); + const Heading = nested ? "h3" : "h2"; return (
-

+ {label} -

+ {windows.map((window) => { const details = pool.driver === "cursor" ? cursorUsageWindowDetails(window.id, pool) : undefined; @@ -628,22 +641,46 @@ export function UsageLimitsPooled({ }) { const [segmentPopover] = useState(() => PopoverCreateHandle()); const segmentPopoverActions = useRef(null); - const pools = collectLimitPools(collectLimitAccounts(presentations), now); + const groups = collectLimitOwnerGroups( + collectLimitAccounts(presentations), + collectAccountOwners(presentations), + now, + ); + const pools = groups.flatMap((group) => group.pools); const notices = collectLimitNotices(presentations); + const notApplicable = collectNotApplicable(presentations); + // Without an owner map everything is Unassigned; a lone heading would be noise. + const showOwners = groups.some((group) => group.owner !== UNASSIGNED_OWNER); const externalLinks = collectExternalUsageLinks(presentations); return (
- {pools.length === 0 && notices.length === 0 && externalLinks.length === 0 ? ( + {pools.length === 0 && + notices.length === 0 && + externalLinks.length === 0 && + notApplicable.length === 0 ? (

No provider on the selected environments reports subscription limits.

) : null} - {pools.map((pool) => ( - - - - ))} + {groups.map((group) => + showOwners ? ( +
+

+ {group.owner} +

+ {group.pools.map((pool) => ( + + ))} +
+ ) : ( + + {group.pools.map((pool) => ( + + ))} + + ), + )}
{({ payload }) => @@ -692,10 +729,36 @@ export function UsageLimitsPooled({
))} + ); } +/** Usage that cannot be read on this setup, with why; informational, not a warning. */ +function NotApplicableList({ + entries, +}: { + readonly entries: ReturnType; +}) { + if (entries.length === 0) return null; + return ( +
+

+ + Not applicable +

+
    + {entries.map((entry) => ( +
  • + {entry.subject}:{" "} + {entry.reason.replace(/^Not applicable:\s*/, "")} +
  • + ))} +
+
+ ); +} + function LimitNotices({ notices }: { readonly notices: readonly string[] }) { if (notices.length === 0) return null; return ( diff --git a/packages/contracts/src/providerUsageLimits.ts b/packages/contracts/src/providerUsageLimits.ts index 446d4f1f3184..904237533a7c 100644 --- a/packages/contracts/src/providerUsageLimits.ts +++ b/packages/contracts/src/providerUsageLimits.ts @@ -84,7 +84,7 @@ export type UsageLimitSourceAccount = typeof UsageLimitSourceAccount.Type; export const UsageLimitSourceSnapshot = Schema.Struct({ id: UsageLimitSourceId, - kind: Schema.Literal("cliproxy"), + kind: Schema.Literals(["cliproxy", "magpie"]), label: TrimmedNonEmptyString, /** Origin of the hub, which also serves the agents sent through it. */ origin: Schema.optional(TrimmedNonEmptyString), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 5e6917eb2819..ea599cb76614 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -947,8 +947,16 @@ export const AntigravitySettings = makeProviderSettingsSchema( ); export type AntigravitySettings = typeof AntigravitySettings.Type; +/** + * A read-only quota source: a CLIProxyAPI hub (management API) or a Magpie + * gateway (`/v1/magpie/quotas`). A Magpie gateway on loopback answers without + * a key; `managementKey` then holds its gateway key when it needs one. + */ +export const UsageLimitSourceKind = Schema.Literals(["cliproxy", "magpie"]); +export type UsageLimitSourceKind = typeof UsageLimitSourceKind.Type; + export const UsageLimitSourceConfig = Schema.Struct({ - kind: Schema.Literal("cliproxy"), + kind: UsageLimitSourceKind, label: Schema.optional(TrimmedNonEmptyString), url: TrimmedNonEmptyString, managementKey: SettingsSecretValue.pipe( @@ -1622,6 +1630,14 @@ export const ServerSettings = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed({})), ), + /** + * Who each subscription account belongs to, keyed by its email, so the + * Limits view can group accounts by owner. Unlisted accounts are Unassigned. + */ + usageAccountOwners: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), + /** Sent by the Usage tab with each summary request to this environment; edit in settings.json. Invalid values are ignored. */ usageModelFilter: ForwardCompatibleOptional(UsageModelFilter), }); @@ -2011,6 +2027,10 @@ export const ServerSettingsPatch = Schema.Struct({ usageModelAliases: Schema.optionalKey( Schema.Record(TrimmedNonEmptyString, Schema.NullOr(TrimmedNonEmptyString)), ), + /** Per-email owner; `null` returns the account to Unassigned. */ + usageAccountOwners: Schema.optionalKey( + Schema.Record(TrimmedNonEmptyString, Schema.NullOr(TrimmedNonEmptyString)), + ), }); export type ServerSettingsPatch = typeof ServerSettingsPatch.Type; diff --git a/packages/provider-opencode/src/server/status.test.ts b/packages/provider-opencode/src/server/status.test.ts index 732aa5156082..b029ea00ca78 100644 --- a/packages/provider-opencode/src/server/status.test.ts +++ b/packages/provider-opencode/src/server/status.test.ts @@ -326,9 +326,13 @@ it.effect("does not read local credentials for external or disabled OpenCode ins it.effect("keeps Go entitlement absence distinct from failed or malformed usage responses", () => Effect.gen(function* () { + // A refused key is a standing "not applicable"; a server error or an + // unreadable body is a failed probe worth a warning. for (const [status, reason] of [ [403, "unsupported"], - [401, "probeFailed"], + [402, "unsupported"], + [401, "unsupported"], + [500, "probeFailed"], [200, "probeFailed"], ] as const) { const limits = yield* readOpenCodeGoUsageLimits({ @@ -353,6 +357,10 @@ it.effect("keeps Go entitlement absence distinct from failed or malformed usage Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); NodeAssert.equal(limits.unavailable?.reason, reason); + NodeAssert.equal( + limits.unavailable?.message?.startsWith("Not applicable") ?? false, + reason === "unsupported", + ); NodeAssert.equal(limits.credentialFingerprint, undefined); NodeAssert.deepEqual(limits.windows, []); } diff --git a/packages/provider-opencode/src/server/usageLimits.ts b/packages/provider-opencode/src/server/usageLimits.ts index 03488e515a79..cbd8dc24b4a3 100644 --- a/packages/provider-opencode/src/server/usageLimits.ts +++ b/packages/provider-opencode/src/server/usageLimits.ts @@ -91,6 +91,8 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")( }) { const checkedAt = DateTime.formatIso(yield* DateTime.now); const unsupported = makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); + const notApplicable = (message: string) => + makeUnavailableUsageLimits({ checkedAt, reason: "unsupported", message }); if (!input.enabled || input.serverUrl.trim()) return unsupported; return yield* Effect.gen(function* () { @@ -131,7 +133,7 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")( ]; const keys = [...new Set([...storedKeys, goKey].filter((key): key is string => Boolean(key)))]; let apiKey = keys[0]; - if (!apiKey) return unsupported; + if (!apiKey) return notApplicable("Not applicable: no OpenCode Go key on this host."); const client = yield* HttpClient.HttpClient; const readUsage = (key: string) => @@ -146,8 +148,14 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")( apiKey = key; response = yield* readUsage(apiKey); } - // A valid Zen key can exist without a Go subscription. - if (response.status === 403) return unsupported; + // A refused key (no Go subscription, or a key Go does not know) is a + // standing state, not a probe to retry. + if (response.status === 401) { + return notApplicable("Not applicable: OpenCode Go does not accept this key."); + } + if (response.status === 402 || response.status === 403 || response.status === 404) { + return notApplicable("Not applicable: no active OpenCode Go subscription on this key."); + } const body = yield* HttpClientResponse.filterStatusOk(response).pipe( Effect.flatMap(HttpClientResponse.schemaBodyJson(UsageResponse)), ); diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 023c6eb74333..3021c659b0d5 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -407,6 +407,7 @@ export function applyServerSettingsPatch( sourceControlHosts: sourceControlHostsPatch, usagePriceOverrides: usagePriceOverridesPatch, usageModelAliases: usageModelAliasesPatch, + usageAccountOwners: usageAccountOwnersPatch, // Entry replacement: deepMerge would keep keys the client meant to clear. projectSettingsOverrides: projectSettingsOverridesPatch, projectAgentBrowserAccessOverrides: _legacyBrowserAccess, @@ -642,6 +643,14 @@ export function applyServerSettingsPatch( ), } : {}), + ...(usageAccountOwnersPatch !== undefined + ? { + usageAccountOwners: mergeSettingsEntries( + current.usageAccountOwners, + usageAccountOwnersPatch, + ), + } + : {}), ...(patch.sourceControlWriterModelSelection !== undefined ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection } : {}), diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index b66001ca1924..e94d4c33911a 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -17,7 +17,10 @@ import { withUsageLimitsCommands, collectLimitAccounts, collectExternalUsageLinks, + collectAccountOwners, collectLimitNotices, + collectLimitOwnerGroups, + collectNotApplicable, collectLimitPools, elapsedShare, exhaustedUsageWindow, @@ -1837,3 +1840,118 @@ describe("ChatGPT sharing presentation", () => { ).toBe(false); }); }); + +describe("owners and not-applicable usage", () => { + const checkedAt = "2026-09-03T11:00:00.000Z"; + const claude = ProviderDriverKind.make("claudeAgent"); + const codex = ProviderDriverKind.make("codex"); + const opencode = ProviderDriverKind.make("opencode"); + const limits = { checkedAt, windows: [window] }; + const magpie = { + id: UsageLimitSourceId.make("magpie:127.0.0.1:3425"), + kind: "magpie" as const, + label: "Magpie", + checkedAt, + accounts: [ + { id: "claude:a", driver: claude, email: "Owner.A@example.com", usageLimits: limits }, + { id: "claude:b", driver: claude, email: "second.a@example.com", usageLimits: limits }, + { id: "codex:c", driver: codex, email: "b@example.com", usageLimits: limits }, + { id: "codex:d", driver: codex, email: "nobody@example.com", usageLimits: limits }, + { + id: "codex:team", + driver: codex, + email: "owner.a@example.com · Team", + usageLimits: { + checkedAt, + windows: [], + unavailable: { reason: "unsupported" as const, message: "Payment Required." }, + }, + }, + { + id: "magpie-go:k", + driver: opencode, + usageLimits: { + checkedAt, + windows: [], + unavailable: { reason: "probeFailed" as const, message: "Upstream timed out." }, + }, + }, + ], + }; + const routed = provider({ + instanceId: ProviderInstanceId.make("magpie-codex"), + displayName: "Magpie Codex", + usageLimits: { + checkedAt, + windows: [], + unavailable: { reason: "unsupported", message: "Not applicable: gateway reports it." }, + }, + }); + // Unsupported, but asking the user to act: never "not applicable". + const signIn = provider({ + instanceId: ProviderInstanceId.make("antigravity"), + driver: ProviderDriverKind.make("antigravity"), + displayName: "Antigravity", + usageLimits: { + checkedAt, + windows: [], + unavailable: { reason: "unsupported", message: "Sign in with Google to see limits." }, + }, + }); + const presentations = (owners?: Record) => + new Map([ + [ + EnvironmentId.make("env-a"), + { + entry: { target: { label: "Crown" } }, + serverConfig: { + providers: [routed, signIn], + usageLimitSources: [magpie], + ...(owners ? { settings: { usageAccountOwners: owners } } : {}), + }, + }, + ], + ]); + + it("groups accounts by the configured owner, case-insensitively, Unassigned last", () => { + const view = presentations({ + "owner.a@example.com": "Kameron", + "second.a@example.com": "Kameron", + "b@example.com": "Jeff", + }); + const groups = collectLimitOwnerGroups( + collectLimitAccounts(view), + collectAccountOwners(view), + now, + ); + expect( + groups.map((group) => [ + group.owner, + group.pools.map((pool) => [pool.driver, pool.accounts.map((account) => account.key)]), + ]), + ).toEqual([ + ["Kameron", [[claude, [`env-a:${magpie.id}:claude:a`, `env-a:${magpie.id}:claude:b`]]]], + ["Jeff", [[codex, [`env-a:${magpie.id}:codex:c`]]]], + ["Unassigned", [[codex, [`env-a:${magpie.id}:codex:d`]]]], + ]); + }); + + it("puts everything in one Unassigned group without an owner map", () => { + const view = presentations(); + const groups = collectLimitOwnerGroups( + collectLimitAccounts(view), + collectAccountOwners(view), + now, + ); + expect(groups.map((group) => group.owner)).toEqual(["Unassigned"]); + }); + + it("lists not-applicable usage apart from failures", () => { + const view = presentations(); + expect(collectNotApplicable(view)).toEqual([ + { subject: "Magpie Codex", reason: "Not applicable: gateway reports it." }, + { subject: "Magpie · owner.a@example.com · Team", reason: "Payment Required." }, + ]); + expect(collectLimitNotices(view)).toEqual(["Magpie · k: Upstream timed out."]); + }); +}); diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 6fe6c70a89a4..0c8ddf78ff40 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -178,6 +178,9 @@ export type LimitPresentations = ReadonlyMap< readonly serverConfig: { readonly providers: readonly ServerProvider[]; readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined; + readonly settings?: + | { readonly usageAccountOwners?: Readonly> | undefined } + | undefined; } | null; } >; @@ -444,11 +447,123 @@ export function collectLimitNotices(presentations: LimitPresentations): readonly } else if (source.accounts.length === 0) { notices.add(`${label(environmentLabel, source.label)}: No accounts reported.`); } + for (const account of source.accounts) { + if (account.usageLimits.unavailable?.reason !== "probeFailed") continue; + const subject = `${source.label} · ${sourceAccountName(account)}`; + notices.add( + `${label(environmentLabel, subject)}: ${limitsNotice(account.usageLimits) ?? ""}`, + ); + } } } return [...notices]; } +/** A hub account by its email, else its id without the `provider:` prefix sources add. */ +function sourceAccountName(account: { readonly id: string; readonly email?: string | undefined }) { + return account.email ?? account.id.replace(/^[\w-]+:/, ""); +} + +/** + * Usage that cannot be read on its current setup (a key with no subscription, + * an instance whose gateway reports for it), so a missing bar reads as "not + * applicable". Only entries that say why are listed. + */ +export function collectNotApplicable( + presentations: LimitPresentations, +): ReadonlyArray<{ readonly subject: string; readonly reason: string }> { + const label = (environmentLabel: string, subject: string) => + presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject; + const entries = new Map(); + for (const presentation of presentations.values()) { + const environmentLabel = presentation.entry.target.label; + for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) { + // Only an explicit "Not applicable:" reason: other unsupported messages + // (a sign-in prompt, a sharing notice shown as a link) ask for action. + const unavailable = provider.usageLimits?.unavailable; + if ( + unavailable?.reason !== "unsupported" || + !unavailable.message?.startsWith(NOT_APPLICABLE_PREFIX) || + provider.usageLimits?.externalUsage + ) { + continue; + } + const name = provider.displayName?.trim() || String(provider.driver); + entries.set(label(environmentLabel, name), unavailable.message); + } + for (const source of presentation.serverConfig?.usageLimitSources ?? []) { + // Magpie maps only standing vendor refusals to unsupported. + if (source.kind !== "magpie") continue; + for (const account of source.accounts) { + const unavailable = account.usageLimits.unavailable; + if (unavailable?.reason !== "unsupported") continue; + entries.set( + label(environmentLabel, `${source.label} · ${sourceAccountName(account)}`), + unavailable.message ?? "This account has no subscription limits.", + ); + } + } + } + return [...entries].map(([subject, reason]) => ({ subject, reason })); +} + +export const UNASSIGNED_OWNER = "Unassigned"; + +const NOT_APPLICABLE_PREFIX = "Not applicable:"; + +/** `owner@example.com · Team` and `Owner@Example.com` look up the same owner. */ +function ownerLookupKey(email: string): string { + return email.split(" · ")[0]!.trim().toLowerCase(); +} + +/** The email → owner map from every connected environment; the first to name an email wins. */ +export function collectAccountOwners( + presentations: LimitPresentations, +): ReadonlyMap { + const owners = new Map(); + for (const presentation of presentations.values()) { + const map = presentation.serverConfig?.settings?.usageAccountOwners ?? {}; + for (const [email, owner] of Object.entries(map)) { + const key = ownerLookupKey(email); + if (key && owner.trim() && !owners.has(key)) owners.set(key, owner.trim()); + } + } + return owners; +} + +function accountOwner( + account: Pick, + owners: ReadonlyMap, +): string { + return (account.email && owners.get(ownerLookupKey(account.email))) || UNASSIGNED_OWNER; +} + +/** + * Accounts split by owner, each owner's accounts pooled per provider as + * {@link collectLimitPools} does. Owners keep the order the map names them; + * Unassigned comes last. With no owner map there is one group, so the view + * reads as it did before owners existed. + */ +export function collectLimitOwnerGroups( + accounts: readonly LimitAccount[], + owners: ReadonlyMap, + now: number, +): ReadonlyArray<{ readonly owner: string; readonly pools: readonly LimitPool[] }> { + const order = [...new Set(owners.values())]; + const byOwner = new Map(); + for (const account of accounts) { + const owner = accountOwner(account, owners); + const list = byOwner.get(owner); + if (list) list.push(account); + else byOwner.set(owner, [account]); + } + const rank = (owner: string) => + owner === UNASSIGNED_OWNER ? Number.POSITIVE_INFINITY : order.indexOf(owner); + return [...byOwner] + .sort(([left], [right]) => rank(left) - rank(right)) + .map(([owner, members]) => ({ owner, pools: collectLimitPools(members, now) })); +} + export interface LimitPoolMember { readonly account: LimitAccount; readonly window: ServerProviderUsageWindow; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 07806d3cac65..f6c84b2c7e32 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -938,6 +938,9 @@ importers: ffi-rs: specifier: 1.3.2 version: 1.3.2 + jsonc-parser: + specifier: 3.3.1 + version: 3.3.1 node-pty: specifier: 1.2.0-beta.15 version: 1.2.0-beta.15(patch_hash=ff8117509663fe1d5a07ef2648c324e80a9349b7d90401a00a591702615b8b30)