UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

352 lines (351 loc) • 14.9 kB
import { l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs"; import { S as parseDateStringTimestampMs } from "../../number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord } from "../../record-coerce-CVPuDqcc.mjs"; import { r as createLazyRuntimeModule } from "../../lazy-runtime-zGjszCtt.mjs"; import { n as jsonResult } from "../../tool-results-CcV0sxnb.mjs"; import { h as readProviderJsonResponse } from "../../provider-http-errors-Dtgw3x-5.mjs"; import { r as clampPercent } from "../../provider-usage.shared-ChpSZtTb.mjs"; import "../../string-coerce-runtime-BwAZZDf5.mjs"; import "../../number-runtime-W4chuk8B.mjs"; import { r as buildProviderReplayFamilyHooks } from "../../provider-model-shared-Dg70R9-2.mjs"; import { n as isProviderApiKeyConfiguredAsync } from "../../provider-auth-availability-Bv9WFzc3.mjs"; import { b as defaultToolStreamExtraParams } from "../../provider-stream-shared-BJrJjQd2.mjs"; import "../../provider-http-LcawLneq.mjs"; import "../../provider-auth-D_oAZ3fr.mjs"; import { _ as runLiveProviderCatalog } from "../../provider-catalog-live-runtime-D-M7f_ww.mjs"; import { t as defineSingleProviderPluginEntry } from "../../provider-entry-CRfSFsHE.mjs"; import { n as buildUsageHttpErrorSnapshot, r as fetchJson } from "../../provider-usage.fetch.shared-BxW_bbQo.mjs"; import "../../provider-usage-DEMof86V.mjs"; import "../../provider-web-search-hr4kzF3y.mjs"; import { n as createCodeExecutionToolDefinition, t as buildMissingCodeExecutionApiKeyPayload } from "../../code-execution-tool-shared-kghxzkq2.mjs"; import { o as normalizeXaiModelId } from "../../model-id-Cs3j89NC.mjs"; import { a as createLazyXaiSpeechProvider, i as createLazyXaiRealtimeVoiceProvider, n as createLazyXaiMediaUnderstandingProvider, o as createLazyXaiVideoGenerationProvider, r as createLazyXaiRealtimeTranscriptionProvider, t as createLazyXaiImageGenerationProvider } from "../../lazy-capability-provider-factories-Du9OB75Z.mjs"; import "../../model-compat-C3zUp-L8.mjs"; import { n as applyXaiConfig, t as XAI_DEFAULT_MODEL_REF } from "../../onboard-B5OlMszM.mjs"; import { i as isXaiGrokProxyBaseUrl, n as buildLiveXaiProvider, r as buildXaiProvider, t as buildLiveXaiOAuthProvider } from "../../provider-catalog-_Rqur04q.mjs"; import { t as isXaiProviderId } from "../../provider-id-DCdct8aI.mjs"; import { t as resolveXaiTransport } from "../../provider-routing-BAPSdjTE.mjs"; import { t as applyXaiRuntimeModelCompat } from "../../runtime-model-compat-Lm61EgSw.mjs"; import { n as resolveXaiForwardCompatModel, t as isModernXaiModel } from "../../provider-models-D0pXIDvX.mjs"; import { n as resolveThinkingProfile } from "../../provider-policy-api-CEE7cEnB.mjs"; import { n as resolveFallbackXaiAuth, t as isXaiToolEnabled } from "../../tool-auth-shared-CKBbJvB4.mjs"; import { n as resolveCodeExecutionEnabled, t as readPluginCodeExecutionConfig } from "../../code-execution-config-DyasElwe.mjs"; import { t as resolveEffectiveXSearchConfig } from "../../x-search-config-Dwl9bsAA.mjs"; import { n as wrapXaiProviderStream, r as wrapXaiSimpleCompletionStream, t as XAI_GROK_OAUTH_CLIENT_VERSION } from "../../stream-BOGP9X5B.mjs"; import { t as createXaiWebSearchProvider } from "../../web-search-BQLC_Fm5.mjs"; import { n as buildMissingXSearchApiKeyPayload, r as createXSearchToolDefinition } from "../../x-search-tool-shared-DwqLlXbx.mjs"; import { n as createXaiOAuthAuthMethod, r as refreshXaiOAuthCredential, t as createXaiDeviceCodeAuthMethod } from "../../xai-oauth-entry-DeBAfOrx.mjs"; //#region extensions/xai/index.ts const SUPERGROK_BILLING_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits"; const SUPERGROK_CLIENT_MODE = "cli"; const MAX_PLAN_CHARS = 128; const MAX_EXACT_INTEGER = 9007199254740991; function parseCentValue(e) { const t = asOptionalRecord(e)?.val; if (t === void 0 || t === null) return 0; if (typeof t === "number" && Number.isInteger(t)) return t; if (typeof t === "string" && /^-?\d+$/.test(t.trim())) return Number.parseInt(t.trim(), 10); } function parseMoneyValue(e) { const t = parseCentValue(e); if (t === void 0 || t < 0 || t > MAX_EXACT_INTEGER) return; return t / 100; } function parsePlan(e) { const t = normalizeOptionalString(e); if (!t || t.length > MAX_PLAN_CHARS || hasControlCharacter(t)) return; return t; } function hasControlCharacter(e) { for (let t = 0; t < e.length; t += 1) if (e.charCodeAt(t) < 32) return true; return false; } function parsePercent(e) { if (typeof e !== "number" || !Number.isFinite(e) || e < 0) return; return clampPercent(e); } function readCurrentPeriod(e) { return asOptionalRecord(e["currentPeriod"] ?? e["current_period"]); } function readPeriodBoundMs(e, t, n) { const r = n === "start" ? "billingPeriodStart" : "billingPeriodEnd"; const i = n === "start" ? "billing_period_start" : "billing_period_end"; return parseDateStringTimestampMs(t?.[n] ?? e[r] ?? e[i]); } function hasRecognizedUsagePeriod(e) { const t = readCurrentPeriod(e); const n = normalizeOptionalString(t?.type) ?? ""; if (!n.endsWith("WEEKLY") && !n.endsWith("MONTHLY")) return false; return readPeriodBoundMs(e, t, "start") !== void 0 || readPeriodBoundMs(e, t, "end") !== void 0; } function resolveUsageWindow(e) { const t = readCurrentPeriod(e); const n = parsePercent(e["creditUsagePercent"] ?? e["credit_usage_percent"]); const r = parseCentValue(e["used"]); const i = parseCentValue(e["monthlyLimit"] ?? e["monthly_limit"]); const a = r !== void 0 && i !== void 0 && i > 0 && r >= 0 ? parsePercent(r / i * 100) : void 0; const o = n ?? a; if (o === void 0) return; const s = normalizeOptionalString(t?.type) ?? ""; const c = s.endsWith("WEEKLY") ? "Weekly" : s.endsWith("MONTHLY") || i !== void 0 || e["billingPeriodEnd"] !== void 0 || e["billing_period_end"] !== void 0 ? "Monthly" : "Usage"; const l = readPeriodBoundMs(e, t, "end"); return { label: c, usedPercent: o, ...l !== void 0 ? { resetAt: l } : {} }; } function resolveBilling(e) { const t = parseMoneyValue(e["prepaidBalance"] ?? e["prepaid_balance"]); if (t === void 0) return; return [{ type: "balance", label: "Prepaid balance", amount: t, unit: "USD" }]; } const PROVIDER_ID = "xai"; const XAI_CREDIT_OR_SPENDING_LIMIT_RE = /\b(?:used all available credits|run out of credits|monthly spending limit|purchase more credits|raise your spending limit|need a Grok subscription)\b/i; const XAI_RATE_LIMIT_RE = /\b(?:rate limit exceeded|too many requests)\b/i; const XAI_PROVIDER_INTERNAL_ERROR_RE = /\binternal error during token generation\b/i; const loadCodeExecutionModule = createLazyRuntimeModule(() => import("./code-execution.js")); const loadXSearchModule = createLazyRuntimeModule(() => import("./x-search.js")); function classifyXaiFailoverReason({ errorMessage: e, status: t, code: n, errorType: r }) { if (XAI_CREDIT_OR_SPENDING_LIMIT_RE.test(e)) return "billing"; if (XAI_RATE_LIMIT_RE.test(e)) return "rate_limit"; if (t === void 0 && n === void 0 && r === void 0 && XAI_PROVIDER_INTERNAL_ERROR_RE.test(e)) return "server_error"; } function isCodeExecutionEnabled(e, t) { return resolveCodeExecutionEnabled({ sourceConfig: e, runtimeConfig: e, config: readPluginCodeExecutionConfig(e), auth: t }); } function isXSearchEnabled(e, t) { if (resolveEffectiveXSearchConfig(e)?.enabled === false) return false; return isXaiToolEnabled({ sourceConfig: e, auth: t }); } function shouldExposeXaiBilledTool(e) { const t = e.activeProvider?.trim(); if (!t || e.enabled === false) return false; return isXaiProviderId(t) || e.enabled === true; } function canExposeXaiBilledTool(e, t, n) { const r = e.runtimeConfig ?? e.config; const i = t(r)?.enabled; return shouldExposeXaiBilledTool({ activeProvider: e.activeModel?.provider, enabled: i }) && n(r, e); } function createLazyCodeExecutionTool(e) { if (!canExposeXaiBilledTool(e, readPluginCodeExecutionConfig, isCodeExecutionEnabled)) return null; return createCodeExecutionToolDefinition(async (t, n) => { const { createCodeExecutionTool: r } = await loadCodeExecutionModule(); const i = r({ config: e.config, runtimeConfig: e.runtimeConfig ?? null, auth: e }); if (!i) return jsonResult(buildMissingCodeExecutionApiKeyPayload()); return await i.execute(t, n); }); } function createLazyXSearchTool(e) { if (!canExposeXaiBilledTool(e, resolveEffectiveXSearchConfig, isXSearchEnabled)) return null; return createXSearchToolDefinition(async (t, n, r) => { r?.throwIfAborted(); const { createXSearchTool: i } = await loadXSearchModule(); r?.throwIfAborted(); const a = i({ config: e.config, runtimeConfig: e.runtimeConfig ?? null, auth: e }); if (!a) return jsonResult(buildMissingXSearchApiKeyPayload()); return await a.execute(t, n, r); }); } var xai_default = defineSingleProviderPluginEntry({ id: "xai", name: "xAI Plugin", description: "Bundled xAI plugin", provider: () => ({ label: "xAI", aliases: ["x-ai"], docsPath: "/providers/xai", auth: [{ methodId: "api-key", label: "xAI API key", hint: "API key", optionKey: "xaiApiKey", flagName: "--xai-api-key", envVar: "XAI_API_KEY", promptMessage: "Enter xAI API key", defaultModel: XAI_DEFAULT_MODEL_REF, preserveExistingPrimary: true, applyConfig: (e) => applyXaiConfig(e), wizard: { groupLabel: "xAI (Grok)" } }], extraAuth: [createXaiOAuthAuthMethod(), createXaiDeviceCodeAuthMethod()], catalog: { order: "simple", run: async (e) => { const t = e.resolveProviderAuth(PROVIDER_ID); if (t.preparationFailed) return null; const { resolveApiKeyForProvider: n } = await import("../../plugin-sdk/provider-auth-runtime.js"); const r = isXaiGrokProxyBaseUrl(e.config.models?.providers?.[PROVIDER_ID]?.baseUrl); const i = t.mode === "token" && r && t.discoveryApiKey ? { ...t, apiKey: t.discoveryApiKey } : await n({ provider: PROVIDER_ID, cfg: e.config, ...e.agentDir ? { agentDir: e.agentDir } : {}, ...e.workspaceDir ? { workspaceDir: e.workspaceDir } : {}, ...t.profileId ? { profileId: t.profileId, lockedProfile: true } : {}, ...!t.profileId && t.mode !== "none" ? { allowAuthProfileFallback: false } : {} }).catch(() => void 0); const a = (i?.mode === "token" || t.mode === "token") && r; if (a && (!i?.apiKey || i.mode !== "token")) return { providers: {}, outcomes: [{ provider: PROVIDER_ID, profileId: t.profileId, status: "unavailable" }] }; const o = i?.apiKey && (i.mode === "oauth" || a) ? { ...i, oauth: true } : { ...t.apiKey ? t : e.resolveProviderApiKey(PROVIDER_ID), oauth: false }; if (!o.apiKey) return null; const s = o.apiKey; return await runLiveProviderCatalog({ providerId: PROVIDER_ID, profileId: o.profileId, run: async () => ({ provider: o.oauth ? await buildLiveXaiOAuthProvider({ discoveryApiKey: s, authMode: o.mode === "token" ? "token" : "oauth" }) : await buildLiveXaiProvider(o) }) }); }, staticRun: async (e) => { const t = e.resolveProviderAuth(PROVIDER_ID); const n = t.mode === "oauth" ? "oauth" : t.mode === "token" && isXaiGrokProxyBaseUrl(e.config.models?.providers?.[PROVIDER_ID]?.baseUrl) ? "token" : void 0; return { provider: buildXaiProvider("openai-responses", n) }; } }, ...buildProviderReplayFamilyHooks({ family: "openai-compatible" }), prepareExtraParams: (e) => defaultToolStreamExtraParams(e.extraParams), wrapStreamFn: (e) => wrapXaiProviderStream(e), wrapSimpleCompletionStreamFn: (e) => wrapXaiSimpleCompletionStream(e), resolveSyntheticAuth: ({ config: e }) => { const t = resolveFallbackXaiAuth(e); if (!t) return; return { apiKey: t.apiKey, source: t.source, mode: "api-key" }; }, normalizeResolvedModel: ({ model: e }) => applyXaiRuntimeModelCompat(e), normalizeTransport: ({ provider: e, api: t, baseUrl: n }) => resolveXaiTransport({ provider: e, api: t, baseUrl: n }), normalizeModelId: ({ modelId: e }) => normalizeXaiModelId(e), resolveDynamicModel: (e) => resolveXaiForwardCompatModel({ providerId: PROVIDER_ID, ctx: e }), refreshOAuth: refreshXaiOAuthCredential, resolveUsageAuth: async (e) => { const t = await e.resolveOAuthToken(); return t ? t : { handled: true }; }, fetchUsageSnapshot: async (e) => { const t = await fetchJson(SUPERGROK_BILLING_URL, { method: "GET", headers: { Authorization: `Bearer ${e.token}`, Accept: "application/json", "x-grok-client-mode": SUPERGROK_CLIENT_MODE, "x-grok-client-version": XAI_GROK_OAUTH_CLIENT_VERSION } }, e.timeoutMs, e.fetchFn); if (!t.ok) { await t.body?.cancel().catch(() => void 0); return buildUsageHttpErrorSnapshot({ provider: PROVIDER_ID, status: t.status, tokenExpiredStatuses: [401, 403] }); } try { const e = await readProviderJsonResponse(t, "xai-usage"); const n = asOptionalRecord(e); const r = asOptionalRecord(n?.["config"]); if (!r) return { provider: PROVIDER_ID, displayName: "SuperGrok", windows: [], error: "Malformed billing response" }; const i = resolveUsageWindow(r); const a = resolveBilling(r); const o = parsePlan(n?.["subscription_tier"] ?? n?.["subscriptionTier"]) ?? "SuperGrok"; if (i || (r["creditUsagePercent"] ?? r["credit_usage_percent"]) === void 0 && hasRecognizedUsagePeriod(r)) return { provider: PROVIDER_ID, displayName: "SuperGrok", windows: i ? [i] : [], billing: a, plan: o, ...i ? {} : { summary: "Included usage omitted" } }; return { provider: PROVIDER_ID, displayName: "SuperGrok", windows: [], error: "No usage data" }; } catch { return { provider: PROVIDER_ID, displayName: "SuperGrok", windows: [], error: "Malformed billing response" }; } }, resolveThinkingProfile, isModernModelRef: ({ modelId: e }) => isModernXaiModel(e), classifyFailoverReason: classifyXaiFailoverReason }), register(e) { e.registerWebSearchProvider(createXaiWebSearchProvider()); e.registerMediaUnderstandingProvider(createLazyXaiMediaUnderstandingProvider()); e.registerVideoGenerationProvider(createLazyXaiVideoGenerationProvider({ isProviderApiKeyConfiguredAsync })); e.registerImageGenerationProvider(createLazyXaiImageGenerationProvider()); e.registerSpeechProvider(createLazyXaiSpeechProvider); e.registerRealtimeTranscriptionProvider(createLazyXaiRealtimeTranscriptionProvider); e.registerRealtimeVoiceProvider(createLazyXaiRealtimeVoiceProvider); e.registerTool((e) => createLazyCodeExecutionTool(e), { name: "code_execution" }); e.registerTool((e) => createLazyXSearchTool(e), { name: "x_search" }); } }); //#endregion export { xai_default as default };