Files
t3code/packages/provider-opencode/src/server/usageLimits.ts
T

127 lines
4.8 KiB
TypeScript

import type { ServerProviderUsageWindow } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
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 * as Hex from "effect/encoding/Hex";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientRequest from "effect/http/HttpClientRequest";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
import {
clampPercent,
makeUnavailableUsageLimits,
makeUsageLimits,
} from "@t3tools/provider-core/server/usageLimits";
import * as HostProcess from "@t3tools/shared/HostProcess";
const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknown) });
const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String });
const decodeAuthFile = Schema.decodeEffect(Schema.fromJsonString(AuthFile));
const decodeApiAuth = Schema.decodeUnknownOption(ApiAuth);
const UsageWindow = Schema.Struct({
percent: Schema.Finite,
resetsAt: Schema.DateTimeUtcFromString,
});
const UsageResponse = Schema.Struct({
usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
});
/** External OpenCode servers own their credentials; never read the host's account for them. */
export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: {
readonly enabled: boolean;
readonly serverUrl: string;
readonly environment: NodeJS.ProcessEnv;
}) {
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const unsupported = makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
if (!input.enabled || input.serverUrl.trim()) return unsupported;
return yield* Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const env = input.environment;
const dataHome =
env.XDG_DATA_HOME ||
path.join(
env.HOME || env.USERPROFILE || (yield* HostProcess.HomeDirectory),
".local",
"share",
);
const authPath = path.join(dataHome, "opencode", "auth.json");
const contents =
env.OPENCODE_AUTH_CONTENT ||
(yield* fs.readFileString(authPath).pipe(
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
}),
));
const auth = yield* decodeAuthFile(contents);
const apiAuth = decodeApiAuth(auth["opencode-go"]);
// OpenCode overlays stored API credentials after environment credentials.
const apiKey = (Option.isSome(apiAuth) ? apiAuth.value.key : env.OPENCODE_API_KEY)?.trim();
if (!apiKey) return unsupported;
const client = yield* HttpClient.HttpClient;
const response = yield* client.execute(
HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
HttpClientRequest.bearerToken(apiKey),
),
);
// A valid Zen key can exist without a Go subscription.
if (response.status === 403) return unsupported;
const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(UsageResponse)),
);
const windows: ServerProviderUsageWindow[] = [
{
id: "go_rolling",
kind: "session",
label: "Go · Session",
windowDurationMins: 5 * 60,
usedPercent: clampPercent(body.usage.rolling.percent),
resetsAt: DateTime.formatIso(body.usage.rolling.resetsAt),
},
{
id: "go_weekly",
kind: "weekly",
label: "Go · Weekly",
windowDurationMins: 7 * 24 * 60,
usedPercent: clampPercent(body.usage.weekly.percent),
resetsAt: DateTime.formatIso(body.usage.weekly.resetsAt),
},
{
id: "go_monthly",
kind: "monthly",
label: "Go · Monthly",
usedPercent: clampPercent(body.usage.monthly.percent),
resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt),
},
];
const crypto = yield* Crypto.Crypto;
// Go's usage response has no account ID. An unkeyed hash matches across
// environments without a shared secret. It permits offline guesses, but
// Go keys are randomly generated.
const credentialFingerprint = yield* crypto
.digest("SHA-256", new TextEncoder().encode(`opencode-go\0${apiKey}`))
.pipe(Effect.map(Hex.encode), Effect.orDie);
return {
...makeUsageLimits({ checkedAt, windows }),
credentialFingerprint,
};
}).pipe(
Effect.timeout("5 seconds"),
Effect.orElseSucceed(() =>
makeUnavailableUsageLimits({
checkedAt,
reason: "probeFailed",
message: "OpenCode Go could not read usage.",
}),
),
);
});