// pi-ai library adapter for the Grok Build core: import this from server-side // code that composes a pi-ai / pi-agent Models registry. Keep it free of app // imports and side effects, and never import it from client code. The // extension adapter (extension.ts) must NOT import this module — the pi-ai // subpath import below is fatal under pi's extension loader. // // Auth is OAuth-only by design: API keys are not supported anywhere in this // project. The Grok subscription token is the sole credential. import { createProvider, type AuthInteraction, type OAuthAuth, type Provider, type ProviderStreams, } from "@earendil-works/pi-ai"; import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy"; import { GROK_MODELS, XAI_BASE_URL, XAI_PROVIDER_ID, loginXai, refreshXai, requireXaiOAuthCredential, withXaiPayloadInvariants, type XaiLoginHost, type XaiOptions, } from "./xai-grok-build.ts"; export { GROK_45_MODEL, GROK_COMPOSER_MODEL, GROK_MODELS, REASONING_ENCRYPTED_INCLUDE, XAI_BASE_URL, XAI_CLI_HEADERS, XAI_MODEL_ID, XAI_MODEL_OVERRIDE_HEADER, XAI_PROVIDER_ID, XaiToolSchemaCompatibilityError, assertXaiCompatibleToolSchemas, ensureEncryptedReasoningInclude, withXaiPayloadInvariants, type XaiOptions, } from "./xai-grok-build.ts"; export function xaiGrokBuildResponsesProvider( options: XaiOptions = {}, ): Provider<"openai-responses"> { const opts: XaiOptions = { ...options }; return createProvider({ id: XAI_PROVIDER_ID, name: "xAI Grok Build", baseUrl: XAI_BASE_URL, auth: { oauth: xaiOAuthAuth(opts) }, models: [...GROK_MODELS], api: withXaiInvariantStreams(openAIResponsesApi()), }); } function withXaiInvariantStreams(api: ProviderStreams): ProviderStreams { return { stream(model, context, options) { return api.stream(model, context, withXaiPayloadInvariants(options)); }, streamSimple(model, context, options) { return api.streamSimple(model, context, withXaiPayloadInvariants(options)); }, }; } function xaiOAuthAuth(opts: XaiOptions): OAuthAuth { return { name: "xAI (Grok subscription)", async login(callbacks) { return { type: "oauth", ...(await loginXai(toHost(callbacks), opts)) }; }, async refresh(credential) { return { type: "oauth", ...(await refreshXai(requireXaiOAuthCredential(credential))) }; }, async toAuth(credential) { return { apiKey: requireXaiOAuthCredential(credential).access, baseUrl: XAI_BASE_URL }; }, }; } function toHost(cb: AuthInteraction): XaiLoginHost { return { deviceCode: (info) => cb.notify({ type: "device_code", ...info }), progress: (message) => cb.notify({ type: "progress", message }), ...(cb.signal !== undefined ? { signal: cb.signal } : {}), }; }