fix(grok-cli): align Grok Build with current subscription protocol (#2590)
This commit is contained in:
127
open-sse/services/grokCliModels.js
Normal file
127
open-sse/services/grokCliModels.js
Normal file
@@ -0,0 +1,127 @@
|
||||
import {
|
||||
GROK_CLI_BASE_URL,
|
||||
GROK_CLI_CLIENT_IDENTIFIER,
|
||||
GROK_CLI_MODEL,
|
||||
GROK_CLI_USER_AGENT,
|
||||
GROK_CLI_VERSION,
|
||||
} from "../config/grokCli.js";
|
||||
import { refreshProviderCredentials } from "./oauthCredentialManager.js";
|
||||
import { proxyAwareFetch } from "../utils/proxyFetch.js";
|
||||
|
||||
const MODELS_URL = `${GROK_CLI_BASE_URL}/models`;
|
||||
|
||||
function modelEntries(data) {
|
||||
const value = Array.isArray(data) ? data : data?.data ?? data?.models ?? data?.results ?? [];
|
||||
if (Array.isArray(value)) return value.map((item) => [null, item]);
|
||||
if (value && typeof value === "object") return Object.entries(value);
|
||||
return [];
|
||||
}
|
||||
|
||||
export function parseGrokCliModels(data) {
|
||||
const seen = new Set();
|
||||
const models = [];
|
||||
|
||||
for (const [key, raw] of modelEntries(data)) {
|
||||
const item = typeof raw === "string" ? { id: raw } : raw;
|
||||
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
|
||||
const id = String(
|
||||
item.id ?? item.model_id ?? item.modelId ?? item.model ?? item.slug ?? key ?? item.name ?? "",
|
||||
).trim();
|
||||
if (!id || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
|
||||
const model = {
|
||||
...item,
|
||||
id,
|
||||
name: item.display_name ?? item.displayName ?? item.name ?? id,
|
||||
};
|
||||
const contextLength = Number(
|
||||
item.context_length ?? item.contextLength ?? item.context_window ?? item.contextWindow,
|
||||
);
|
||||
const maxOutputTokens = Number(item.max_output_tokens ?? item.maxOutputTokens);
|
||||
if (Number.isFinite(contextLength) && contextLength > 0) model.contextLength = contextLength;
|
||||
if (Number.isFinite(maxOutputTokens) && maxOutputTokens > 0) {
|
||||
model.maxOutputTokens = maxOutputTokens;
|
||||
}
|
||||
if (id === GROK_CLI_MODEL) {
|
||||
model.contextLength ||= 500000;
|
||||
model.maxOutputTokens ||= 64000;
|
||||
}
|
||||
models.push(model);
|
||||
}
|
||||
|
||||
return models;
|
||||
}
|
||||
|
||||
function buildHeaders(accessToken, providerSpecificData = {}) {
|
||||
const headers = {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: "application/json",
|
||||
"User-Agent": GROK_CLI_USER_AGENT,
|
||||
"x-xai-token-auth": "xai-grok-cli",
|
||||
"x-grok-client-version": GROK_CLI_VERSION,
|
||||
"x-grok-client-identifier": GROK_CLI_CLIENT_IDENTIFIER,
|
||||
"x-grok-client-mode": "headless",
|
||||
};
|
||||
const email = providerSpecificData?.email;
|
||||
const userId = providerSpecificData?.userId || providerSpecificData?.principalId;
|
||||
if (email) headers["x-email"] = email;
|
||||
if (userId) headers["x-userid"] = userId;
|
||||
return headers;
|
||||
}
|
||||
|
||||
export async function resolveGrokCliModels(credentials, options = {}) {
|
||||
const {
|
||||
fetchFn = proxyAwareFetch,
|
||||
log = console,
|
||||
proxyOptions = null,
|
||||
onCredentialsRefreshed,
|
||||
} = options;
|
||||
let accessToken = credentials?.accessToken;
|
||||
if (!accessToken) return { models: [], warning: "Grok CLI access token is missing." };
|
||||
|
||||
const request = (token) => fetchFn(
|
||||
MODELS_URL,
|
||||
{
|
||||
method: "GET",
|
||||
headers: buildHeaders(token, credentials?.providerSpecificData),
|
||||
},
|
||||
proxyOptions,
|
||||
);
|
||||
|
||||
try {
|
||||
let response = await request(accessToken);
|
||||
if ((response.status === 401 || response.status === 403) && credentials?.refreshToken) {
|
||||
const refreshed = await refreshProviderCredentials(
|
||||
"grok-cli",
|
||||
credentials,
|
||||
log,
|
||||
proxyOptions,
|
||||
);
|
||||
if (refreshed?.accessToken) {
|
||||
accessToken = refreshed.accessToken;
|
||||
try {
|
||||
await onCredentialsRefreshed?.(refreshed);
|
||||
} catch (error) {
|
||||
log?.warn?.("Grok CLI credential persistence failed", error);
|
||||
}
|
||||
response = await request(accessToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const detail = await response.text().catch(() => "");
|
||||
return {
|
||||
models: [],
|
||||
warning: `Grok CLI model discovery failed (${response.status})${detail ? `: ${detail.slice(0, 160)}` : ""}`,
|
||||
};
|
||||
}
|
||||
|
||||
const models = parseGrokCliModels(await response.json());
|
||||
return models.length
|
||||
? { models }
|
||||
: { models: [], warning: "Grok CLI returned no selectable models." };
|
||||
} catch (error) {
|
||||
return { models: [], warning: `Grok CLI model discovery failed: ${error.message}` };
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,10 @@ for (const entry of REGISTRY) {
|
||||
for (const a of entry.aliases || []) ALIAS_TO_PROVIDER_ID[a] = entry.id;
|
||||
}
|
||||
|
||||
const BUILTIN_MODEL_ALIASES = {
|
||||
"grok-build": "gcli/grok-build",
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve provider alias to provider ID
|
||||
*/
|
||||
@@ -104,7 +108,9 @@ export async function getModelInfoCore(modelStr, aliasesOrGetter) {
|
||||
: aliasesOrGetter;
|
||||
|
||||
// Resolve alias
|
||||
const resolved = resolveModelAliasFromMap(parsed.model, aliases);
|
||||
const resolved =
|
||||
resolveModelAliasFromMap(parsed.model, aliases) ||
|
||||
resolveModelAliasFromMap(parsed.model, BUILTIN_MODEL_ALIASES);
|
||||
if (resolved) {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,11 @@
|
||||
|
||||
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
|
||||
import { U, parseResetTime, toFiniteNumber } from "./shared.js";
|
||||
import {
|
||||
GROK_CLI_CLIENT_IDENTIFIER,
|
||||
GROK_CLI_USER_AGENT,
|
||||
GROK_CLI_VERSION,
|
||||
} from "../../config/grokCli.js";
|
||||
|
||||
const USAGE = U("grok-cli");
|
||||
const BILLING_URL = USAGE.url || "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
|
||||
@@ -43,10 +48,11 @@ function buildGrokCliHeaders(accessToken, providerSpecificData = {}) {
|
||||
const headers = {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: "application/json",
|
||||
"User-Agent": "grok-pager/0.2.93 grok-shell/0.2.93 (linux; x86_64)",
|
||||
"User-Agent": GROK_CLI_USER_AGENT,
|
||||
"x-xai-token-auth": "xai-grok-cli",
|
||||
"x-grok-client-identifier": "grok-pager",
|
||||
"x-grok-client-version": "0.2.93",
|
||||
"x-grok-client-identifier": GROK_CLI_CLIENT_IDENTIFIER,
|
||||
"x-grok-client-version": GROK_CLI_VERSION,
|
||||
"x-grok-client-mode": "headless",
|
||||
};
|
||||
const email = psd.email;
|
||||
const userId = psd.userId || psd.principalId;
|
||||
@@ -55,8 +61,18 @@ function buildGrokCliHeaders(accessToken, providerSpecificData = {}) {
|
||||
return headers;
|
||||
}
|
||||
|
||||
function subscriptionTier(user, config) {
|
||||
const rawTier =
|
||||
user?.subscriptionTier ??
|
||||
user?.subscription_tier ??
|
||||
user?.subscription?.tier ??
|
||||
config?.subscriptionTier ??
|
||||
config?.subscription_tier;
|
||||
return typeof rawTier === "string" ? rawTier.trim() : "";
|
||||
}
|
||||
|
||||
function resolvePlan(user, config) {
|
||||
const tier = typeof user?.subscriptionTier === "string" ? user.subscriptionTier.trim() : "";
|
||||
const tier = subscriptionTier(user, config);
|
||||
if (tier) {
|
||||
return tier
|
||||
.replace(/[_-]+/g, " ")
|
||||
@@ -105,11 +121,42 @@ export function parseGrokCliBilling(billing, user = null) {
|
||||
|
||||
const periodEnd =
|
||||
parseResetTime(config.billingPeriodEnd) ||
|
||||
parseResetTime(config.billing_period_end) ||
|
||||
parseResetTime(config.currentPeriod?.end) ||
|
||||
parseResetTime(config.resetAt || config.resetsAt || config.periodEnd) ||
|
||||
parseResetTime(root.billingPeriodEnd) ||
|
||||
parseResetTime(root.billing_period_end) ||
|
||||
parseResetTime(root.resetAt || root.resetsAt || root.periodEnd) ||
|
||||
null;
|
||||
|
||||
const quotas = {};
|
||||
const tier = subscriptionTier(user, config);
|
||||
const subscriptionAccess = Boolean(tier) && !/^(free|none|null)$/i.test(tier);
|
||||
|
||||
// Current Grok Build responses expose included monthly usage at top level.
|
||||
const monthlyLimit = unwrapVal(
|
||||
config.monthlyLimit ?? config.monthly_limit ?? root.monthlyLimit ?? root.monthly_limit,
|
||||
NaN,
|
||||
);
|
||||
const includedUsed = unwrapVal(
|
||||
config.includedUsed ?? config.included_used ?? root.includedUsed ?? root.included_used,
|
||||
NaN,
|
||||
);
|
||||
const totalUsed = unwrapVal(
|
||||
config.totalUsed ?? config.total_used ?? root.totalUsed ?? root.total_used,
|
||||
NaN,
|
||||
);
|
||||
if (Number.isFinite(monthlyLimit) && monthlyLimit > 0) {
|
||||
quotas["Monthly included"] = makeQuota({
|
||||
used: Number.isFinite(includedUsed)
|
||||
? includedUsed
|
||||
: Number.isFinite(totalUsed)
|
||||
? totalUsed
|
||||
: 0,
|
||||
total: monthlyLimit,
|
||||
resetAt: periodEnd,
|
||||
});
|
||||
}
|
||||
|
||||
// Primary: on-demand spending window (subscription / promo credits)
|
||||
const onDemandCap = unwrapVal(config.onDemandCap ?? root.onDemandCap, NaN);
|
||||
@@ -121,7 +168,12 @@ export function parseGrokCliBilling(billing, user = null) {
|
||||
total: onDemandCap,
|
||||
resetAt: periodEnd,
|
||||
});
|
||||
} else if (Number.isFinite(onDemandCap) && onDemandCap === 0 && Number.isFinite(onDemandUsed)) {
|
||||
} else if (
|
||||
!subscriptionAccess &&
|
||||
Number.isFinite(onDemandCap) &&
|
||||
onDemandCap === 0 &&
|
||||
Number.isFinite(onDemandUsed)
|
||||
) {
|
||||
// Cap 0 is the exhausted free/promo state (chat returns 402 spending-limit).
|
||||
// UI treats total===0 as unlimited, so use a synthetic 1/1 depleted row.
|
||||
quotas["On-demand"] = {
|
||||
@@ -199,6 +251,7 @@ export function parseGrokCliBilling(billing, user = null) {
|
||||
quotas,
|
||||
periodEnd,
|
||||
exhausted,
|
||||
subscriptionAccess,
|
||||
rawConfig: config,
|
||||
};
|
||||
}
|
||||
@@ -255,8 +308,9 @@ export async function getGrokCliUsage(accessToken, providerSpecificData = null,
|
||||
if (!parsed.quotas || Object.keys(parsed.quotas).length === 0) {
|
||||
return {
|
||||
plan: parsed.plan,
|
||||
message:
|
||||
"Grok Build connected, but no credit allotment was returned. Free promo may be exhausted — upgrade at https://grok.com/supergrok or add credits at https://grok.com/?_s=usage.",
|
||||
message: parsed.subscriptionAccess
|
||||
? "Subscription access is active; Grok does not expose a numeric included quota."
|
||||
: "Grok Build connected, but no credit allotment was returned. Free promo may be exhausted.",
|
||||
quotas: {},
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user