fix(server): report the Grok account email so usage limits merge across environments (#12588)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
This commit is contained in:
3 files changed
+170
-87
No files matched your search
@@ -19,7 +19,7 @@ import {
|
||||
enrichGrokSnapshot,
|
||||
} from "../Layers/GrokProvider.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { readGrokUsageLimits } from "../Layers/grokUsageLimits.ts";
|
||||
import { readGrokAccount } from "../Layers/grokUsageLimits.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -133,8 +133,13 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(
|
||||
Effect.flatMap((snapshot) =>
|
||||
effectiveConfig.enabled && snapshot.installed && snapshot.auth.status === "authenticated"
|
||||
? readGrokUsageLimits(processEnv).pipe(
|
||||
Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
|
||||
? readGrokAccount(processEnv).pipe(
|
||||
// The email lets clients recognize one account signed in on several environments.
|
||||
Effect.map(({ email, usageLimits }) => ({
|
||||
...snapshot,
|
||||
auth: email ? { ...snapshot.auth, email } : snapshot.auth,
|
||||
usageLimits,
|
||||
})),
|
||||
)
|
||||
: Effect.succeed(snapshot),
|
||||
),
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
parseGrokModelsCliOutput,
|
||||
} from "./GrokProvider.ts";
|
||||
import { execScriptSource, writeFakeCli } from "../../testUtils/fakeCli.ts";
|
||||
import { grokUsageResponseToLimits, readGrokUsageLimits } from "./grokUsageLimits.ts";
|
||||
import { grokUsageResponseToLimits, readGrokAccount } from "./grokUsageLimits.ts";
|
||||
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
@@ -586,7 +586,7 @@ describe("Grok usage limits", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
it.layer(NodeServices.layer)("readGrokAccount", (it) => {
|
||||
it.effect("reads the configured Grok home and prefers the current login scope to legacy", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -595,7 +595,7 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
NodePath.join(directory, "auth.json"),
|
||||
'{"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828":{"key":"session-token","auth_mode":"oauth"},"https://accounts.x.ai/sign-in":{"key":"legacy-token"}}',
|
||||
);
|
||||
const limits = yield* readGrokUsageLimits({
|
||||
const { usageLimits: limits } = yield* readGrokAccount({
|
||||
GROK_HOME: directory,
|
||||
HOME: "/unrelated-home",
|
||||
}).pipe(
|
||||
@@ -621,7 +621,7 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
it.effect(
|
||||
"uses GROK_AUTH without reading stored credentials and accepts the legacy login scope",
|
||||
() =>
|
||||
readGrokUsageLimits({
|
||||
readGrokAccount({
|
||||
GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"legacy-token"}}',
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
@@ -645,7 +645,9 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
);
|
||||
}),
|
||||
),
|
||||
Effect.tap((limits) => Effect.sync(() => expect(limits.windows[0]?.usedPercent).toBe(12))),
|
||||
Effect.tap(({ usageLimits }) =>
|
||||
Effect.sync(() => expect(usageLimits.windows[0]?.usedPercent).toBe(12)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -684,7 +686,7 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
GROK_CONFIG_PATH: "/custom-config.toml",
|
||||
},
|
||||
]) {
|
||||
const limits = yield* readGrokUsageLimits({
|
||||
const { usageLimits: limits } = yield* readGrokAccount({
|
||||
HOME: "/definitely/not/a/grok-home",
|
||||
...environment,
|
||||
}).pipe(
|
||||
@@ -706,7 +708,7 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const directory = yield* fs.makeTempDirectoryScoped();
|
||||
const client = HttpClient.make(() => Effect.die("must not request without credentials"));
|
||||
const missing = yield* readGrokUsageLimits({ HOME: directory }).pipe(
|
||||
const { usageLimits: missing } = yield* readGrokAccount({ HOME: directory }).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, client),
|
||||
);
|
||||
expect(missing.unavailable?.reason).toBe("unsupported");
|
||||
@@ -714,7 +716,7 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
"private-token-invalid-json",
|
||||
'{"https://accounts.x.ai/sign-in":{"key":42}}',
|
||||
]) {
|
||||
const malformed = yield* readGrokUsageLimits({
|
||||
const { usageLimits: malformed } = yield* readGrokAccount({
|
||||
GROK_HOME: directory,
|
||||
GROK_AUTH: contents,
|
||||
}).pipe(Effect.provideService(HttpClient.HttpClient, client));
|
||||
@@ -735,7 +737,7 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
'[grok_com_config]\nissuer = "https://custom.example"',
|
||||
'endpoints.proxy = "https://custom.example"',
|
||||
]) {
|
||||
const limits = yield* readGrokUsageLimits({
|
||||
const { usageLimits: limits } = yield* readGrokAccount({
|
||||
GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-token"}}',
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
@@ -758,15 +760,16 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("sanitizes HTTP failures and malformed billing responses", () =>
|
||||
it.effect("sanitizes HTTP failures and malformed billing responses, keeping the account", () =>
|
||||
Effect.gen(function* () {
|
||||
for (const response of [
|
||||
new Response("private response", { status: 401 }),
|
||||
Response.json({ config: { creditUsagePercent: "private-value" } }),
|
||||
]) {
|
||||
const limits = yield* readGrokUsageLimits({
|
||||
const { email, usageLimits: limits } = yield* readGrokAccount({
|
||||
HOME: "/definitely/not/a/grok-home",
|
||||
GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"private-token"}}',
|
||||
GROK_AUTH:
|
||||
'{"https://accounts.x.ai/sign-in":{"key":"private-token","email":"[email protected]"}}',
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
@@ -775,6 +778,7 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(email).toBe("[email protected]");
|
||||
expect(limits.windows).toEqual([]);
|
||||
expect(limits.unavailable).toEqual({
|
||||
reason: "probeFailed",
|
||||
@@ -784,3 +788,58 @@ it.layer(NodeServices.layer)("readGrokUsageLimits", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("readGrokAccount email", (it) => {
|
||||
it.effect("names the account whose limits were read, and nothing for other auth", () =>
|
||||
Effect.gen(function* () {
|
||||
const current = '"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"';
|
||||
const cases = [
|
||||
[
|
||||
{ GROK_AUTH: `{${current}:{"key":"t","email":" [email protected] "}}` },
|
||||
"[email protected]",
|
||||
],
|
||||
[
|
||||
{
|
||||
GROK_AUTH: `{${current}:{"key":"t","email":"[email protected]"},"https://accounts.x.ai/sign-in":{"key":"t","email":"[email protected]"}}`,
|
||||
},
|
||||
"[email protected]",
|
||||
],
|
||||
[{ GROK_AUTH: `{${current}:{"key":"t"}}` }, undefined],
|
||||
[
|
||||
{
|
||||
GROK_AUTH: `{${current}:{"key":"t","email":"[email protected]"}}`,
|
||||
XAI_API_KEY: "api-key",
|
||||
},
|
||||
undefined,
|
||||
],
|
||||
[
|
||||
{
|
||||
GROK_AUTH: `{${current}:{"key":"t","email":"[email protected]","auth_mode":"api_key"}}`,
|
||||
},
|
||||
undefined,
|
||||
],
|
||||
[{ GROK_AUTH: "not-json" }, undefined],
|
||||
] as const;
|
||||
for (const [environment, expected] of cases) {
|
||||
const { email, usageLimits } = yield* readGrokAccount({
|
||||
HOME: "/definitely/not/a/grok-home",
|
||||
...environment,
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ config: { creditUsagePercent: 25 } }),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(email).toBe(expected);
|
||||
if (expected) expect(usageLimits.windows[0]?.usedPercent).toBe(25);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -18,6 +18,7 @@ const GrokCredentials = Schema.Record(
|
||||
Schema.Struct({
|
||||
key: Schema.optional(Schema.String),
|
||||
auth_mode: Schema.optional(Schema.String),
|
||||
email: Schema.optional(Schema.String),
|
||||
}),
|
||||
);
|
||||
const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(GrokCredentials));
|
||||
@@ -65,72 +66,97 @@ export function grokUsageResponseToLimits(
|
||||
return makeUsageLimits({ checkedAt, windows: [window] });
|
||||
}
|
||||
|
||||
export const readGrokUsageLimits = Effect.fn("readGrokUsageLimits")(function* (
|
||||
/**
|
||||
* The grok.com login the CLI uses by default, or undefined when the CLI is
|
||||
* configured to pick another account, endpoint, or an API key.
|
||||
*/
|
||||
const readGrokCredential = Effect.fn("readGrokCredential")(function* (
|
||||
environment: NodeJS.ProcessEnv,
|
||||
) {
|
||||
// T3's ACP adapter explicitly selects API-key auth when this variable is set.
|
||||
if (environment.XAI_API_KEY?.trim()) return undefined;
|
||||
// Alternate auth deployments can select another scope or account from the same file.
|
||||
if (
|
||||
[
|
||||
"GROK_OIDC_ISSUER",
|
||||
"GROK_OIDC_CLIENT_ID",
|
||||
"GROK_OAUTH2_ISSUER",
|
||||
"GROK_OAUTH2_CLIENT_ID",
|
||||
"GROK_OAUTH2_PRINCIPAL_TYPE",
|
||||
"GROK_OAUTH2_PRINCIPAL_ID",
|
||||
"GROK_AUTH_PROVIDER_COMMAND",
|
||||
"GROK_LOCAL_AUTH",
|
||||
"GROK_CLI_CHAT_PROXY_BASE_URL",
|
||||
"GROK_MODELS_BASE_URL",
|
||||
"GROK_CONFIG",
|
||||
"GROK_CONFIG_PATH",
|
||||
].some((name) => environment[name]?.trim())
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const home =
|
||||
environment.GROK_HOME?.trim() ||
|
||||
path.join(environment.HOME || environment.USERPROFILE || NodeOS.homedir(), ".grok");
|
||||
for (const configPath of [
|
||||
path.join(home, "config.toml"),
|
||||
path.join(home, "managed_config.toml"),
|
||||
path.join(home, "requirements.toml"),
|
||||
"/etc/grok/managed_config.toml",
|
||||
"/etc/grok/requirements.toml",
|
||||
]) {
|
||||
const config = yield* fs.readFileString(configPath).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed("") : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
// These sections can change the selected account or endpoint. Leave custom deployments to the CLI.
|
||||
if (/^\s*(?:\[\[?\s*)?["']?(?:auth|grok_com_config|endpoints)["']?\s*[.\]=]/m.test(config)) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
const contents =
|
||||
environment.GROK_AUTH?.trim() ||
|
||||
(yield* fs.readFileString(path.join(home, "auth.json")).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
|
||||
}),
|
||||
));
|
||||
const credentials = yield* decodeCredentials(contents);
|
||||
// Never pick an arbitrary account from other deployments stored in the same file.
|
||||
const credential =
|
||||
credentials["https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"] ??
|
||||
credentials["https://accounts.x.ai/sign-in"];
|
||||
return credential?.auth_mode === "api_key" ? undefined : credential;
|
||||
});
|
||||
|
||||
/**
|
||||
* Reads the default grok.com login once and reports its usage limits along with
|
||||
* its email, so the email always names the account whose quota was read.
|
||||
*/
|
||||
export const readGrokAccount = Effect.fn("readGrokAccount")(function* (
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
) {
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
return yield* Effect.gen(function* () {
|
||||
// T3's ACP adapter explicitly selects API-key auth when this variable is set.
|
||||
if (environment.XAI_API_KEY?.trim()) {
|
||||
return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
|
||||
}
|
||||
// Alternate auth deployments can select another scope or account from the same file.
|
||||
if (
|
||||
[
|
||||
"GROK_OIDC_ISSUER",
|
||||
"GROK_OIDC_CLIENT_ID",
|
||||
"GROK_OAUTH2_ISSUER",
|
||||
"GROK_OAUTH2_CLIENT_ID",
|
||||
"GROK_OAUTH2_PRINCIPAL_TYPE",
|
||||
"GROK_OAUTH2_PRINCIPAL_ID",
|
||||
"GROK_AUTH_PROVIDER_COMMAND",
|
||||
"GROK_LOCAL_AUTH",
|
||||
"GROK_CLI_CHAT_PROXY_BASE_URL",
|
||||
"GROK_MODELS_BASE_URL",
|
||||
"GROK_CONFIG",
|
||||
"GROK_CONFIG_PATH",
|
||||
].some((name) => environment[name]?.trim())
|
||||
) {
|
||||
return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
|
||||
}
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const home =
|
||||
environment.GROK_HOME?.trim() ||
|
||||
path.join(environment.HOME || environment.USERPROFILE || NodeOS.homedir(), ".grok");
|
||||
for (const configPath of [
|
||||
path.join(home, "config.toml"),
|
||||
path.join(home, "managed_config.toml"),
|
||||
path.join(home, "requirements.toml"),
|
||||
"/etc/grok/managed_config.toml",
|
||||
"/etc/grok/requirements.toml",
|
||||
]) {
|
||||
const config = yield* fs.readFileString(configPath).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed("") : Effect.fail(error),
|
||||
}),
|
||||
);
|
||||
// These sections can change the selected account or endpoint. Leave custom deployments to the CLI.
|
||||
if (/^\s*(?:\[\[?\s*)?["']?(?:auth|grok_com_config|endpoints)["']?\s*[.\]=]/m.test(config)) {
|
||||
return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
|
||||
}
|
||||
}
|
||||
const contents =
|
||||
environment.GROK_AUTH?.trim() ||
|
||||
(yield* fs.readFileString(path.join(home, "auth.json")).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
|
||||
}),
|
||||
));
|
||||
const credentials = yield* decodeCredentials(contents);
|
||||
// Never pick an arbitrary account from other deployments stored in the same file.
|
||||
const credential =
|
||||
credentials["https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"] ??
|
||||
credentials["https://accounts.x.ai/sign-in"];
|
||||
const token = credential?.auth_mode === "api_key" ? undefined : credential?.key?.trim();
|
||||
if (!token) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
|
||||
const probeFailed = makeUnavailableUsageLimits({
|
||||
checkedAt,
|
||||
reason: "probeFailed",
|
||||
message: "Grok could not read usage limits.",
|
||||
});
|
||||
const credential = yield* Effect.option(
|
||||
readGrokCredential(environment).pipe(Effect.timeout("10 seconds")),
|
||||
);
|
||||
if (Option.isNone(credential)) return { email: undefined, usageLimits: probeFailed };
|
||||
const email = credential.value?.email?.trim() || undefined;
|
||||
const token = credential.value?.key?.trim();
|
||||
if (!token) {
|
||||
return { email, usageLimits: makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }) };
|
||||
}
|
||||
// A failed quota request still knows which account it asked about.
|
||||
const usageLimits = yield* Effect.gen(function* () {
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const response = yield* client.execute(
|
||||
HttpClientRequest.get("https://cli-chat-proxy.grok.com/v1/billing?format=credits").pipe(
|
||||
@@ -143,14 +169,7 @@ export const readGrokUsageLimits = Effect.fn("readGrokUsageLimits")(function* (
|
||||
return grokUsageResponseToLimits(body, checkedAt);
|
||||
}).pipe(
|
||||
Effect.timeout("10 seconds"),
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(
|
||||
makeUnavailableUsageLimits({
|
||||
checkedAt,
|
||||
reason: "probeFailed",
|
||||
message: "Grok could not read usage limits.",
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(probeFailed)),
|
||||
);
|
||||
return { email, usageLimits };
|
||||
});
|
||||
Reference in new issue
Block a user