The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import type { ServerProviderUsageWindow } from "@t3tools/contracts"; |
| 2 | import { |
| 3 | clampPercent, |
| 4 | makeUnavailableUsageLimits, |
| 5 | makeUsageLimits, |
| 6 | } from "@t3tools/provider-core/server/usageLimits"; |
| 7 | import * as DateTime from "effect/DateTime"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | import * as HttpClient from "effect/http/HttpClient"; |
| 11 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 12 | |
| 13 | const Instant = Schema.Finite.check( |
| 14 | Schema.isBetween({ minimum: -8640000000000000, maximum: 8640000000000000 }), |
| 15 | ); |
| 16 | const Meter = Schema.Struct({ |
| 17 | percent: Schema.Finite, |
| 18 | limited: Schema.Boolean, |
| 19 | resetsAt: Instant, |
| 20 | }); |
| 21 | const BudgetModel = Schema.Struct({ |
| 22 | providerID: Schema.String, |
| 23 | modelID: Schema.String, |
| 24 | name: Schema.String, |
| 25 | spent: Schema.optionalKey(Schema.Finite), |
| 26 | }); |
| 27 | // Decode only fields needed by T3, independently of the pinned 2.0 client. |
| 28 | const ResponseBody = Schema.Struct({ |
| 29 | location: Schema.Struct({ directory: Schema.String }), |
| 30 | data: Schema.NullOr( |
| 31 | Schema.Struct({ |
| 32 | workspace: Schema.Struct({ |
| 33 | id: Schema.String, |
| 34 | name: Schema.optionalKey(Schema.String), |
| 35 | usageURL: Schema.String, |
| 36 | }), |
| 37 | go: Schema.optionalKey(Schema.Struct({ rolling: Meter, weekly: Meter, monthly: Meter })), |
| 38 | budgets: Schema.Array( |
| 39 | Schema.Struct({ |
| 40 | id: Schema.String, |
| 41 | limit: Schema.Finite, |
| 42 | spent: Schema.Finite, |
| 43 | scope: Schema.Literals(["each", "combined"]), |
| 44 | per: Schema.Literals(["set", "model"]), |
| 45 | coverage: Schema.Literals(["all", "models"]), |
| 46 | models: Schema.Array(BudgetModel), |
| 47 | shared: Schema.Boolean, |
| 48 | resetsAt: Instant, |
| 49 | }), |
| 50 | ), |
| 51 | }), |
| 52 | ), |
| 53 | }); |
| 54 | |
| 55 | const Providers = Schema.Struct({ |
| 56 | data: Schema.Array( |
| 57 | Schema.Struct({ |
| 58 | id: Schema.String, |
| 59 | integrationID: Schema.optionalKey(Schema.String), |
| 60 | }), |
| 61 | ), |
| 62 | }); |
| 63 | |
| 64 | const resetTime = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); |
| 65 | const budgetPercent = (spent: number, limit: number) => |
| 66 | limit <= 0 ? 100 : clampPercent((spent / limit) * 100); |
| 67 | |
| 68 | /** Undefined alone permits the legacy credential reader; null data is authoritative. */ |
| 69 | export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(function* ( |
| 70 | directory: string, |
| 71 | ) { |
| 72 | const checkedAt = DateTime.formatIso(yield* DateTime.now); |
| 73 | return yield* Effect.gen(function* () { |
| 74 | const response = yield* HttpClient.get("/api/experimental/usage/limits", { |
| 75 | urlParams: { "location[directory]": directory }, |
| 76 | }); |
| 77 | if ( |
| 78 | response.status === 404 || |
| 79 | response.status === 405 || |
| 80 | (response.status === 200 && |
| 81 | response.headers["content-type"]?.split(";")[0]?.trim() === "text/html") |
| 82 | ) |
| 83 | return undefined; |
| 84 | const body = yield* HttpClientResponse.filterStatusOk(response).pipe( |
| 85 | Effect.flatMap(HttpClientResponse.schemaBodyJson(ResponseBody)), |
| 86 | ); |
| 87 | if (body.data === null) |
| 88 | return makeUnavailableUsageLimits({ |
| 89 | checkedAt, |
| 90 | reason: "unsupported", |
| 91 | message: "No OpenCode Console workspace is signed in.", |
| 92 | }); |
| 93 | const { go, budgets, workspace } = body.data; |
| 94 | const usageURL = URL.parse(workspace.usageURL); |
| 95 | const externalUsage = |
| 96 | usageURL?.protocol === "http:" || usageURL?.protocol === "https:" |
| 97 | ? { externalUsage: { label: workspace.name?.trim() || workspace.id, url: usageURL.href } } |
| 98 | : {}; |
| 99 | // A Zen-only workspace has neither a Go subscription nor spend limits. |
| 100 | if (!go && budgets.length === 0) |
| 101 | return { |
| 102 | ...makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }), |
| 103 | ...externalUsage, |
| 104 | }; |
| 105 | const consoleProviders = budgets.some( |
| 106 | (budget) => budget.coverage === "all" && budget.per === "set", |
| 107 | ) |
| 108 | ? yield* HttpClient.get("/api/provider", { |
| 109 | urlParams: { "location[directory]": directory }, |
| 110 | }).pipe( |
| 111 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 112 | Effect.flatMap(HttpClientResponse.schemaBodyJson(Providers)), |
| 113 | Effect.map((page) => |
| 114 | page.data |
| 115 | .filter( |
| 116 | (provider) => |
| 117 | provider.integrationID === "opencode" && provider.id !== "opencode-go", |
| 118 | ) |
| 119 | .map((provider) => provider.id), |
| 120 | ), |
| 121 | Effect.orElseSucceed(() => []), |
| 122 | ) |
| 123 | : []; |
| 124 | const windows: ServerProviderUsageWindow[] = []; |
| 125 | if (go) { |
| 126 | for (const [key, kind, label, duration] of [ |
| 127 | ["rolling", "session", "Session", 300], |
| 128 | ["weekly", "weekly", "Weekly", 10080], |
| 129 | ["monthly", "monthly", "Monthly", undefined], |
| 130 | ] as const) { |
| 131 | const meter = go[key]; |
| 132 | windows.push({ |
| 133 | id: `go_${key}`, |
| 134 | kind, |
| 135 | label: `Go · ${label}`, |
| 136 | usedPercent: meter.limited ? 100 : clampPercent(meter.percent), |
| 137 | resetsAt: resetTime(meter.resetsAt), |
| 138 | ...(duration === undefined ? {} : { windowDurationMins: duration }), |
| 139 | }); |
| 140 | } |
| 141 | } |
| 142 | for (const budget of budgets) { |
| 143 | const scope = budget.shared || budget.scope === "combined" ? "Shared" : "Individual"; |
| 144 | const covered = |
| 145 | budget.coverage === "all" |
| 146 | ? "All spend" |
| 147 | : budget.models.map((model) => model.name).join(", ") || "Models"; |
| 148 | if ( |
| 149 | budget.per === "model" && |
| 150 | budget.coverage === "models" && |
| 151 | budget.models.length > 0 && |
| 152 | budget.models.every((model) => model.spent !== undefined) |
| 153 | ) { |
| 154 | for (const model of budget.models) { |
| 155 | windows.push({ |
| 156 | id: `budget_${budget.id}_${model.providerID}_${model.modelID}`, |
| 157 | kind: "other", |
| 158 | label: `Console · ${scope} · ${model.name}`, |
| 159 | modelIds: [`${model.providerID}/${model.modelID}`], |
| 160 | usedPercent: budgetPercent(model.spent ?? budget.spent, budget.limit), |
| 161 | resetsAt: resetTime(budget.resetsAt), |
| 162 | }); |
| 163 | } |
| 164 | } else { |
| 165 | windows.push({ |
| 166 | id: `budget_${budget.id}`, |
| 167 | kind: "other", |
| 168 | label: `Console · ${scope} · ${covered}${budget.per === "model" ? " · Most used model" : ""}`, |
| 169 | // Aggregate per-model spend cannot identify the exhausted model. |
| 170 | ...(budget.per === "model" |
| 171 | ? { modelIds: [] } |
| 172 | : budget.coverage === "models" |
| 173 | ? { |
| 174 | modelIds: budget.models.map((model) => `${model.providerID}/${model.modelID}`), |
| 175 | } |
| 176 | : { providerIds: consoleProviders }), |
| 177 | usedPercent: budgetPercent(budget.spent, budget.limit), |
| 178 | resetsAt: resetTime(budget.resetsAt), |
| 179 | }); |
| 180 | } |
| 181 | } |
| 182 | return { ...makeUsageLimits({ checkedAt, windows }), ...externalUsage }; |
| 183 | }).pipe( |
| 184 | Effect.timeout("5 seconds"), |
| 185 | Effect.orElseSucceed(() => |
| 186 | makeUnavailableUsageLimits({ |
| 187 | checkedAt, |
| 188 | reason: "probeFailed", |
| 189 | message: "OpenCode could not read workspace usage.", |
| 190 | }), |
| 191 | ), |
| 192 | ); |
| 193 | }); |