@gullabs/xai 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/adapter.ts","../src/file-store.ts","../src/model-config/tools.ts","../src/model-config/grok-4-5.ts","../src/model-config/grok-4-6.ts","../src/models.ts","../src/pricing.ts","../src/provider.ts"],"names":["LlmError","isPlainRecord","classifyError","z"],"mappings":";;;;AA0BO,SAAS,cAAc,IAAA,EAA4B;AACxD,EAAA,IACE,EAAE,QAAA,IAAY,IAAA,CAAA,IACd,OAAO,IAAA,CAAK,MAAA,KAAW,QAAA,IACvB,IAAA,CAAK,MAAA,CAAO,IAAA,EAAK,KAAM,EAAA,EACvB;AACA,IAAA,MAAM,IAAI,SAAS,mCAAA,EAAqC;AAAA,MACtD,IAAA,EAAM,cAAA;AAAA,MACN,SAAA,EAAW,KAAA;AAAA,MACX,QAAA,EAAU;AAAA,KACX,CAAA;AAAA,EACH;AACA,EAAA,OAAO,IAAA,CAAK,MAAA;AACd;AA4OA,eAAsB,eAAe,IAAA,EAA4C;AAI/E,EAAA,MAAM,MAAA,GAAS,cAAc,IAAI,CAAA;AAEjC,EAAA,MAAM,EAAE,OAAA,EAAS,MAAA,EAAO,GAAI,MAAM,OAAO,QAAQ,CAAA;AAEjD,EAAA,MAAM,MAAA,GAAS,IAAI,MAAA,CAAO;AAAA,IACxB,MAAA;AAAA,IACA,OAAA,EAAS,qBAAA;AAAA,IACT,UAAA,EAAY;AAAA,GACb,CAAA;AAED,EAAA,OAAO;AAAA,IACL,SAAA,EAAW;AAAA,MACT,MAAM,MAAA,CACJ,MAAA,EACA,OAAA,EAC2B;AAI3B,QAAA,OACE,MAAA,CAAO,SAAA,CAAU,MAAA,CAIjB,MAAA,EAAQ,OAAO,CAAA;AAAA,MACnB;AAAA;AACF,GACF;AACF;AC1QA,SAAS,cAAc,KAAA,E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O;AAAA;AACT,GACF;AACF;AAcO,SAAS,gBAAA,GAAkC;AAChD,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,iBAAA;AAAA,IACT,KAAA,CAAM,KAAA,EAAe,KAAA,EAAc,IAAA,EAAqB;AACtD,MAAA,OAAO,cAAA,CAAe,KAAA,EAAO,KAAA,EAAO,IAAI,CAAA;AAAA,IAC1C,CAAA;AAAA,IACA,SAAS,KAAA,EAAwB;AAC/B,MAAA,OAAO,WAAA,CAAY,KAAK,CAAA,KAAM,MAAA;AAAA,IAChC,CAAA;AAAA,IACA,UAAA,GAAgC;AAC9B,MAAA,OAAO,MAAA,CAAO,KAAK,WAAW,CAAA;AAAA,IAChC;AAAA,GACF;AACF;;;ACtPO,SAAS,YAAY,IAAA,EAA0C;AACpE,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,WAAW,IAAI,CAAA;AAAA,IACxB,gBAAA,EAAkB,mBAAA;AAAA,IAClB,eAAe,gBAAA;AAAiB,GAClC;AACF","file":"index.js","sourcesContent":["/**\n * Structural XaiClientLike interface + buildXaiClient factory.\n *\n * This module defines the structural interface the adapter depends on.\n * The real `openai` SDK is imported ONLY in buildXaiClient so tests can\n * inject a fake without pulling in the real SDK. This is the ONLY file in\n * `packages/xai/src` that imports `openai`.\n *\n * @module\n */\n\nimport { LlmError } from '@gullabs/core'\nimport type { AuthMaterial } from '@gullabs/core'\n\n// ---------------------------------------------------------------------------\n// Auth narrowing — xAI only accepts ApiKeyAuth\n// ---------------------------------------------------------------------------\n\n/**\n * Narrows {@link AuthMaterial} to its `apiKey` string, rejecting the\n * dev-only `CliSessionAuth` variant.\n *\n * xAI is a production API provider and only ever accepts API-key\n * credentials; `{ cliSession: true }` is reserved for the dev-only CLI\n * provider packages (`@gullabs/claude-cli`, `@gullabs/codex-cli`).\n */\nexport function requireApiKey(auth: AuthMaterial): string {\n if (\n !('apiKey' in auth) ||\n typeof auth.apiKey !== 'string' ||\n auth.apiKey.trim() === ''\n ) {\n throw new LlmError('@gullabs/xai requires auth.apiKey', {\n kind: 'invalid_auth',\n retryable: false,\n provider: 'xai',\n })\n }\n return auth.apiKey\n}\n\n// ---------------------------------------------------------------------------\n// Request shape — what the (future) adapter sends to responses.create\n// ---------------------------------------------------------------------------\n\n/** A text content item within an xAI Responses API input message. */\nexport interface XaiInputTextPart {\n type: 'input_text'\n text: string\n}\n\n/**\n * An image content item within an xAI Responses API input message.\n * `image_url` may be a data URL (`data:image/png;base64,...`) or a public URL.\n */\nexport interface XaiInputImagePart {\n type: 'input_image'\n image_url: string\n}\n\n/**\n * A file attachment content item within an xAI Responses API input message.\n * Prefer `file_id` for private uploads (via {@link XaiFileStore}); `file_url`\n * is for publicly reachable documents. Attaching either implicitly enables\n * xAI's `attachment_search` agentic tool.\n */\nexport interface XaiInputFilePart {\n type: 'input_file'\n file_id?: string\n file_url?: string\n}\n\n/** Union of content-part shapes an input message may carry. */\nexport type XaiInputContentPart = XaiInputTextPart | XaiInputImagePart | XaiInputFilePart\n\n/** A single role+content input item constructed by the (future) adapter. */\nexport interface XaiInputItem {\n role: 'user' | 'assistant' | 'system' | 'developer'\n content: XaiInputContentPart[]\n}\n\n/** Live-verified store:false replay item. */\nexport interface XaiFunctionCallInputItem {\n type: 'function_call'\n call_id: string\n name: string\n arguments: string\n}\n\n/** Live-verified store:false replay item. */\nexport interface XaiFunctionCallOutputInputItem {\n type: 'function_call_output'\n call_id: string\n output: string\n}\n\nexport type XaiRequestInputItem =\n XaiInputItem | XaiFunctionCallInputItem | XaiFunctionCallOutputInputItem\n\n/**\n * Structured-output text-format request shape.\n * Real xAI field: `text.format`, NOT `response_format`.\n * `name` and `strict` are included per xAI's Structured Outputs docs\n * conventions even though the live fixture's request-echo does not surface\n * them (only the schema is echoed back).\n */\nexport type XaiTextFormat =\n | { type: 'json_schema'; name: string; schema: unknown; strict: boolean }\n | { type: 'text' }\n\n/**\n * Parameters for `client.responses.create`.\n * Structurally modeled from live-captured xAI Responses API fixtures\n * (see docs/provider-plugins-and-xai-grok-4-5-plan.md §3.1), not from the\n * `openai` npm package's TS types — xAI's actual endpoint shape differs.\n */\nexport interface XaiResponseCreateParams {\n model: string\n input: XaiRequestInputItem[]\n instructions?: string\n reasoning?: { effort: 'low' | 'medium' | 'high' | 'xhigh' }\n text?: { format: XaiTextFormat }\n temperature?: number\n top_p?: number\n max_output_tokens?: number\n prompt_cache_key?: string\n /**\n * Responses `service_tier`. Only `'priority'` is forwarded (live-verified\n * on grok-4.6, 2026-08-12). Omitted when the caller did not request a tier.\n */\n service_tier?: 'priority'\n /** Always `false` — this library never relies on xAI-side conversation storage. */\n store: false\n /**\n * Server-side and/or function tools. Wire names are snake_case.\n * Shape is pinned from live 2026-08-24 fixtures.\n */\n tools?: Array<Record<string, unknown>>\n /** `'auto' | 'required' | 'none'` or live-verified `{ type: 'function', name }`. */\n tool_choice?: string | { type: 'function'; name: string }\n parallel_tool_calls?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Response shape — mirrors the xAI Responses API surface we actually consume\n// ---------------------------------------------------------------------------\n\n/** A single summary-text segment of a `type: 'reasoning'` output item. */\nexport interface XaiReasoningSummaryPart {\n type: 'summary_text'\n text: string\n}\n\n/** A `type: 'reasoning'` item in `output`. */\nexport interface XaiReasoningOutputItem {\n type: 'reasoning'\n id?: string\n summary: XaiReasoningSummaryPart[]\n status?: string\n}\n\n/** A single text content segment of a `type: 'message'` output item. */\nexport interface XaiOutputTextPart {\n type: 'output_text'\n text: string\n logprobs?: unknown[]\n annotations?: unknown[]\n}\n\n/** A `type: 'message'` item in `output`. */\nexport interface XaiMessageOutputItem {\n type: 'message'\n id?: string\n role?: string\n status?: string\n content: XaiOutputTextPart[]\n}\n\n/** Server-tool or function-call output items we do not collapse as messages. */\nexport interface XaiOtherOutputItem {\n type: string\n [key: string]: unknown\n}\n\n/** Union of output-item shapes the Responses API may return. */\nexport type XaiOutputItem =\n XaiReasoningOutputItem | XaiMessageOutputItem | XaiOtherOutputItem\n\n/**\n * Token usage metadata returned alongside an xAI response.\n *\n * Kept loose/open: the known fields are typed, but xAI has been observed to\n * add additional numeric fields (e.g. `num_sources_used`,\n * `cost_in_usd_ticks`, `context_details`) that must not break this type.\n */\nexport interface XaiUsageShape {\n input_tokens: number\n input_tokens_details?: { cached_tokens?: number }\n output_tokens: number\n output_tokens_details?: { reasoning_tokens?: number }\n total_tokens?: number\n /** Additional provider-specific usage fields, passed through raw. */\n [otherKeys: string]: unknown\n}\n\n/**\n * Structural equivalent of the xAI Responses API response body.\n * Only the fields the (future) adapter reads are represented here.\n */\nexport interface XaiResponseShape {\n id: string\n model: string\n /**\n * Real field: `status`. Observed values: \"completed\", \"incomplete\" — kept\n * as a plain `string` since xAI may add further status values over time.\n */\n status: string\n incomplete_details?: { reason?: string } | null\n output: XaiOutputItem[]\n usage: XaiUsageShape\n reasoning?: { effort?: string; summary?: string }\n /**\n * Echoed served tier. Observed values: `\"default\"`, `\"priority\"`.\n * Kept as a plain string — xAI may add further values.\n */\n service_tier?: string\n store?: boolean\n prompt_cache_key?: string | null\n /**\n * Response-level metadata (e.g. `system_fingerprint`) — surfaced into\n * `AdapterResult.providerMetadata` by the adapter when present.\n */\n metadata?: { [key: string]: unknown } | null\n /**\n * Top-level citations array. Live 2026-08-24 search-tools probes returned\n * `null`; citations arrived as `output_text.annotations` of type\n * `url_citation` instead.\n */\n citations?: unknown\n}\n\n// ---------------------------------------------------------------------------\n// XaiClientLike — structural interface (no `openai` dependency)\n// ---------------------------------------------------------------------------\n\n/**\n * Structural interface for the `openai` SDK's `client.responses` surface\n * the adapter uses.\n *\n * Satisfied by:\n * - The real `openai` `OpenAI` client (via `buildXaiClient` wrapper), pointed\n * at xAI's `https://api.x.ai/v1` base URL.\n * - `FakeXaiClient` from `@gullabs/testing`.\n */\nexport interface XaiClientLike {\n responses: {\n create(\n params: XaiResponseCreateParams,\n options?: { signal?: AbortSignal },\n ): Promise<XaiResponseShape>\n }\n}\n\n// ---------------------------------------------------------------------------\n// buildXaiClient — imports the real `openai` SDK\n// ---------------------------------------------------------------------------\n\n/**\n * Build a real `openai`-SDK-backed client from AuthMaterial, pointed at\n * xAI's Responses API endpoint.\n *\n * Only API-key authentication is supported.\n *\n * @param auth - API key credentials ({ apiKey }).\n */\nexport async function buildXaiClient(auth: AuthMaterial): Promise<XaiClientLike> {\n // Resolve and validate auth BEFORE importing the SDK so auth-rejection\n // tests never need to touch the real `openai` module (and thus never hit\n // the network).\n const apiKey = requireApiKey(auth)\n\n const { default: OpenAI } = await import('openai')\n\n const client = new OpenAI({\n apiKey,\n baseURL: 'https://api.x.ai/v1',\n maxRetries: 0,\n })\n\n return {\n responses: {\n async create(\n params: XaiResponseCreateParams,\n options?: { signal?: AbortSignal },\n ): Promise<XaiResponseShape> {\n // Cast needed: our structural types are subsets of the real SDK types,\n // and the real SDK's types do not exactly match xAI's actual response\n // shape (see module doc comment).\n return (\n client.responses.create as unknown as (\n p: unknown,\n o?: { signal?: AbortSignal },\n ) => Promise<XaiResponseShape>\n )(params, options)\n },\n },\n }\n}\n","/**\n * xaiAdapter — @gullabs/xai xAI Grok provider adapter.\n *\n * Pure request⇄response mapping over the xAI Responses API (via\n * XaiClientLike). Never persists, never computes cost, never loops.\n *\n * @module\n */\n\nimport { LlmError, classifyError, assertNever } from '@gullabs/core'\nimport type {\n ProviderAdapter,\n ResolvedRequest,\n AdapterCtx,\n AdapterResult,\n Usage,\n Warning,\n FinishReason,\n JsonValue,\n AuthMaterial,\n Part,\n Citation,\n TokenCountRequest,\n TokenCount,\n} from '@gullabs/core'\nimport { buildXaiClient, requireApiKey } from './client.js'\nimport type {\n XaiClientLike,\n XaiResponseCreateParams,\n XaiInputContentPart,\n XaiRequestInputItem,\n XaiResponseShape,\n XaiUsageShape,\n XaiMessageOutputItem,\n XaiReasoningOutputItem,\n} from './client.js'\n\n// ---------------------------------------------------------------------------\n// Small object-shape helpers (mirrors google adapter's local helpers)\n// ---------------------------------------------------------------------------\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isXaiMessageItem(\n item: XaiResponseShape['output'][number],\n): item is XaiMessageOutputItem {\n return item.type === 'message' && Array.isArray((item as XaiMessageOutputItem).content)\n}\n\nfunction isXaiReasoningItem(\n item: XaiResponseShape['output'][number],\n): item is XaiReasoningOutputItem {\n return (\n item.type === 'reasoning' && Array.isArray((item as { summary?: unknown }).summary)\n )\n}\n\nfunction badXaiRequest(message: string): LlmError {\n return new LlmError(message, { kind: 'bad_request', retryable: false })\n}\n\n// ---------------------------------------------------------------------------\n// Vision / media mapping\n// ---------------------------------------------------------------------------\n\nconst ALLOWED_XAI_IMAGE_MIME_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png'])\n\n/** 20 MiB, xAI's documented inline-image size ceiling. */\nconst MAX_XAI_INLINE_IMAGE_BYTES = 20 * 1024 * 1024\n\n/**\n * Map a single {@link Part} to its xAI Responses API input-content-part\n * equivalent.\n *\n * - `text` → `{ type: 'input_text', text }`\n * - `inline-media` → `{ type: 'input_image', image_url: 'data:<mime>;base64,<data>' }`;\n * rejected (`bad_request`) when `mimeType` is not jpg/jpeg/png, or when the\n * decoded payload exceeds 20 MiB.\n * - `file-uri` → `{ type: 'input_image', image_url: uri }` ONLY when\n * `uri` is a public `http(s)://` URL AND `mimeType` is an allowed image\n * type — a provider-hosted URI from another provider (e.g. Gemini's Files\n * API `https://generativelanguage.googleapis.com/...` — which itself\n * happens to be `https://`, but is not dereferenceable by xAI) is not\n * portable and callers should not reuse `FileUriPart` cross-provider.\n * - `file-ref` → `{ type: 'input_file', file_id }` for xAI Files uploads.\n * Attaching files implicitly enables xAI's `attachment_search` agentic tool\n * (extra tool billing may apply). Empty `fileId` → `bad_request`.\n *\n * Note: xAI enforces an undocumented server-side minimum image size\n * (observed ~8px/side, ~512 total px). This adapter does not pre-validate\n * pixel dimensions — a too-small image surfaces as a `bad_request` from the\n * live API, classified normally by {@link classifyXaiError}.\n */\nfunction mapPart(p: Part): XaiInputContentPart {\n switch (p.kind) {\n case 'text':\n return { type: 'input_text', text: p.text }\n\n case 'inline-media': {\n if (!ALLOWED_XAI_IMAGE_MIME_TYPES.has(p.mimeType)) {\n throw badXaiRequest(\n `xAI vision only supports image/jpeg and image/png; got mimeType \"${p.mimeType}\".`,\n )\n }\n const byteLength = Buffer.from(p.data, 'base64').length\n if (byteLength > MAX_XAI_INLINE_IMAGE_BYTES) {\n throw badXaiRequest(\n `xAI inline images must be at most 20 MiB; got ${byteLength} bytes.`,\n )\n }\n return { type: 'input_image', image_url: `data:${p.mimeType};base64,${p.data}` }\n }\n\n case 'file-uri': {\n const isPublicHttpUrl = p.uri.startsWith('http://') || p.uri.startsWith('https://')\n const isAllowedImageType = ALLOWED_XAI_IMAGE_MIME_TYPES.has(p.mimeType)\n if (!isPublicHttpUrl || !isAllowedImageType) {\n throw badXaiRequest(\n `xAI only accepts public http(s) image URLs via FileUriPart; got scheme of \"${p.uri}\" / mimeType \"${p.mimeType}\".`,\n )\n }\n // Reject known foreign provider hosts even when scheme+mime look valid.\n if (\n p.uri.includes('generativelanguage.googleapis.com') ||\n p.uri.includes('googleapis.com/v1beta/files')\n ) {\n throw badXaiRequest(\n `xAI cannot dereference Gemini/Google Files URIs via FileUriPart; upload to xAI Files and use FileRefPart (file_id) instead. Got \"${p.uri}\".`,\n )\n }\n return { type: 'input_image', image_url: p.uri }\n }\n\n case 'file-ref': {\n if (typeof p.fileId !== 'string' || p.fileId.trim() === '') {\n throw badXaiRequest('FileRefPart.fileId must be a non-empty string.')\n }\n return { type: 'input_file', file_id: p.fileId }\n }\n\n case 'tool-call':\n case 'tool-result':\n throw badXaiRequest(\n `xAI mapPart does not emit ${p.kind} as a content part; the request mapper handles replay items.`,\n )\n\n default:\n return assertNever(p)\n }\n}\n\n// ---------------------------------------------------------------------------\n// providerOptions.xai → explicit allowlisted mapping\n// ---------------------------------------------------------------------------\n\nconst XAI_PROVIDER_OPTION_KEYS = new Set(['promptCacheKey', 'tools', 'parallelToolCalls'])\n\ntype MappedXaiProviderOptions = {\n promptCacheKey?: string\n tools?: Array<Record<string, unknown>>\n parallelToolCalls?: boolean\n}\n\nfunction mapXaiProviderOptions(\n xaiOpts: unknown,\n model: string,\n): MappedXaiProviderOptions {\n if (xaiOpts === undefined) {\n return {}\n }\n\n if (!isPlainRecord(xaiOpts)) {\n throw badXaiRequest(`providerOptions.xai must be an object for model \"${model}\".`)\n }\n\n const unknownKeys = Object.keys(xaiOpts).filter(\n (key) => !XAI_PROVIDER_OPTION_KEYS.has(key),\n )\n if (unknownKeys.length > 0) {\n throw badXaiRequest(\n `providerOptions.xai contains unsupported keys [${unknownKeys.join(\n ', ',\n )}] for model \"${model}\". Allowed keys: promptCacheKey, tools, parallelToolCalls.`,\n )\n }\n\n const mapped: MappedXaiProviderOptions = {}\n if (xaiOpts['promptCacheKey'] !== undefined) {\n if (\n typeof xaiOpts['promptCacheKey'] !== 'string' ||\n xaiOpts['promptCacheKey'].length === 0\n ) {\n throw badXaiRequest(\n `providerOptions.xai.promptCacheKey must be a non-empty string for model \"${model}\".`,\n )\n }\n mapped.promptCacheKey = xaiOpts['promptCacheKey']\n }\n\n if (xaiOpts['tools'] !== undefined) {\n mapped.tools = mapXaiSearchTools(xaiOpts['tools'], model)\n }\n\n if (xaiOpts['parallelToolCalls'] !== undefined) {\n if (typeof xaiOpts['parallelToolCalls'] !== 'boolean') {\n throw badXaiRequest(\n `providerOptions.xai.parallelToolCalls must be a boolean for model \"${model}\".`,\n )\n }\n mapped.parallelToolCalls = xaiOpts['parallelToolCalls']\n }\n\n return mapped\n}\n\nfunction mapXaiSearchTools(\n tools: unknown,\n model: string,\n): Array<Record<string, unknown>> {\n if (!Array.isArray(tools)) {\n throw badXaiRequest(\n `providerOptions.xai.tools must be an array for model \"${model}\".`,\n )\n }\n return tools.map((tool, index) => {\n if (!isPlainRecord(tool) || typeof tool['type'] !== 'string') {\n throw badXaiRequest(\n `providerOptions.xai.tools[${index}] must be an object with a type for model \"${model}\".`,\n )\n }\n if (tool['type'] === 'web_search') {\n const wire: Record<string, unknown> = { type: 'web_search' }\n if (tool['allowedDomains'] !== undefined)\n wire['allowed_domains'] = tool['allowedDomains']\n if (tool['excludedDomains'] !== undefined) {\n wire['excluded_domains'] = tool['excludedDomains']\n }\n if (tool['enableImageUnderstanding'] !== undefined) {\n wire['enable_image_understanding'] = tool['enableImageUnderstanding']\n }\n if (tool['enableImageSearch'] !== undefined) {\n wire['enable_image_search'] = tool['enableImageSearch']\n }\n return wire\n }\n if (tool['type'] === 'x_search') {\n const wire: Record<string, unknown> = { type: 'x_search' }\n if (tool['allowedXHandles'] !== undefined) {\n wire['allowed_x_handles'] = tool['allowedXHandles']\n }\n if (tool['excludedXHandles'] !== undefined) {\n wire['excluded_x_handles'] = tool['excludedXHandles']\n }\n if (tool['fromDate'] !== undefined) wire['from_date'] = tool['fromDate']\n if (tool['toDate'] !== undefined) wire['to_date'] = tool['toDate']\n if (tool['enableImageUnderstanding'] !== undefined) {\n wire['enable_image_understanding'] = tool['enableImageUnderstanding']\n }\n if (tool['enableVideoUnderstanding'] !== undefined) {\n wire['enable_video_understanding'] = tool['enableVideoUnderstanding']\n }\n return wire\n }\n throw badXaiRequest(\n `providerOptions.xai.tools[${index}].type \"${String(tool['type'])}\" is not supported for model \"${model}\".`,\n )\n })\n}\n\n// ---------------------------------------------------------------------------\n// FinishReason mapping (xAI status/incomplete_details → our FinishReason)\n// ---------------------------------------------------------------------------\n\nfunction mapFinishReason(response: XaiResponseShape): FinishReason {\n if (response.status === 'completed') {\n return 'stop'\n }\n if (\n response.status === 'incomplete' &&\n response.incomplete_details?.reason === 'max_output_tokens'\n ) {\n return 'length'\n }\n // Any other status/incomplete_details combination without fixture\n // evidence (or a status we don't recognize) maps to 'other' — the core\n // FinishReason union is closed to these four values.\n return 'other'\n}\n\n// ---------------------------------------------------------------------------\n// Usage mapping — #1 correctness rule\n// ---------------------------------------------------------------------------\n\n/**\n * Usage fields already mapped into canonical {@link Usage} counters — never\n * duplicated into `details` under their raw xAI names.\n */\nconst CANONICALLY_MAPPED_USAGE_KEYS = new Set([\n 'input_tokens',\n 'output_tokens',\n 'total_tokens',\n])\n\n/**\n * Map xAI's `usage` object to our {@link Usage} type.\n *\n * **GROSS convention (ADR-004):**\n * - `usage.input_tokens` is already GROSS (includes cached) → `inputTokens`.\n * - `usage.output_tokens` is already GROSS (includes reasoning) → `outputTokens`.\n * Unlike Gemini, xAI does not require us to sum sub-fields into the gross\n * total — the top-level fields are already gross.\n *\n * **xAI extras** (captured under raw names; not token-priced): every additional\n * NUMERIC top-level usage field (`num_sources_used`,\n * `num_server_side_tools_used` — e.g. after implicit `attachment_search` when\n * files are attached — `cost_in_usd_ticks`, and anything xAI adds later) is\n * surfaced into `details` under its raw name for host visibility. Non-numeric\n * extras (e.g. `context_details`) belong to `AdapterResult.providerMetadata`\n * (see the adapter) and the full raw payload always lands in `Usage.raw`\n * verbatim. Tool invocation fees are billed in `Cost.details.tools` from the\n * live-pinned counters (`web_search_calls`, `x_search_calls`).\n */\nfunction mapUsage(usage: XaiUsageShape): Usage {\n const inputTokens = usage.input_tokens\n const outputTokens = usage.output_tokens\n const cachedInputTokens = usage.input_tokens_details?.cached_tokens\n const thinkingTokens = usage.output_tokens_details?.reasoning_tokens\n const totalTokens = usage.total_tokens\n\n // Canonical details keys: input, output, cached, thinking.\n const details: Record<string, number> = {\n input: inputTokens,\n output: outputTokens,\n ...(cachedInputTokens !== undefined ? { cached: cachedInputTokens } : {}),\n ...(thinkingTokens !== undefined ? { thinking: thinkingTokens } : {}),\n }\n\n // Numeric xAI extras — surfaced under their raw names.\n for (const [key, value] of Object.entries(usage)) {\n if (typeof value === 'number' && !CANONICALLY_MAPPED_USAGE_KEYS.has(key)) {\n details[key] = value\n }\n }\n\n // Live 2026-08-24: per-tool invocation counters live in the nested\n // `server_side_tool_usage_details` object (web_search_calls, x_search_calls,\n // document_search_calls, …). Flatten numeric members under their raw names\n // so pricing can read them from Usage.details.\n const toolUsage = usage['server_side_tool_usage_details']\n if (isPlainRecord(toolUsage)) {\n for (const [key, value] of Object.entries(toolUsage)) {\n if (typeof value === 'number') {\n details[key] = value\n }\n }\n }\n\n const raw: JsonValue = usage as unknown as { [k: string]: JsonValue }\n\n const result: Usage = {\n inputTokens,\n outputTokens,\n details,\n raw,\n ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),\n ...(thinkingTokens !== undefined ? { thinkingTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n }\n\n return result\n}\n\n// ---------------------------------------------------------------------------\n// Error classification\n// ---------------------------------------------------------------------------\n\n/**\n * Structured-body auth-failure signature, taken verbatim from the recorded\n * live error taxonomy (`__fixtures__/09-error-taxonomy.json`,\n * `invalid_api_key` case): HTTP 400 with body\n * `{ code: 'invalid-argument', error: 'Incorrect API key provided. …' }`.\n *\n * The body `code` (`'invalid-argument'`) is NOT discriminating — xAI uses it\n * for genuinely bad requests too (e.g. `Model not found: grok-99`) — and the\n * `openai` SDK's `APIError` drops it (it hoists only the body's `error`\n * field onto `.error`). The exact message PREFIX xAI emits for bad keys is\n * therefore the signature.\n */\nconst XAI_AUTH_ERROR_MESSAGE_PREFIX = 'Incorrect API key provided'\n\n/**\n * Extract the STRUCTURED error-body text from a raw thrown value.\n *\n * Consulted shapes (both are parsed-body fields, never free-form\n * `Error.message` text):\n * - `rawErr.error` as a string — the `openai` SDK's `APIError` hoists the\n * response body's `error` field onto `.error`, which for xAI's\n * `{ code, error }` bodies is the message string itself.\n * - `rawErr.error` as an object — the full parsed body (test fakes and\n * hand-rolled throws of the fixture shape `{ status, error: <body> }`);\n * its `error` (xAI) or `message` (OpenAI-style) string field is read.\n *\n * Free-form `Error.message` is deliberately ignored so arbitrary request\n * content echoed into a message (e.g. a schema-validation error quoting user\n * text that mentions \"api key\") can never influence classification.\n */\nfunction extractXaiErrorBodyText(rawErr: unknown): string | undefined {\n if (rawErr === null || typeof rawErr !== 'object') {\n return undefined\n }\n const body = (rawErr as Record<string, unknown>)['error']\n if (typeof body === 'string') {\n return body\n }\n if (isPlainRecord(body)) {\n if (typeof body['error'] === 'string') {\n return body['error']\n }\n if (typeof body['message'] === 'string') {\n return body['message']\n }\n }\n return undefined\n}\n\n/** True iff the structured body matches xAI's recorded bad-API-key signature. */\nfunction isXaiAuthFailureBody(rawErr: unknown): boolean {\n const text = extractXaiErrorBodyText(rawErr)\n return text !== undefined && text.startsWith(XAI_AUTH_ERROR_MESSAGE_PREFIX)\n}\n\n/**\n * Structured-body safety-check signature, taken from the live 2026-08-14\n * capture (`__fixtures__/15-safety-check-403.json`): HTTP 403 with\n * `err.error` as the plain string\n * `\"Content violates usage guidelines. Failed check: SAFETY_CHECK_TYPE_CYBER\"`.\n *\n * Match the PREFIX only — `SAFETY_CHECK_TYPE_*` suffixes vary. Free-form\n * `Error.message` is never scanned (same anti-echo rule as the auth overlay).\n */\nconst XAI_SAFETY_CHECK_MESSAGE_PREFIX = 'Content violates usage guidelines'\n\n/** True iff the structured body matches xAI's recorded safety-check signature. */\nfunction isXaiSafetyCheckBody(rawErr: unknown): boolean {\n const text = extractXaiErrorBodyText(rawErr)\n return text !== undefined && text.startsWith(XAI_SAFETY_CHECK_MESSAGE_PREFIX)\n}\n\n/**\n * Message/errno signatures of a transport-level failure: the request never\n * reached xAI's servers (or the connection was severed mid-flight), so there\n * is no HTTP response for {@link classifyHttpStatus} to route by status.\n * Covers the `openai` SDK's own default message (`\"Connection error.\"`,\n * thrown by `APIConnectionError`) plus the Node/undici errno codes that\n * surface when the underlying `fetch` rejects before a response arrives.\n */\nconst XAI_TRANSPORT_ERROR_PATTERN =\n /connection error|econnreset|econnrefused|etimedout|eai_again|epipe|socket hang up|fetch failed/i\n\n/** True iff `err.message` or `err.code` matches a known transport-failure signature. */\nfunction matchesXaiTransportSignature(err: unknown): boolean {\n if (!(err instanceof Error)) return false\n if (XAI_TRANSPORT_ERROR_PATTERN.test(err.message)) return true\n const code = (err as { code?: unknown }).code\n return typeof code === 'string' && XAI_TRANSPORT_ERROR_PATTERN.test(code)\n}\n\n/**\n * True iff `rawErr` is (or wraps) a transport-level connection failure —\n * observed live killing Temporal-orchestrated host runs when the `openai`\n * SDK's `APIConnectionError` (\"Connection error.\") fell through\n * `classifyError`'s generic HTTP-status classification to `kind: 'unknown',\n * retryable: false`.\n *\n * Detection order:\n * 1. `rawErr.constructor.name` matches the `openai` SDK's\n * `APIConnectionError` / `APIConnectionTimeoutError` classes. Matched by\n * constructor name rather than `instanceof` so this file does not need a\n * runtime import of `openai` — per `client.ts`, that package is imported\n * ONLY in `buildXaiClient`, keeping unit tests independent of the real\n * SDK.\n * 2. `rawErr.message` / `rawErr.code` matches a known transport-failure\n * signature (handles the SDK's default message text directly, without\n * relying on the class name surviving minification).\n * 3. A wrapped `rawErr.cause` matches either of the above —\n * `APIConnectionError` attaches the underlying fetch/socket error as\n * `.cause`.\n */\nfunction isXaiTransportError(rawErr: unknown): boolean {\n if (!(rawErr instanceof Error)) return false\n\n const ctorName = rawErr.constructor.name\n if (ctorName === 'APIConnectionError' || ctorName === 'APIConnectionTimeoutError') {\n return true\n }\n\n if (matchesXaiTransportSignature(rawErr)) return true\n\n const cause = (rawErr as { cause?: unknown }).cause\n if (cause instanceof Error) {\n const causeCtorName = cause.constructor.name\n if (\n causeCtorName === 'APIConnectionError' ||\n causeCtorName === 'APIConnectionTimeoutError'\n ) {\n return true\n }\n if (matchesXaiTransportSignature(cause)) return true\n }\n\n return false\n}\n\n/**\n * Classify a raw error thrown from the xAI Responses API call into a typed\n * {@link LlmError}.\n *\n * HTTP status is a hint, not a kind. Overlays inspect the STRUCTURED parsed\n * body only — never free-form `Error.message` — so echoed user content cannot\n * change classification.\n *\n * 1. Already an {@link LlmError} → returned unchanged (including an untagged\n * one).\n * 2. HTTP 400 whose structured body starts with\n * `\"Incorrect API key provided\"` (fixture 09; prefix only — the SDK may\n * drop `code`) → `invalid_auth`.\n * 3. HTTP 403 whose structured body starts with\n * `\"Content violates usage guidelines\"` (fixture 15; `SAFETY_CHECK_TYPE_*`\n * suffixes vary) → `content_filter`. A bare 403 without that body stays\n * the core default, `invalid_auth`.\n * 4. `kind: 'unknown'` with a known transport-failure signature (see\n * {@link isXaiTransportError}) → `server`, retryable. A connection that\n * never reached xAI is not the caller's fault.\n * 5. Else rebuild the core classification tagged `provider: 'xai'`.\n */\nexport function classifyXaiError(rawErr: unknown): LlmError {\n if (rawErr instanceof LlmError) {\n return rawErr\n }\n\n const base = classifyError(rawErr)\n\n if (base.httpStatus === 400 && isXaiAuthFailureBody(rawErr)) {\n return new LlmError(base.message, {\n kind: 'invalid_auth',\n retryable: false,\n httpStatus: base.httpStatus,\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n }\n\n if (base.httpStatus === 403 && isXaiSafetyCheckBody(rawErr)) {\n const bodyText = extractXaiErrorBodyText(rawErr)\n return new LlmError(bodyText ?? base.message, {\n kind: 'content_filter',\n retryable: false,\n httpStatus: base.httpStatus,\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n }\n\n if (base.kind === 'unknown' && isXaiTransportError(rawErr)) {\n return new LlmError(base.message, {\n kind: 'server',\n retryable: true,\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n }\n\n return new LlmError(base.message, {\n kind: base.kind,\n retryable: base.retryable,\n ...(base.httpStatus !== undefined ? { httpStatus: base.httpStatus } : {}),\n ...(base.retryAfterMs !== undefined ? { retryAfterMs: base.retryAfterMs } : {}),\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n}\n\n// ---------------------------------------------------------------------------\n// Adapter options\n// ---------------------------------------------------------------------------\n\nexport interface XaiAdapterOptions {\n /**\n * Inject a pre-built client (real or fake).\n * When omitted, `buildXaiClient` is called with `ctx.auth` at call time,\n * inside the classified try/catch so any construction failure is wrapped\n * as a typed `LlmError`.\n */\n client?: XaiClientLike\n /**\n * @internal Testing-only.\n *\n * Override the default `buildXaiClient` factory. Allows unit tests to\n * simulate construction failures without importing the real `openai` SDK.\n * Never set this in production code. Mirrors `GeminiAdapterOptions._clientFactory`.\n */\n _clientFactory?: (auth: AuthMaterial) => XaiClientLike | Promise<XaiClientLike>\n /**\n * @internal Testing-only.\n *\n * Override `fetch` for `POST /v1/tokenize-text` (not on the openai SDK).\n */\n _fetch?: typeof fetch\n}\n\n// ---------------------------------------------------------------------------\n// xaiAdapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create an xAI Grok provider adapter (Responses API).\n *\n * @param opts.client - Optional pre-built client (e.g. for testing).\n */\nexport function xaiAdapter(opts?: XaiAdapterOptions): ProviderAdapter {\n return {\n id: 'xai',\n\n async run(req: ResolvedRequest, ctx: AdapterCtx): Promise<AdapterResult> {\n if (req.provider !== 'xai') {\n throw new LlmError(\n `xaiAdapter received a request for provider \"${req.provider}\", expected \"xai\".`,\n { kind: 'bad_request', retryable: false },\n )\n }\n\n const warnings: Warning[] = []\n const model = req.model\n const genConfig = req.config\n\n // ------------------------------------------------------------------\n // 1. Map messages → input\n // ------------------------------------------------------------------\n const input: XaiRequestInputItem[] = []\n for (const msg of req.messages) {\n const contentParts: XaiInputContentPart[] = []\n for (const part of msg.parts) {\n if (part.kind === 'tool-call') {\n if (contentParts.length > 0) {\n input.push({\n role: msg.role === 'assistant' ? 'assistant' : 'user',\n content: contentParts.splice(0),\n })\n }\n input.push({\n type: 'function_call',\n call_id: part.toolCallId,\n name: part.toolName,\n arguments: JSON.stringify(part.args),\n })\n continue\n }\n if (part.kind === 'tool-result') {\n if (contentParts.length > 0) {\n input.push({\n role: msg.role === 'assistant' ? 'assistant' : 'user',\n content: contentParts.splice(0),\n })\n }\n input.push({\n type: 'function_call_output',\n call_id: part.toolCallId,\n output: JSON.stringify(part.result),\n })\n continue\n }\n contentParts.push(mapPart(part))\n }\n if (contentParts.length > 0) {\n input.push({\n role: msg.role === 'assistant' ? 'assistant' : 'user',\n content: contentParts,\n })\n }\n }\n\n // ------------------------------------------------------------------\n // 2. Build request params\n // ------------------------------------------------------------------\n const params: XaiResponseCreateParams = {\n model,\n input,\n store: false,\n }\n\n if (req.system !== undefined) {\n params.instructions = req.system\n }\n\n // Sampling — forwarded verbatim, no clamping (schema enforces bounds\n // upstream of the adapter).\n if (genConfig.temperature !== undefined) {\n params.temperature = genConfig.temperature\n }\n if (genConfig.topP !== undefined) {\n params.top_p = genConfig.topP\n }\n\n // max_output_tokens — no artificial ceiling; truncation surfaces as\n // finishReason:'length', not an error (see mapFinishReason).\n if (genConfig.maxOutputTokens !== undefined) {\n params.max_output_tokens = genConfig.maxOutputTokens\n }\n\n // serviceTier — descriptor-driven. grok-4.5 admits none (live 2026-07-09\n // rejected `service_tier`). grok-4.6 admits `'priority'` only\n // (live-verified 2026-08-12: `priority` is echoed; `flex` is silently\n // remapped to `default` by xAI, so this adapter rejects it rather\n // than forwarding a no-op).\n const admittedTiers = req.modelDescriptor?.capabilities?.serviceTiers\n if (genConfig.serviceTier !== undefined) {\n if (\n admittedTiers === undefined ||\n !admittedTiers.includes(genConfig.serviceTier)\n ) {\n throw badXaiRequest(\n `serviceTier is not supported for xai model \"${model}\" (got \"${genConfig.serviceTier}\").`,\n )\n }\n if (genConfig.serviceTier !== 'priority') {\n throw badXaiRequest(\n `serviceTier \"${genConfig.serviceTier}\" is not supported for xai model \"${model}\" (only \"priority\" is admitted).`,\n )\n }\n params.service_tier = 'priority'\n }\n\n // ------------------------------------------------------------------\n // 3. Reasoning → { effort }\n //\n // Admitted efforts are descriptor-owned. grok-4.5: `'low' | 'medium' | 'high'`\n // (live-verified 2026-08-24). grok-4.6: `'low' | 'medium' | 'high' | 'xhigh'`\n // (live-verified 2026-08-12). `'none'` is rejected by both. budgetTokens\n // is not supported (level-style reasoning). includeThoughts is a no-op\n // for xAI — reasoning summaries come back unconditionally whenever\n // reasoning ran, so reasoningText is always surfaced below regardless\n // of this flag; we do not throw on it since it is a legitimate\n // ReasoningIntent field this provider simply doesn't need.\n // ------------------------------------------------------------------\n const reasoning = genConfig.reasoning\n if (reasoning !== undefined) {\n if (reasoning.budgetTokens !== undefined) {\n throw badXaiRequest(\n `reasoning.budgetTokens is not supported for model \"${model}\" (xAI uses effort-level reasoning, not token budgets); use reasoning.effort instead.`,\n )\n }\n\n if (reasoning.effort !== undefined) {\n const effort = reasoning.effort\n if (effort === 'none') {\n throw badXaiRequest(\n `reasoning.effort \"none\" is not supported for xai model \"${model}\".`,\n )\n }\n const admitted = req.modelDescriptor?.capabilities?.admittedReasoningEfforts\n // Fail-closed without a descriptor, matching the serviceTier branch:\n // a host-supplied descriptor that omits admittedReasoningEfforts\n // must not silently re-admit medium/xhigh onto grok-4.5.\n if (admitted === undefined || !admitted.includes(effort)) {\n throw badXaiRequest(\n `reasoning.effort \"${effort}\" is not supported for xai model \"${model}\".`,\n )\n }\n params.reasoning = { effort }\n }\n }\n\n // ------------------------------------------------------------------\n // 4. Structured output → text.format (NOT response_format)\n // ------------------------------------------------------------------\n const structuredOutputRequested = req.outputJsonSchema !== undefined\n if (structuredOutputRequested) {\n const schema = req.outputJsonSchema\n const name =\n isPlainRecord(schema) &&\n typeof schema['title'] === 'string' &&\n schema['title'].length > 0\n ? schema['title']\n : 'structured_output'\n params.text = {\n format: { type: 'json_schema', name, schema, strict: true },\n }\n }\n\n // ------------------------------------------------------------------\n // 5. providerOptions.xai → prompt_cache_key\n // ------------------------------------------------------------------\n const xaiProviderConfig = mapXaiProviderOptions(\n genConfig.providerOptions?.['xai'],\n model,\n )\n if (xaiProviderConfig.promptCacheKey !== undefined) {\n params.prompt_cache_key = xaiProviderConfig.promptCacheKey\n }\n\n const hasFileRef = req.messages.some((msg) =>\n msg.parts.some((part) => part.kind === 'file-ref'),\n )\n const searchTools = xaiProviderConfig.tools\n if (searchTools !== undefined) {\n if (req.modelDescriptor?.capabilities?.grounding !== true) {\n throw badXaiRequest(\n `providerOptions.xai.tools requires capabilities.grounding on the model descriptor for \"${model}\".`,\n )\n }\n params.tools = searchTools\n }\n\n if (req.tools !== undefined && req.tools.length > 0) {\n if (req.modelDescriptor?.capabilities?.functionCalling !== true) {\n throw badXaiRequest(\n `tools is not supported for xai model \"${model}\" (capabilities.functionCalling is not true).`,\n )\n }\n const functionTools = req.tools.map((tool) => ({\n type: 'function',\n name: tool.name,\n description: tool.description,\n parameters: tool.inputJsonSchema,\n }))\n params.tools = [...(params.tools ?? []), ...functionTools]\n if (req.toolChoice !== undefined) {\n params.tool_choice =\n typeof req.toolChoice === 'string'\n ? req.toolChoice\n : { type: 'function', name: req.toolChoice.name }\n }\n }\n if (xaiProviderConfig.parallelToolCalls !== undefined) {\n params.parallel_tool_calls = xaiProviderConfig.parallelToolCalls\n }\n\n // ------------------------------------------------------------------\n // 6. Client construction + SDK call — inside the classifier so ANY\n // failure (including bad auth construction) is rethrown as a typed\n // LlmError(provider:'xai').\n // ------------------------------------------------------------------\n let response: XaiResponseShape\n try {\n const buildClient = opts?._clientFactory ?? buildXaiClient\n const client: XaiClientLike =\n opts?.client !== undefined ? opts.client : await buildClient(ctx.auth)\n ctx.logger.debug(\n { model, configKeys: Object.keys(params) },\n 'llm.adapter.dispatch',\n )\n response = await client.responses.create(\n params,\n ctx.signal !== undefined ? { signal: ctx.signal } : undefined,\n )\n } catch (rawErr) {\n throw classifyXaiError(rawErr)\n }\n\n // ------------------------------------------------------------------\n // 7. Map response\n // ------------------------------------------------------------------\n let text = ''\n let reasoningText: string | undefined\n const messageItems: XaiMessageOutputItem[] = []\n const toolCalls: NonNullable<AdapterResult['toolCalls']> = []\n\n for (const item of response.output) {\n if (isXaiMessageItem(item)) {\n messageItems.push(item)\n } else if (isXaiReasoningItem(item)) {\n const joined = item.summary.map((s) => s.text).join('')\n if (joined.length > 0) {\n reasoningText = (reasoningText ?? '') + joined\n }\n } else if (item.type === 'function_call') {\n const callId = typeof item['call_id'] === 'string' ? item['call_id'] : ''\n const name = typeof item['name'] === 'string' ? item['name'] : ''\n let args: JsonValue = {}\n if (typeof item['arguments'] === 'string') {\n try {\n args = JSON.parse(item['arguments']) as JsonValue\n } catch {\n args = item['arguments']\n }\n }\n if (callId.length > 0 && name.length > 0) {\n toolCalls.push({ toolCallId: callId, toolName: name, args })\n }\n }\n }\n\n // xAI's Responses API convention: when multiple `type: 'message'`\n // output items are present, the LAST one is the response — earlier\n // ones are superseded (observed live in strict json_schema mode,\n // grok-4.5, reasoning effort high: two complete-JSON message items in\n // one response). Concatenating across items corrupts the payload\n // (e.g. two JSON documents back-to-back); joining `output_text` parts\n // WITHIN a single message item is still correct (segmentation, not\n // duplication).\n if (messageItems.length > 0) {\n const lastMessage = messageItems[messageItems.length - 1] as XaiMessageOutputItem\n text = lastMessage.content.map((part) => part.text).join('')\n\n if (messageItems.length > 1) {\n warnings.push({\n type: 'other',\n message: `xai: response contained ${messageItems.length} message output items; using the last one and discarding ${\n messageItems.length - 1\n } earlier message item(s).`,\n })\n }\n }\n\n // Parse structured output (JSON text → rawStructured).\n let rawStructured: unknown\n if (structuredOutputRequested && text.length > 0) {\n try {\n rawStructured = JSON.parse(text)\n } catch {\n // Core reports unparsed via absence of rawStructured; callers own\n // validation/retry policy (ADR-009).\n }\n }\n\n const usage = mapUsage(response.usage)\n const finishReason = mapFinishReason(response)\n\n const expectedToolCounters = expectedServerToolCounters(\n xaiProviderConfig.tools,\n hasFileRef,\n )\n if (expectedToolCounters.length > 0 || hasFileRef) {\n usage.details['server_tools_requested'] = 1\n const missing = expectedToolCounters.filter((key) => !(key in usage.details))\n if (missing.length > 0) {\n usage.details['server_tools_missing'] = 1\n warnings.push({\n type: 'other',\n message: `xai: server tools were requested but usage is missing counters [${missing.join(\n ', ',\n )}]; tool cost will be estimated.`,\n })\n }\n if (hasFileRef) {\n // Attachment_search counter is not live-pinned (ZDR blocks file\n // attach). Never claim exact $0 for a file-ref call.\n usage.details['attachment_search_unpinned'] = 1\n warnings.push({\n type: 'other',\n message:\n 'xai: file-ref enables attachment_search but that counter is not live-pinned; tool cost is estimated.',\n })\n }\n }\n\n const citations = collectXaiCitations(response, messageItems)\n\n // Response-level metadata → providerMetadata: usage.context_details\n // (non-numeric usage extra) and response.metadata (e.g.\n // system_fingerprint). Numeric usage extras live in usage.details; the\n // full raw usage payload is already in usage.raw.\n const providerMeta: { [k: string]: JsonValue } = {}\n const contextDetails = response.usage['context_details']\n if (isPlainRecord(contextDetails)) {\n providerMeta['context_details'] = contextDetails as unknown as JsonValue\n }\n if (isPlainRecord(response.metadata)) {\n providerMeta['metadata'] = response.metadata as unknown as JsonValue\n }\n\n // Surface the echoed tier verbatim. xAI can remap (flex → default);\n // discarding non-priority values would let the engine fall back to the\n // requested tier and bill 2× on a default-served call.\n const servedServiceTier =\n typeof response.service_tier === 'string' && response.service_tier.length > 0\n ? response.service_tier\n : undefined\n\n const result: AdapterResult = {\n model: response.model,\n usage,\n warnings,\n finishReason,\n responseId: response.id,\n ...(text.length > 0 ? { text } : {}),\n ...(reasoningText !== undefined ? { reasoningText } : {}),\n ...(rawStructured !== undefined ? { rawStructured } : {}),\n ...(servedServiceTier !== undefined ? { servedServiceTier } : {}),\n ...(Object.keys(providerMeta).length > 0\n ? { providerMetadata: providerMeta }\n : {}),\n ...(citations.length > 0 ? { citations } : {}),\n ...(toolCalls.length > 0 ? { toolCalls, finishReason: 'tool_calls' } : {}),\n }\n\n return result\n },\n\n async countTokens(req: TokenCountRequest, ctx: AdapterCtx): Promise<TokenCount> {\n if (req.provider !== 'xai') {\n throw new LlmError(\n `xaiAdapter received a request for provider \"${req.provider}\", expected \"xai\".`,\n { kind: 'bad_request', retryable: false },\n )\n }\n if (req.tools !== undefined && req.tools.length > 0) {\n throw badXaiRequest(\n 'xAI countTokens rejects tools; tokenize-text cannot represent tool declarations.',\n )\n }\n\n const text = concatenateTokenizeText(req)\n const apiKey = requireApiKey(ctx.auth)\n const fetchImpl = opts?._fetch ?? fetch\n\n try {\n const res = await fetchImpl('https://api.x.ai/v1/tokenize-text', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ model: req.model, text }),\n ...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),\n })\n\n if (!res.ok) {\n let parsed: unknown\n try {\n parsed = await res.json()\n } catch {\n parsed = await res.text().catch(() => '')\n }\n throw Object.assign(new Error(`xAI tokenize-text HTTP ${res.status}`), {\n status: res.status,\n error: parsed,\n })\n }\n\n const raw: unknown = await res.json()\n if (!isPlainRecord(raw) || !Array.isArray(raw['token_ids'])) {\n throw new LlmError(\n 'xAI tokenize-text response is malformed: missing required field: token_ids',\n { kind: 'server', retryable: true, provider: 'xai' },\n )\n }\n const n = raw['token_ids'].length\n return {\n totalTokens: n,\n accuracy: 'lower-bound',\n details: { textTokens: n },\n raw: raw as JsonValue,\n }\n } catch (rawErr) {\n if (rawErr instanceof Error && rawErr.name === 'AbortError') {\n throw new LlmError('xAI tokenize-text aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n cause: rawErr,\n })\n }\n throw classifyXaiError(rawErr)\n }\n },\n }\n}\n\n/** Live-pinned 2026-08-24 counter names from `usage.server_side_tool_usage_details`. */\nconst WEB_SEARCH_COUNTER = 'web_search_calls'\nconst X_SEARCH_COUNTER = 'x_search_calls'\nfunction expectedServerToolCounters(\n tools: Array<Record<string, unknown>> | undefined,\n _hasFileRef: boolean,\n): string[] {\n const keys: string[] = []\n if (tools !== undefined) {\n for (const tool of tools) {\n if (tool['type'] === 'web_search') keys.push(WEB_SEARCH_COUNTER)\n if (tool['type'] === 'x_search') keys.push(X_SEARCH_COUNTER)\n }\n }\n return keys\n}\n\nfunction collectXaiCitations(\n response: XaiResponseShape,\n messageItems: XaiMessageOutputItem[],\n): Citation[] {\n const seen = new Set<string>()\n const citations: Citation[] = []\n\n const push = (url: unknown, title: unknown) => {\n if (typeof url !== 'string' || url.length === 0) return\n if (seen.has(url)) return\n seen.add(url)\n const citation: Citation = { url }\n if (typeof title === 'string' && title.length > 0 && title !== url) {\n citation.title = title\n }\n try {\n const parsed = new URL(url)\n if (parsed.hostname.length > 0) {\n citation.sourceName = parsed.hostname.startsWith('www.')\n ? parsed.hostname.slice(4)\n : parsed.hostname\n }\n } catch {\n /* keep url-only */\n }\n citations.push(citation)\n }\n\n if (Array.isArray(response.citations)) {\n for (const item of response.citations) {\n if (typeof item === 'string') {\n push(item, undefined)\n } else if (isPlainRecord(item)) {\n push(item['url'] ?? item['uri'], item['title'])\n }\n }\n }\n\n const lastMessage = messageItems.at(-1)\n const citationMessages = lastMessage === undefined ? [] : [lastMessage]\n for (const item of citationMessages) {\n for (const part of item.content) {\n const annotations = part.annotations\n if (!Array.isArray(annotations)) continue\n for (const ann of annotations) {\n if (!isPlainRecord(ann)) continue\n if (ann['type'] !== undefined && ann['type'] !== 'url_citation') continue\n push(ann['url'], ann['title'])\n }\n }\n }\n\n return citations\n}\n\nfunction concatenateTokenizeText(req: TokenCountRequest): string {\n const chunks: string[] = []\n if (req.system !== undefined && req.system.length > 0) {\n chunks.push(req.system)\n }\n for (const message of req.messages) {\n for (const part of message.parts) {\n switch (part.kind) {\n case 'text':\n chunks.push(part.text)\n break\n case 'inline-media':\n case 'file-uri':\n case 'file-ref':\n case 'tool-call':\n case 'tool-result':\n throw badXaiRequest(\n `xAI countTokens rejects ${part.kind} parts; tokenize-text is text-only.`,\n )\n default:\n return assertNever(part)\n }\n }\n }\n return chunks.join('\\n')\n}\n","/**\n * XaiFileStore — thin wrapper over the xAI Files REST API.\n *\n * Upload / get / list / delete / content over injectable `fetch`.\n * No READY-state polling (upload returns metadata immediately).\n * No ambient credential reads — auth is injected at construction.\n *\n * @module\n */\n\nimport type { AuthMaterial, JsonValue, Logger } from '@gullabs/core'\nimport { LlmError, classifyError, redactSecrets } from '@gullabs/core'\n\nimport { requireApiKey } from './client.js'\nimport { classifyXaiError } from './adapter.js'\n\n// ---------------------------------------------------------------------------\n// Public constants\n// ---------------------------------------------------------------------------\n\n/** xAI minimum `expires_after` (1 hour), inclusive. */\nexport const XAI_FILE_TTL_MIN_SECONDS = 3_600\n\n/** xAI maximum `expires_after` (30 days), inclusive. */\nexport const XAI_FILE_TTL_MAX_SECONDS = 2_592_000\n\n/**\n * Conservative max upload size (48 MiB). Managing-files docs say ~48 MB;\n * upload REST says 50 MB — we take the lower bound.\n */\nexport const XAI_FILE_MAX_BYTES = 48 * 1024 * 1024\n\n/** Default Files API base (includes `/v1`). */\nexport const XAI_FILES_DEFAULT_BASE_URL = 'https://api.x.ai/v1'\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** A handle to a file stored in the xAI Files API. */\nexport interface XaiFileHandle {\n /** File id, e.g. `\"file_a128090d-…\"`. Use as `FileRefPart.fileId`. */\n id: string\n filename?: string\n bytes?: number\n purpose?: string\n createdAt?: Date\n /** Present when the file has a TTL; key omitted when permanent / unknown. */\n expiresAt?: Date\n /** Full vendor JSON object for forward-compat (P2 raw lane). */\n raw?: { [k: string]: JsonValue }\n}\n\nexport interface XaiFileUploadInput {\n data: Uint8Array | Blob\n filename: string\n mimeType?: string\n /**\n * TTL in seconds. Must be an integer in\n * `[XAI_FILE_TTL_MIN_SECONDS, XAI_FILE_TTL_MAX_SECONDS]` when set.\n * Omit only for permanent storage (discouraged for ephemeral corpus).\n */\n expiresAfterSeconds?: number\n /** Default `\"assistants\"` (OpenAI SDK convention; xAI does not enforce). */\n purpose?: string\n}\n\nexport interface XaiFileListOptions {\n /** 1..100. Server default is 100 when omitted. */\n limit?: number\n order?: 'asc' | 'desc'\n sortBy?: 'created_at' | 'filename' | 'size'\n paginationToken?: string\n}\n\nexport interface XaiFileListResult {\n files: XaiFileHandle[]\n paginationToken?: string\n}\n\n/**\n * Options for {@link XaiFileStore.delete} / {@link XaiFileStore.deleteAll}.\n *\n * Default is fail-open (P5 side-effect style). Pass `failClosed: true` when\n * the host gates durable state (e.g. `released_at`) on known delete success.\n */\nexport interface FileDeleteOptions {\n signal?: AbortSignal\n /**\n * When true, non-404 failures throw typed `LlmError`.\n * When false/omitted, non-404 failures invoke `onDeleteError` and resolve.\n * HTTP 404 is success in both modes (idempotent).\n */\n failClosed?: boolean\n}\n\nexport interface XaiFileStoreOptions {\n auth: AuthMaterial\n /** Default {@link XAI_FILES_DEFAULT_BASE_URL}. */\n baseUrl?: string\n /** Injectable fetch for tests. Default: global `fetch`. */\n fetch?: typeof fetch\n /**\n * Delete failures that are NOT already-gone (404).\n * Default: `logger.error` or `console.error` with a redacted message.\n */\n onDeleteError?: (fileId: string, err: unknown) => void\n logger?: Logger\n /** Injectable clock for tests. Default: `Date.now`. */\n now?: () => number\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\ntype VendorFileObject = {\n id?: unknown\n filename?: unknown\n bytes?: unknown\n purpose?: unknown\n created_at?: unknown\n expires_at?: unknown\n object?: unknown\n [k: string]: unknown\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction badRequest(message: string): LlmError {\n return new LlmError(message, {\n kind: 'bad_request',\n retryable: false,\n provider: 'xai',\n })\n}\n\nfunction resolveFileId(fileIdOrHandle: string | Pick<XaiFileHandle, 'id'>): string {\n if (typeof fileIdOrHandle === 'string') {\n return fileIdOrHandle\n }\n return fileIdOrHandle.id\n}\n\nfunction unixSecondsToDate(value: unknown): Date | undefined {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return undefined\n }\n return new Date(value * 1000)\n}\n\nfunction makeHandle(raw: VendorFileObject): XaiFileHandle {\n if (typeof raw.id !== 'string' || raw.id.length === 0) {\n throw new LlmError('File response missing required field (id)', {\n kind: 'server',\n retryable: false,\n provider: 'xai',\n })\n }\n\n const handle: XaiFileHandle = {\n id: raw.id,\n raw: raw as { [k: string]: JsonValue },\n }\n\n if (typeof raw.filename === 'string' && raw.filename.length > 0) {\n handle.filename = raw.filename\n }\n if (typeof raw.bytes === 'number' && Number.isFinite(raw.bytes)) {\n handle.bytes = raw.bytes\n }\n if (typeof raw.purpose === 'string') {\n handle.purpose = raw.purpose\n }\n\n const createdAt = unixSecondsToDate(raw.created_at)\n if (createdAt !== undefined) {\n handle.createdAt = createdAt\n }\n\n // expires_at is null for permanent files — omit the key entirely (Google parity).\n if (raw.expires_at !== null && raw.expires_at !== undefined) {\n const expiresAt = unixSecondsToDate(raw.expires_at)\n if (expiresAt !== undefined) {\n handle.expiresAt = expiresAt\n }\n }\n\n return handle\n}\n\nfunction byteLengthOf(data: Uint8Array | Blob): number {\n return data instanceof Uint8Array ? data.byteLength : data.size\n}\n\nfunction toBlob(data: Uint8Array | Blob, mimeType: string | undefined): Blob {\n if (data instanceof Blob) {\n return data\n }\n // Copy into a plain ArrayBuffer-backed view for BlobPart typing.\n const copy = Uint8Array.from(data)\n return mimeType !== undefined && mimeType.length > 0\n ? new Blob([copy], { type: mimeType })\n : new Blob([copy])\n}\n\n/**\n * Shape a non-2xx fetch response into a throw value that\n * {@link classifyXaiError} / {@link classifyError} understand:\n * - `.status` for HTTP routing\n * - `.error` for structured body (auth-body detection)\n */\n/**\n * Error shaped for {@link classifyError} / {@link classifyXaiError}:\n * numeric `.status` for HTTP routing, `.error` for structured body text.\n */\nclass XaiFilesHttpError extends Error {\n readonly status: number\n readonly error: unknown\n\n constructor(status: number, message: string, errorBody: unknown) {\n super(message)\n this.name = 'XaiFilesHttpError'\n this.status = status\n this.error = errorBody\n }\n}\n\nasync function throwHttpFailure(res: Response): Promise<never> {\n const status = res.status\n let bodyText = ''\n try {\n bodyText = await res.text()\n } catch {\n bodyText = ''\n }\n\n let parsed: unknown = bodyText\n if (bodyText.length > 0) {\n try {\n parsed = JSON.parse(bodyText) as unknown\n } catch {\n parsed = bodyText\n }\n }\n\n let message = `xAI Files API HTTP ${status}`\n if (typeof parsed === 'string' && parsed.length > 0) {\n message = parsed\n } else if (isPlainRecord(parsed) && typeof parsed['error'] === 'string') {\n message = parsed['error']\n }\n\n throw new XaiFilesHttpError(status, message, parsed)\n}\n\nfunction isNotFoundError(err: unknown): boolean {\n if (err instanceof LlmError && err.httpStatus === 404) {\n return true\n }\n if (typeof err === 'object' && err !== null) {\n const status = (err as { status?: unknown }).status\n if (status === 404) return true\n const httpStatus = (err as { httpStatus?: unknown }).httpStatus\n if (httpStatus === 404) return true\n }\n return false\n}\n\nfunction notFoundError(fileId: string, operation: string): LlmError {\n return new LlmError(`xAI file not found during ${operation}: \"${fileId}\"`, {\n kind: 'bad_request',\n retryable: false,\n httpStatus: 404,\n provider: 'xai',\n })\n}\n\nfunction maybeZdrHint(message: string): string {\n if (\n /zero\\s*data\\s*retention|\\bzdr\\b|files?\\s+(api\\s+)?(disabled|unavailable|not supported)/i.test(\n message,\n )\n ) {\n return `${message} (xAI Zero Data Retention blocks new file uploads and file_id attachments for this team.)`\n }\n return message\n}\n\n/** Prefer structured body text / explicit message over generic `HTTP NNN`. */\nfunction extractThrownMessage(raw: unknown): string | undefined {\n if (raw === null || typeof raw !== 'object') return undefined\n const obj = raw as Record<string, unknown>\n if (typeof obj['message'] === 'string' && obj['message'].length > 0) {\n return obj['message']\n }\n const err = obj['error']\n if (typeof err === 'string' && err.length > 0) return err\n if (typeof err === 'object' && err !== null) {\n const nested = err as Record<string, unknown>\n if (typeof nested['error'] === 'string' && nested['error'].length > 0) {\n return nested['error']\n }\n if (typeof nested['message'] === 'string' && nested['message'].length > 0) {\n return nested['message']\n }\n }\n return undefined\n}\n\nfunction classifyStoreError(raw: unknown): LlmError {\n if (raw instanceof LlmError) {\n return raw\n }\n const classified = classifyXaiError(raw)\n const bodyMessage = extractThrownMessage(raw)\n // classifyError maps plain `{ status }` throws to generic \"HTTP NNN\" — prefer\n // the structured body text we attached in throwHttpFailure when present.\n const baseMessage =\n bodyMessage !== undefined &&\n (classified.message.startsWith('HTTP ') || classified.message.length === 0)\n ? bodyMessage\n : classified.message\n const hinted = maybeZdrHint(baseMessage)\n if (\n hinted === classified.message &&\n classified.provider === 'xai' &&\n bodyMessage === undefined\n ) {\n return classified\n }\n return new LlmError(hinted, {\n kind: classified.kind,\n retryable: classified.retryable,\n ...(classified.httpStatus !== undefined ? { httpStatus: classified.httpStatus } : {}),\n ...(classified.retryAfterMs !== undefined\n ? { retryAfterMs: classified.retryAfterMs }\n : {}),\n provider: 'xai',\n cause: classified.cause ?? raw,\n })\n}\n\n// ---------------------------------------------------------------------------\n// XaiFileStore\n// ---------------------------------------------------------------------------\n\n/**\n * **Auth snapshot note:** captures `AuthMaterial` at construction and holds\n * the resolved API key for the store lifetime. Correct for static API keys.\n * Refreshable credentials would need a resolver callback (see GoogleFileStore\n * / ADR-020).\n */\nexport class XaiFileStore {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly fetchImpl: typeof fetch\n private readonly onDeleteError: (fileId: string, err: unknown) => void\n private readonly logger: Logger | undefined\n\n constructor(opts: XaiFileStoreOptions) {\n this.apiKey = requireApiKey(opts.auth)\n this.baseUrl = (opts.baseUrl ?? XAI_FILES_DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.fetchImpl = opts.fetch ?? fetch\n this.logger = opts.logger\n this.onDeleteError =\n opts.onDeleteError ??\n ((fileId, err) => {\n const message = redactSecrets(classifyError(err).message)\n if (this.logger !== undefined) {\n this.logger.error({ fileId, error: message }, 'xai.file.delete.failed')\n } else {\n console.error(`[XaiFileStore] delete failed for \"${fileId}\":`, message)\n }\n })\n }\n\n private authHeaders(): Headers {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${this.apiKey}`)\n return headers\n }\n\n private filesUrl(path = ''): string {\n if (path.length === 0) return `${this.baseUrl}/files`\n return `${this.baseUrl}/files/${path.replace(/^\\//, '')}`\n }\n\n /** Build RequestInit without writing `signal: undefined` (exactOptionalPropertyTypes). */\n private requestInit(\n method: string,\n opts?: { body?: FormData; signal?: AbortSignal },\n ): RequestInit {\n const init: RequestInit = {\n method,\n headers: this.authHeaders(),\n }\n if (opts?.body !== undefined) {\n init.body = opts.body\n }\n if (opts?.signal !== undefined) {\n init.signal = opts.signal\n }\n return init\n }\n\n /**\n * Upload bytes to xAI Files. Returns immediately with metadata (no poll).\n *\n * Multipart field order is load-bearing: `expires_after` then `purpose`\n * then `file` — reversing order yields HTTP 400 from xAI.\n */\n async upload(input: XaiFileUploadInput, signal?: AbortSignal): Promise<XaiFileHandle> {\n if (typeof input.filename !== 'string' || input.filename.trim() === '') {\n throw badRequest('XaiFileUploadInput.filename must be a non-empty string.')\n }\n\n const size = byteLengthOf(input.data)\n if (size > XAI_FILE_MAX_BYTES) {\n throw badRequest(\n `xAI file uploads must be at most ${XAI_FILE_MAX_BYTES} bytes (48 MiB); got ${size}.`,\n )\n }\n\n if (input.expiresAfterSeconds !== undefined) {\n const ttl = input.expiresAfterSeconds\n if (\n typeof ttl !== 'number' ||\n !Number.isInteger(ttl) ||\n ttl < XAI_FILE_TTL_MIN_SECONDS ||\n ttl > XAI_FILE_TTL_MAX_SECONDS\n ) {\n throw badRequest(\n `expiresAfterSeconds must be an integer in [${XAI_FILE_TTL_MIN_SECONDS}, ${XAI_FILE_TTL_MAX_SECONDS}]; got ${String(ttl)}.`,\n )\n }\n }\n\n const purpose = input.purpose ?? 'assistants'\n const form = new FormData()\n\n // Order: expires_after → purpose → file (xAI multipart requirement).\n if (input.expiresAfterSeconds !== undefined) {\n form.append('expires_after', String(input.expiresAfterSeconds))\n }\n form.append('purpose', purpose)\n form.append('file', toBlob(input.data, input.mimeType), input.filename)\n\n let res: Response\n try {\n res = await this.fetchImpl(\n this.filesUrl(),\n this.requestInit('POST', {\n body: form,\n ...(signal !== undefined ? { signal } : {}),\n }),\n )\n } catch (e) {\n if (signal?.aborted === true) {\n throw new LlmError('xAI file upload aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n })\n }\n throw classifyStoreError(e)\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res)\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n let json: unknown\n try {\n json = await res.json()\n } catch (e) {\n throw new LlmError('xAI file upload returned non-JSON body', {\n kind: 'server',\n retryable: false,\n provider: 'xai',\n cause: e,\n })\n }\n\n return makeHandle(json as VendorFileObject)\n }\n\n async get(fileId: string, signal?: AbortSignal): Promise<XaiFileHandle> {\n if (typeof fileId !== 'string' || fileId.trim() === '') {\n throw badRequest('fileId must be a non-empty string.')\n }\n\n let res: Response\n try {\n res = await this.fetchImpl(\n this.filesUrl(fileId),\n this.requestInit('GET', signal !== undefined ? { signal } : {}),\n )\n } catch (e) {\n if (signal?.aborted === true) {\n throw new LlmError('xAI file get aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n })\n }\n throw classifyStoreError(e)\n }\n\n if (res.status === 404) {\n throw notFoundError(fileId, 'get')\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res)\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n const json = (await res.json()) as VendorFileObject\n return makeHandle(json)\n }\n\n async list(\n opts: XaiFileListOptions = {},\n signal?: AbortSignal,\n ): Promise<XaiFileListResult> {\n if (opts.limit !== undefined) {\n if (\n typeof opts.limit !== 'number' ||\n !Number.isInteger(opts.limit) ||\n opts.limit < 1 ||\n opts.limit > 100\n ) {\n throw badRequest('list.limit must be an integer in [1, 100].')\n }\n }\n\n const params = new URLSearchParams()\n if (opts.limit !== undefined) params.set('limit', String(opts.limit))\n if (opts.order !== undefined) params.set('order', opts.order)\n if (opts.sortBy !== undefined) params.set('sort_by', opts.sortBy)\n if (opts.paginationToken !== undefined) {\n params.set('pagination_token', opts.paginationToken)\n }\n\n const qs = params.toString()\n const url = qs.length > 0 ? `${this.filesUrl()}?${qs}` : this.filesUrl()\n\n let res: Response\n try {\n res = await this.fetchImpl(\n url,\n this.requestInit('GET', signal !== undefined ? { signal } : {}),\n )\n } catch (e) {\n if (signal?.aborted === true) {\n throw new LlmError('xAI file list aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n })\n }\n throw classifyStoreError(e)\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res)\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n const json = (await res.json()) as {\n data?: VendorFileObject[]\n pagination_token?: string\n }\n const files = Array.isArray(json.data) ? json.data.map((f) => makeHandle(f)) : []\n const result: XaiFileListResult = { files }\n if (typeof json.pagination_token === 'string' && json.pagination_token.length > 0) {\n result.paginationToken = json.pagination_token\n }\n return result\n }\n\n /**\n * Delete a file. Idempotent: HTTP 404 → success.\n *\n * Default (`failClosed` omitted/false): non-404 errors go to `onDeleteError`\n * and resolve (P5 fail-open). With `failClosed: true`, non-404 errors throw\n * typed `LlmError` and `onDeleteError` is not called.\n *\n * Empty/blank ids always throw `bad_request` (caller fault).\n */\n async delete(\n fileIdOrHandle: string | Pick<XaiFileHandle, 'id'>,\n opts?: FileDeleteOptions,\n ): Promise<void> {\n const fileId = resolveFileId(fileIdOrHandle)\n if (typeof fileId !== 'string' || fileId.trim() === '') {\n throw badRequest('fileId must be a non-empty string.')\n }\n\n const failClosed = opts?.failClosed === true\n const signal = opts?.signal\n\n try {\n const res = await this.fetchImpl(\n this.filesUrl(fileId),\n this.requestInit('DELETE', signal !== undefined ? { signal } : {}),\n )\n\n if (res.status === 404) {\n return\n }\n\n if (!res.ok) {\n await throwHttpFailure(res)\n }\n } catch (err) {\n if (isNotFoundError(err)) {\n return\n }\n\n // Abort during fetch: surface as aborted LlmError through the same path.\n const classified =\n signal?.aborted === true && !(err instanceof LlmError)\n ? new LlmError('xAI file delete aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n cause: err,\n })\n : classifyStoreError(err)\n\n if (failClosed) {\n throw classified\n }\n this.onDeleteError(fileId, classified)\n }\n }\n\n /**\n * Delete many files.\n *\n * Fail-open (default): `Promise.allSettled` — each failure → `onDeleteError`.\n * Fail-closed: `Promise.all` — first throw rejects; in-flight siblings are\n * not cancelled (partial deletes may already have succeeded at the provider).\n * Prefer per-id delete + host DB mark when gating durable release state.\n */\n async deleteAll(\n ids: ReadonlyArray<string | Pick<XaiFileHandle, 'id'>>,\n opts?: FileDeleteOptions,\n ): Promise<void> {\n if (opts?.failClosed === true) {\n await Promise.all(ids.map((id) => this.delete(id, opts)))\n return\n }\n await Promise.allSettled(ids.map((id) => this.delete(id, opts)))\n }\n\n /** Download raw file bytes. */\n async getContent(fileId: string, signal?: AbortSignal): Promise<Uint8Array> {\n if (typeof fileId !== 'string' || fileId.trim() === '') {\n throw badRequest('fileId must be a non-empty string.')\n }\n\n let res: Response\n try {\n res = await this.fetchImpl(\n this.filesUrl(`${fileId}/content`),\n this.requestInit('GET', signal !== undefined ? { signal } : {}),\n )\n } catch (e) {\n if (signal?.aborted === true) {\n throw new LlmError('xAI file content download aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n })\n }\n throw classifyStoreError(e)\n }\n\n if (res.status === 404) {\n throw notFoundError(fileId, 'getContent')\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res)\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n const buf = await res.arrayBuffer()\n return new Uint8Array(buf)\n }\n}\n","/**\n * Structurally representable Zod schemas for xAI Live Search tools.\n *\n * Public config constraints are encoded as unions of exclusive shapes so\n * derived JSON Schema is exact (no `superRefine` / `check`).\n *\n * @module\n */\n\nimport { z } from 'zod'\n\nconst webSearchFlags = {\n enableImageUnderstanding: z.boolean().optional().meta({\n title: 'Enable Image Understanding',\n description: 'Ask xAI to analyze images found during web search.',\n }),\n enableImageSearch: z.boolean().optional().meta({\n title: 'Enable Image Search',\n description: 'Ask xAI to include image search results.',\n }),\n}\n\nexport const XaiWebSearchToolSchema = z\n .union([\n z.strictObject({\n type: z.literal('web_search'),\n allowedDomains: z.array(z.string()).max(5),\n ...webSearchFlags,\n }),\n z.strictObject({\n type: z.literal('web_search'),\n excludedDomains: z.array(z.string()).max(5),\n ...webSearchFlags,\n }),\n z.strictObject({\n type: z.literal('web_search'),\n ...webSearchFlags,\n }),\n ])\n .meta({\n title: 'XaiWebSearchTool',\n description:\n 'xAI web_search server tool. allowedDomains and excludedDomains are mutually exclusive (max 5).',\n })\n\nconst xSearchFlags = {\n fromDate: z.iso.date().optional().meta({\n title: 'From Date',\n description: 'Inclusive ISO-8601 date lower bound for X search.',\n }),\n toDate: z.iso.date().optional().meta({\n title: 'To Date',\n description: 'Inclusive ISO-8601 date upper bound for X search.',\n }),\n enableImageUnderstanding: z.boolean().optional().meta({\n title: 'Enable Image Understanding',\n description: 'Ask xAI to analyze images in matched posts.',\n }),\n enableVideoUnderstanding: z.boolean().optional().meta({\n title: 'Enable Video Understanding',\n description: 'Ask xAI to analyze videos in matched posts.',\n }),\n}\n\nexport const XaiXSearchToolSchema = z\n .union([\n z.strictObject({\n type: z.literal('x_search'),\n allowedXHandles: z.array(z.string()).max(20),\n ...xSearchFlags,\n }),\n z.strictObject({\n type: z.literal('x_search'),\n excludedXHandles: z.array(z.string()).max(20),\n ...xSearchFlags,\n }),\n z.strictObject({\n type: z.literal('x_search'),\n ...xSearchFlags,\n }),\n ])\n .meta({\n title: 'XaiXSearchTool',\n description:\n 'xAI x_search server tool. allowedXHandles and excludedXHandles are mutually exclusive (max 20).',\n })\n\n/**\n * Admitted tools combinations: at most one web_search and at most one x_search.\n * Both orders are admitted so callers are not rejected for listing order.\n */\nexport const XaiToolsSchema = z\n .union([\n z.tuple([XaiWebSearchToolSchema]),\n z.tuple([XaiXSearchToolSchema]),\n z.tuple([XaiWebSearchToolSchema, XaiXSearchToolSchema]),\n z.tuple([XaiXSearchToolSchema, XaiWebSearchToolSchema]),\n ])\n .meta({\n title: 'XaiTools',\n description:\n 'xAI Live Search tools. At most one web_search and at most one x_search.',\n })\n\nexport const XaiProviderOptionsSchema = z\n .strictObject({\n promptCacheKey: z\n .string()\n .min(1)\n .optional()\n .meta({\n title: 'Prompt Cache Key',\n description:\n 'xAI conversation-routing cache key — maps to Responses API ' +\n '`prompt_cache_key`.',\n }),\n tools: XaiToolsSchema.optional().meta({\n title: 'Live Search Tools',\n description: 'xAI server-side web_search / x_search tools.',\n }),\n parallelToolCalls: z.boolean().optional().meta({\n title: 'Parallel Tool Calls',\n description: 'xAI Responses parallel_tool_calls. Not a generic contract field.',\n }),\n })\n .meta({\n title: 'xAI Provider Options',\n description: 'Allowlisted xAI provider options.',\n })\n","/**\n * Strict Zod config schema for xAI's `grok-4.5` model.\n *\n * Mirrors `@gullabs/core`'s `packages/core/src/model-config/*.ts` doc-density\n * style, but is a single self-contained `z.strictObject` — unlike Gemini's\n * schemas, xai has no service-tier branching (no `z.union` of tier variants\n * needed), no `topK`, and a reasoning-effort union of `'low'|'medium'|'high'`\n * (live-verified 2026-08-24).\n *\n * @module\n */\n\nimport { z } from 'zod'\n\nimport { XaiProviderOptionsSchema } from './tools.js'\n\nexport const Grok45ConfigSchema = z\n .strictObject({\n temperature: z.number().optional().meta({\n title: 'Temperature',\n description: 'Sampling temperature forwarded verbatim to grok-4.5.',\n }),\n topP: z.number().optional().meta({\n title: 'Top P',\n description: 'Nucleus sampling parameter forwarded verbatim to grok-4.5.',\n }),\n maxOutputTokens: z\n .number()\n .int()\n .positive()\n .optional()\n .meta({\n title: 'Max Output Tokens',\n description:\n 'Maximum output token cap for grok-4.5. No artificial ceiling — xAI ' +\n 'accepts arbitrarily large values (live-verified); truncation surfaces ' +\n \"as finishReason:'length', not an error.\",\n }),\n reasoning: z\n .strictObject({\n effort: z.enum(['low', 'medium', 'high']).meta({\n title: 'Reasoning Effort',\n description:\n 'Reasoning effort for grok-4.5. \"low\", \"medium\", and \"high\" are ' +\n 'admitted (live-verified 2026-08-24); \"none\"/\"xhigh\" are rejected ' +\n 'by the live API. Vendor default when omitted is \"high\".',\n }),\n })\n .optional()\n .meta({\n title: 'Reasoning',\n description:\n 'grok-4.5 effort-level reasoning configuration. No budgetTokens field — ' +\n 'xAI uses level-style reasoning, not token budgets.',\n }),\n timeoutMs: z.number().int().positive().optional().meta({\n title: 'Timeout',\n description: 'Logical request timeout in milliseconds.',\n }),\n providerOptions: z\n .strictObject({\n xai: XaiProviderOptionsSchema.optional(),\n })\n .optional()\n .meta({\n title: 'Provider Options',\n description: 'Provider-specific options accepted for grok-4.5.',\n }),\n })\n .meta({\n title: 'Grok45Config',\n description:\n 'Strict Responses API config for model grok-4.5. Level reasoning ' +\n '(low/medium/high), tunable sampling, no service tiers, structured output, ' +\n 'vision, Live Search tools, priced.',\n examples: [{ reasoning: { effort: 'high' } }],\n })\n","/**\n * Strict Zod config schema for xAI's `grok-4.6` model.\n *\n * Same Responses-API surface as grok-4.5, plus live-verified (2026-08-12)\n * `reasoning.effort` of `'low' | 'medium' | 'high' | 'xhigh'` and\n * `serviceTier: 'priority'`. `'none'` is rejected by the live API. Unknown\n * tiers (`flex`, `standard`, `batch`) are rejected — `flex` is silently\n * remapped to `default` by xAI, so this schema never admits it.\n *\n * @module\n */\n\nimport { z } from 'zod'\n\nimport { XaiProviderOptionsSchema } from './tools.js'\n\nexport const Grok46ConfigSchema = z\n .strictObject({\n temperature: z.number().optional().meta({\n title: 'Temperature',\n description: 'Sampling temperature forwarded verbatim to grok-4.6.',\n }),\n topP: z.number().optional().meta({\n title: 'Top P',\n description: 'Nucleus sampling parameter forwarded verbatim to grok-4.6.',\n }),\n maxOutputTokens: z\n .number()\n .int()\n .positive()\n .optional()\n .meta({\n title: 'Max Output Tokens',\n description:\n 'Maximum output token cap for grok-4.6. No artificial ceiling — xAI ' +\n 'accepts arbitrarily large values; truncation surfaces as ' +\n \"finishReason:'length', not an error.\",\n }),\n reasoning: z\n .strictObject({\n effort: z.enum(['low', 'medium', 'high', 'xhigh']).meta({\n title: 'Reasoning Effort',\n description:\n 'Reasoning effort for grok-4.6. Live-verified 2026-08-12: \"low\", ' +\n '\"medium\", \"high\", and \"xhigh\" are accepted; \"none\" is rejected. ' +\n 'Vendor default when omitted is \"high\".',\n }),\n })\n .optional()\n .meta({\n title: 'Reasoning',\n description:\n 'grok-4.6 effort-level reasoning configuration. No budgetTokens field — ' +\n 'xAI uses level-style reasoning, not token budgets.',\n }),\n serviceTier: z\n .literal('priority')\n .optional()\n .meta({\n title: 'Service Tier',\n description:\n 'xAI priority processing for grok-4.6 (Responses `service_tier: ' +\n '\"priority\"`). Echo live-verified 2026-08-12. Bills at 2× after the ' +\n 'cache discount (uncached standard-list 2× confirmed by live ticks; ' +\n 'cached/long-context legs follow the official 2× rule). ' +\n 'Omitted requests stay on xAI default. ' +\n '\"flex\"/\"standard\"/\"batch\" are rejected.',\n }),\n timeoutMs: z.number().int().positive().optional().meta({\n title: 'Timeout',\n description: 'Logical request timeout in milliseconds.',\n }),\n providerOptions: z\n .strictObject({\n xai: XaiProviderOptionsSchema.optional(),\n })\n .optional()\n .meta({\n title: 'Provider Options',\n description: 'Provider-specific options accepted for grok-4.6.',\n }),\n })\n .meta({\n title: 'Grok46Config',\n description:\n 'Strict Responses API config for model grok-4.6. Level reasoning ' +\n '(low/medium/high/xhigh), optional priority service tier, tunable sampling, ' +\n 'structured output, vision, priced.',\n examples: [{ reasoning: { effort: 'high' } }],\n })\n","/**\n * Model descriptor + registry for @gullabs/xai.\n *\n * Ships two canonical models: `grok-4.5` and `grok-4.6`. xAI aliases\n * (`grok-4.5-latest`, `grok-build-latest`) visible in `/v1/models` are\n * intentionally NOT registered (reject-don't-map). `grok-4.6` has no\n * aliases as of the 2026-08-12 `/v1/models` listing.\n *\n * @module\n */\n\nimport type { ModelDescriptor, ModelRegistry } from '@gullabs/core'\nimport {\n createModelRegistry,\n toConfigJsonSchema,\n zodToStandardSchema,\n} from '@gullabs/core'\n\nimport { Grok45ConfigSchema } from './model-config/grok-4-5.js'\nimport { Grok46ConfigSchema } from './model-config/grok-4-6.js'\n\nexport { Grok45ConfigSchema } from './model-config/grok-4-5.js'\nexport { Grok46ConfigSchema } from './model-config/grok-4-6.js'\n\nexport const grok45ModelDescriptor: ModelDescriptor = {\n model: 'grok-4.5',\n provider: 'xai',\n pricingFamily: 'grok-4.5',\n capabilities: {\n reasoning: true,\n reasoningApi: 'level',\n admittedReasoningEfforts: ['low', 'medium', 'high'],\n structuredOutput: true,\n nativeStructuredOutput: true,\n vision: true,\n audioInput: false,\n sampling: 'tunable',\n caching: { explicit: false, minTokens: 0 },\n grounding: true,\n functionCalling: true,\n // No serviceTiers key — grok-4.5 has no admitted service-tier vocabulary.\n },\n configSchema: Grok45ConfigSchema,\n configJsonSchema: toConfigJsonSchema(Grok45ConfigSchema),\n validateConfig: zodToStandardSchema(Grok45ConfigSchema),\n}\n\nexport const grok46ModelDescriptor: ModelDescriptor = {\n model: 'grok-4.6',\n provider: 'xai',\n pricingFamily: 'grok-4.6',\n capabilities: {\n reasoning: true,\n reasoningApi: 'level',\n admittedReasoningEfforts: ['low', 'medium', 'high', 'xhigh'],\n structuredOutput: true,\n nativeStructuredOutput: true,\n vision: true,\n audioInput: false,\n sampling: 'tunable',\n caching: { explicit: false, minTokens: 0 },\n grounding: true,\n functionCalling: true,\n serviceTiers: ['priority'],\n },\n configSchema: Grok46ConfigSchema,\n configJsonSchema: toConfigJsonSchema(Grok46ConfigSchema),\n validateConfig: zodToStandardSchema(Grok46ConfigSchema),\n}\n\n/** Every model descriptor `@gullabs/xai` contributes. */\nexport const xaiModelDescriptors: ModelDescriptor[] = [\n grok45ModelDescriptor,\n grok46ModelDescriptor,\n]\n\nexport const xaiRegistry: ModelRegistry = createModelRegistry(xaiModelDescriptors)\n","/**\n * xAI pricing snapshot + cost computation for @gullabs/xai.\n *\n * All rates are in **micro-USD per million tokens** (µUSD/M), matching\n * `@gullabs/core`'s `ModelRates` convention exactly: `cost_µUSD = N *\n * ratePerM / 1_000_000`.\n *\n * This is a SELF-CONTAINED, xai-owned reimplementation — it does NOT import\n * core's Gemini-specific `computeCost`/`GEMINI_PRICING`/`geminiPricingSource`\n * (those are Gemini-only). `PricingSource` is provider-scoped by contract\n * (see `packages/core/src/ports.ts`); this module is xai's own.\n *\n * **Long-context tier.** grok-4.5 / grok-4.6 charge a premium when the GROSS\n * input token count exceeds 200,000 (`long_context_threshold` in xAI's\n * `/v1/models` listing). Selected by `inputTokens` (incl. cached), not by\n * billable input — mirrors core's `selectRates` convention exactly (strictly\n * greater than 200,000).\n *\n * **Service tiers.** grok-4.5 has none. grok-4.6 admits `'priority'`\n * (echo live-verified 2026-08-12). The 2× multiplier is confirmed by\n * fixture `12-grok-4-6-xhigh-priority.json` (`cost_in_usd_ticks` equals\n * exactly 2× standard list). `'default'` (the value xAI echoes when no\n * priority is served) and `undefined` (no tier requested) price at the\n * standard list. Any other defined tier is unpriced (reject-don't-map).\n *\n * **Conversion factor.** xAI's `/v1/models` raw `*_token_price` fields are\n * in hundred-thousandths of a dollar per token (i.e. divide the raw integer\n * by 10,000 to get USD per million tokens): e.g. `grok-4.6`'s raw\n * `prompt_text_token_price: 20000` ÷ 10,000 = $2.00/M.\n *\n * Verified against `/v1/models` on 2026-08-12. Prior snapshot\n * `xai-2026-07-09` priced grok-4.5 cached input at $0.50 / $1.00; the live\n * listing now reports $0.30 / $0.60.\n *\n * @module\n */\n\nimport type { Cost, PricingSource, Usage } from '@gullabs/core'\n\n/** Identifies this pricing snapshot — bump the date when rates change. */\nexport const xaiPricingVersion = 'xai-2026-08-24' as const\n\n/**\n * Live-pinned 2026-08-24 per-invocation tool rates (µUSD per call).\n * Source: `usage.server_side_tool_usage_details` on /v1/responses.\n * $5 / 1,000 web or X searches. Attachment search is not priced until live-pinned.\n */\nexport const XAI_TOOL_RATE_MICRO_USD = {\n web_search_calls: 5_000,\n x_search_calls: 5_000,\n} as const\n\nconst XAI_TOOL_COUNTER_KEYS = ['web_search_calls', 'x_search_calls'] as const\n\n/**\n * Per-model rate entry (all values in µUSD per million tokens).\n *\n * `gt200k` (when present) applies when GROSS input tokens > 200,000.\n */\nexport interface XaiModelRates {\n /** µUSD per million input tokens (billable = gross − cached). */\n inputPerM: number\n /** µUSD per million cache-read tokens. */\n cachedPerM: number\n /** µUSD per million output tokens (reasoning tokens are folded in). */\n outputPerM: number\n /** Optional high-tier rates for long-context (GROSS input > 200k). */\n gt200k?: {\n inputPerM: number\n cachedPerM: number\n outputPerM: number\n }\n /**\n * Multiplier for Responses `service_tier: \"priority\"`. Absent = this\n * model does not admit priority (unpriced). Uncached standard-list 2×\n * is confirmed by fixture `12-grok-4-6-xhigh-priority.json` ticks;\n * cached and `gt200k` legs follow the official 2×-after-cache-discount\n * docs rule (that fixture has cached=0 and input < 200k).\n */\n priorityFactor?: number\n}\n\n/**\n * Frozen xAI pricing snapshot (per-1M in µUSD).\n *\n * Keys are EXACT canonical model identifiers — no prefix or alias matching.\n * xAI aliases (e.g. `grok-4.5-latest`, `grok-build-latest`) are deliberately\n * NOT registered/priced (reject-don't-map): callers must use the canonical\n * id; anything else resolves to the unpriced path.\n */\nexport const XAI_PRICING: Readonly<Record<string, XaiModelRates>> = Object.freeze({\n // ── grok-4.5 ── $2.00/$6.00 (≤200k), $4.00/$12.00 (>200k); cached $0.30/$0.60\n 'grok-4.5': {\n inputPerM: 2_000_000,\n cachedPerM: 300_000,\n outputPerM: 6_000_000,\n gt200k: {\n inputPerM: 4_000_000,\n cachedPerM: 600_000,\n outputPerM: 12_000_000,\n },\n },\n // ── grok-4.6 ── $2.00/$6.00 (≤200k), $4.00/$12.00 (>200k); cached $0.50/$1.00\n 'grok-4.6': {\n inputPerM: 2_000_000,\n cachedPerM: 500_000,\n outputPerM: 6_000_000,\n gt200k: {\n inputPerM: 4_000_000,\n cachedPerM: 1_000_000,\n outputPerM: 12_000_000,\n },\n // Confirmed 2026-08-12 by fixture 12 cost_in_usd_ticks (2× list).\n priorityFactor: 2,\n },\n})\n\nconst LONG_CONTEXT_THRESHOLD = 200_000\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Look up rates for a model — EXACT match only.\n *\n * Deliberately no prefix matching (unlike core's Gemini lookup): xAI aliases\n * such as `grok-4.5-latest` would otherwise prefix-match `grok-4.5` and\n * silently reintroduce the alias behavior the model registry rejects. An id\n * that is not an exact `XAI_PRICING` key is unpriced.\n */\nfunction lookupRates(model: string): XaiModelRates | undefined {\n return XAI_PRICING[model]\n}\n\n/**\n * Select the applicable rate set for a model given the GROSS input token\n * count. When a model has a `gt200k` tier, that tier's rates apply when\n * `grossInputTokens` is **strictly greater than** 200,000.\n */\nfunction selectRates(\n rates: XaiModelRates,\n grossInputTokens: number,\n): { inputPerM: number; cachedPerM: number; outputPerM: number } {\n if (rates.gt200k !== undefined && grossInputTokens > LONG_CONTEXT_THRESHOLD) {\n return rates.gt200k\n }\n return {\n inputPerM: rates.inputPerM,\n cachedPerM: rates.cachedPerM,\n outputPerM: rates.outputPerM,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the cost of an xAI LLM call given a model name and usage data.\n *\n * Pure function — no side effects, always returns a well-formed {@link Cost}.\n *\n * **Algorithm** (mirrors `@gullabs/core`'s `computeCost` exactly, xai-owned):\n * 1. Look up rates for `model`; if not found, return an unpriced `Cost`\n * (`microUsd: null`) naming the model.\n * 2. `undefined` or `'default'` prices at the standard list.\n * `'priority'` applies `rates.priorityFactor` when present.\n * Any other defined tier, or `'priority'` on a model without\n * `priorityFactor`, is unpriced (reject-don't-map).\n * 3. Select base vs. `>200k` long-context rates from GROSS `inputTokens`.\n * 4. Billable input = `inputTokens − (cachedInputTokens ?? 0)`, clamped to 0.\n * 5. Round each component (input, cached, output) independently to the\n * nearest integer micro-USD.\n * 6. `microUsd` is the sum of the four components — guarantees\n * `details.input + details.cached + details.output + details.tools === microUsd`.\n * 7. Tool lanes: live-pinned counters `web_search_calls`, `x_search_calls`.\n * Missing expected counters → `tools: 0`, `estimated`. File-ref sets\n * `attachment_search_unpinned` → `estimated` (attachment not priced).\n * `'exact'` requires no unpinned attachment and counters present or no\n * server tools requested.\n */\nexport function computeXaiCost(model: string, usage: Usage, tier?: string): Cost {\n const rates = lookupRates(model)\n\n if (rates === undefined) {\n return {\n microUsd: null,\n usd: null,\n pricingVersion: xaiPricingVersion,\n confidence: 'estimated',\n details: { input: 0, cached: 0, output: 0, tools: 0 },\n unpricedReason: `Unknown model \"${model}\"; no pricing entry found.`,\n }\n }\n\n let factor = 1\n if (tier !== undefined && tier !== 'default') {\n if (tier === 'priority' && rates.priorityFactor !== undefined) {\n factor = rates.priorityFactor\n } else {\n return {\n microUsd: null,\n usd: null,\n pricingVersion: xaiPricingVersion,\n confidence: 'estimated',\n details: { input: 0, cached: 0, output: 0, tools: 0 },\n unpricedReason: `Unknown service tier \"${tier}\"; xai model \"${model}\" has no such tier, refusing to guess a pricing multiplier.`,\n }\n }\n }\n\n const base = selectRates(rates, usage.inputTokens)\n\n const cached = usage.cachedInputTokens ?? 0\n const billableInput = Math.max(0, usage.inputTokens - cached)\n\n const inputCost = Math.round((billableInput * base.inputPerM * factor) / 1_000_000)\n const cachedCost = Math.round((cached * base.cachedPerM * factor) / 1_000_000)\n const outputCost = Math.round(\n (usage.outputTokens * base.outputPerM * factor) / 1_000_000,\n )\n\n const serverToolsRequested = usage.details['server_tools_requested'] === 1\n const missingRequestedCounters =\n usage.details['server_tools_missing'] === 1 ||\n (serverToolsRequested &&\n usage.details['attachment_search_unpinned'] !== 1 &&\n !XAI_TOOL_COUNTER_KEYS.some((key) => key in usage.details))\n const attachmentUnpinned = usage.details['attachment_search_unpinned'] === 1\n\n const toolsCost = missingRequestedCounters\n ? 0\n : XAI_TOOL_COUNTER_KEYS.reduce((sum, key) => {\n const count = usage.details[key]\n if (typeof count !== 'number' || count <= 0) return sum\n return sum + Math.round(count * XAI_TOOL_RATE_MICRO_USD[key])\n }, 0)\n\n const microUsd = inputCost + cachedCost + outputCost + toolsCost\n\n return {\n microUsd,\n usd: microUsd / 1_000_000,\n pricingVersion: xaiPricingVersion,\n confidence: missingRequestedCounters || attachmentUnpinned ? 'estimated' : 'exact',\n details: {\n input: inputCost,\n cached: cachedCost,\n output: outputCost,\n tools: toolsCost,\n },\n }\n}\n\n/**\n * Factory that returns the **xai-scoped** {@link PricingSource} port\n * implementation backed by {@link XAI_PRICING}.\n *\n * @example\n * ```ts\n * import { xaiPricingSource } from '@gullabs/xai'\n *\n * const pricing = xaiPricingSource()\n * const cost = pricing.price('grok-4.6', usage)\n * ```\n */\nexport function xaiPricingSource(): PricingSource {\n return {\n version: xaiPricingVersion,\n price(model: string, usage: Usage, tier?: string): Cost {\n return computeXaiCost(model, usage, tier)\n },\n hasModel(model: string): boolean {\n return lookupRates(model) !== undefined\n },\n listModels(): readonly string[] {\n return Object.keys(XAI_PRICING)\n },\n }\n}\n","/**\n * `xaiProvider` — {@link ProviderPlugin} factory for @gullabs/xai.\n *\n * Bundles the xAI Grok adapter, the `grok-4.5` / `grok-4.6` model\n * descriptors, and the xai pricing source into a single plugin for\n * {@link composeProviders}.\n *\n * @module\n */\n\nimport type { ProviderPlugin } from '@gullabs/core'\n\nimport { xaiAdapter } from './adapter.js'\nimport type { XaiAdapterOptions } from './adapter.js'\nimport { xaiModelDescriptors } from './models.js'\nimport { xaiPricingSource } from './pricing.js'\n\n/**\n * Create a {@link ProviderPlugin} for the xAI Grok provider.\n *\n * @param opts - Forwarded to {@link xaiAdapter}.\n * @returns A plugin bundling the xAI adapter, the `grok-4.5` / `grok-4.6`\n * model descriptors, and the built-in xai pricing source.\n *\n * @example\n * ```ts\n * import { createClient, composeProviders } from '@gullabs/core'\n * import { xaiProvider } from '@gullabs/xai'\n *\n * const client = createClient({\n * ...composeProviders([xaiProvider()]),\n * })\n * ```\n */\nexport function xaiProvider(opts?: XaiAdapterOptions): ProviderPlugin {\n return {\n adapter: xaiAdapter(opts),\n modelDescriptors: xaiModelDescriptors,\n pricingSource: xaiPricingSource(),\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/model-config/tools.ts","../src/model-config/grok-4-5.ts","../src/model-config/grok-4-6.ts","../src/model-config/grok-4-7.ts","../src/models.ts","../src/pricing.ts","../src/adapter.ts","../src/file-store.ts","../src/provider.ts"],"names":["z","LlmError","isPlainRecord","classifyError"],"mappings":";;;;AA0BO,SAAS,cAAc,IAAA,EAA4B;AACxD,EAAA,IACE,EAAE,QAAA,I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AAAA,IAC1C;AAEA,IAAA,IAAI,CAAC,IAAI,EAAA,EAAI;AACX,MAAA,IAAI;AACF,QAAA,MAAM,iBAAiB,GAAG,CAAA;AAAA,MAC5B,SAAS,CAAA,EAAG;AACV,QAAA,MAAM,mBAAmB,CAAC,CAAA;AAAA,MAC5B;AAAA,IACF;AAEA,IAAA,MAAM,GAAA,GAAM,MAAM,GAAA,CAAI,WAAA,EAAY;AAClC,IAAA,OAAO,IAAI,WAAW,GAAG,CAAA;AAAA,EAC3B;AACF;;;AClqBO,SAAS,YAAY,IAAA,EAA0C;AACpE,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,WAAW,IAAI,CAAA;AAAA,IACxB,gBAAA,EAAkB,mBAAA;AAAA,IAClB,eAAe,gBAAA;AAAiB,GAClC;AACF","file":"index.js","sourcesContent":["/**\n * Structural XaiClientLike interface + buildXaiClient factory.\n *\n * This module defines the structural interface the adapter depends on.\n * The real `openai` SDK is imported ONLY in buildXaiClient so tests can\n * inject a fake without pulling in the real SDK. This is the ONLY file in\n * `packages/xai/src` that imports `openai`.\n *\n * @module\n */\n\nimport { LlmError } from '@gullabs/core'\nimport type { AuthMaterial } from '@gullabs/core'\n\n// ---------------------------------------------------------------------------\n// Auth narrowing — xAI only accepts ApiKeyAuth\n// ---------------------------------------------------------------------------\n\n/**\n * Narrows {@link AuthMaterial} to its `apiKey` string, rejecting the\n * dev-only `CliSessionAuth` variant.\n *\n * xAI is a production API provider and only ever accepts API-key\n * credentials; `{ cliSession: true }` is reserved for the dev-only CLI\n * provider packages (`@gullabs/claude-cli`, `@gullabs/codex-cli`).\n */\nexport function requireApiKey(auth: AuthMaterial): string {\n if (\n !('apiKey' in auth) ||\n typeof auth.apiKey !== 'string' ||\n auth.apiKey.trim() === ''\n ) {\n throw new LlmError('@gullabs/xai requires auth.apiKey', {\n kind: 'invalid_auth',\n retryable: false,\n provider: 'xai',\n })\n }\n return auth.apiKey\n}\n\n// ---------------------------------------------------------------------------\n// Request shape — what the (future) adapter sends to responses.create\n// ---------------------------------------------------------------------------\n\n/** A text content item within an xAI Responses API input message. */\nexport interface XaiInputTextPart {\n type: 'input_text'\n text: string\n}\n\n/**\n * An image content item within an xAI Responses API input message.\n * `image_url` may be a data URL (`data:image/png;base64,...`) or a public URL.\n */\nexport interface XaiInputImagePart {\n type: 'input_image'\n image_url: string\n}\n\n/**\n * A file attachment content item within an xAI Responses API input message.\n * Prefer `file_id` for private uploads (via {@link XaiFileStore}); `file_url`\n * is for publicly reachable documents. Attaching either implicitly enables\n * xAI's `attachment_search` agentic tool.\n */\nexport interface XaiInputFilePart {\n type: 'input_file'\n file_id?: string\n file_url?: string\n}\n\n/** Union of content-part shapes an input message may carry. */\nexport type XaiInputContentPart = XaiInputTextPart | XaiInputImagePart | XaiInputFilePart\n\n/** A single role+content input item constructed by the (future) adapter. */\nexport interface XaiInputItem {\n role: 'user' | 'assistant' | 'system' | 'developer'\n content: XaiInputContentPart[]\n}\n\n/** Live-verified store:false replay item. */\nexport interface XaiFunctionCallInputItem {\n type: 'function_call'\n call_id: string\n name: string\n arguments: string\n}\n\n/** Live-verified store:false replay item. */\nexport interface XaiFunctionCallOutputInputItem {\n type: 'function_call_output'\n call_id: string\n output: string\n}\n\nexport type XaiRequestInputItem =\n XaiInputItem | XaiFunctionCallInputItem | XaiFunctionCallOutputInputItem | XaiOutputItem\n\n/** Full wire history for stateless continuation. */\nexport interface XaiReplayState {\n model: string\n input: XaiRequestInputItem[]\n}\n\n/**\n * Structured-output text-format request shape.\n * Real xAI field: `text.format`, NOT `response_format`.\n * `name` and `strict` are included per xAI's Structured Outputs docs\n * conventions even though the live fixture's request-echo does not surface\n * them (only the schema is echoed back).\n */\nexport type XaiTextFormat =\n | { type: 'json_schema'; name: string; schema: unknown; strict: boolean }\n | { type: 'text' }\n\n/**\n * Parameters for `client.responses.create`.\n * Structurally modeled from live-captured xAI Responses API fixtures\n * (see docs/provider-plugins-and-xai-grok-4-5-plan.md §3.1), not from the\n * `openai` npm package's TS types — xAI's actual endpoint shape differs.\n */\nexport interface XaiResponseCreateParams {\n model: string\n input: XaiRequestInputItem[]\n instructions?: string\n reasoning?: { effort: 'low' | 'medium' | 'high' | 'xhigh' }\n text?: { format: XaiTextFormat }\n temperature?: number\n top_p?: number\n max_output_tokens?: number\n prompt_cache_key?: string\n /**\n * Responses `service_tier`. Only `'priority'` is forwarded (live-verified\n * on grok-4.6, 2026-08-12). Omitted when the caller did not request a tier.\n */\n service_tier?: 'priority'\n /** Always `false` — this library never relies on xAI-side conversation storage. */\n store: false\n /**\n * Server-side and/or function tools. Wire names are snake_case.\n * Shape is pinned from live 2026-08-24 fixtures.\n */\n tools?: Array<Record<string, unknown>>\n /** `'auto' | 'required' | 'none'` or live-verified `{ type: 'function', name }`. */\n tool_choice?: string | { type: 'function'; name: string }\n parallel_tool_calls?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Response shape — mirrors the xAI Responses API surface we actually consume\n// ---------------------------------------------------------------------------\n\n/** A single summary-text segment of a `type: 'reasoning'` output item. */\nexport interface XaiReasoningSummaryPart {\n type: 'summary_text'\n text: string\n}\n\n/** A `type: 'reasoning'` item in `output`. */\nexport interface XaiReasoningOutputItem {\n type: 'reasoning'\n id?: string\n summary: XaiReasoningSummaryPart[]\n status?: string\n}\n\n/** A single text content segment of a `type: 'message'` output item. */\nexport interface XaiOutputTextPart {\n type: 'output_text'\n text: string\n logprobs?: unknown[]\n annotations?: unknown[]\n}\n\n/** A `type: 'message'` item in `output`. */\nexport interface XaiMessageOutputItem {\n type: 'message'\n id?: string\n role?: string\n status?: string\n content: XaiOutputTextPart[]\n}\n\n/** Server-tool or function-call output items we do not collapse as messages. */\nexport interface XaiOtherOutputItem {\n type: string\n [key: string]: unknown\n}\n\n/** Union of output-item shapes the Responses API may return. */\nexport type XaiOutputItem =\n XaiReasoningOutputItem | XaiMessageOutputItem | XaiOtherOutputItem\n\n/**\n * Token usage metadata returned alongside an xAI response.\n *\n * Kept loose/open: the known fields are typed, but xAI has been observed to\n * add additional numeric fields (e.g. `num_sources_used`,\n * `cost_in_usd_ticks`, `context_details`) that must not break this type.\n */\nexport interface XaiUsageShape {\n input_tokens: number\n input_tokens_details?: { cached_tokens?: number }\n output_tokens: number\n output_tokens_details?: { reasoning_tokens?: number }\n total_tokens?: number\n /** Additional provider-specific usage fields, passed through raw. */\n [otherKeys: string]: unknown\n}\n\n/**\n * Structural equivalent of the xAI Responses API response body.\n * Only the fields the (future) adapter reads are represented here.\n */\nexport interface XaiResponseShape {\n id: string\n model: string\n /**\n * Real field: `status`. Observed values: \"completed\", \"incomplete\" — kept\n * as a plain `string` since xAI may add further status values over time.\n */\n status: string\n incomplete_details?: { reason?: string } | null\n output: XaiOutputItem[]\n usage: XaiUsageShape\n reasoning?: { effort?: string; summary?: string }\n /**\n * Echoed served tier. Observed values: `\"default\"`, `\"priority\"`.\n * Kept as a plain string — xAI may add further values.\n */\n service_tier?: string\n store?: boolean\n prompt_cache_key?: string | null\n /**\n * Response-level metadata (e.g. `system_fingerprint`) — surfaced into\n * `AdapterResult.providerMetadata` by the adapter when present.\n */\n metadata?: { [key: string]: unknown } | null\n /**\n * Top-level citations array. Live 2026-08-24 search-tools probes returned\n * `null`; citations arrived as `output_text.annotations` of type\n * `url_citation` instead.\n */\n citations?: unknown\n}\n\n// ---------------------------------------------------------------------------\n// XaiClientLike — structural interface (no `openai` dependency)\n// ---------------------------------------------------------------------------\n\n/**\n * Structural interface for the `openai` SDK's `client.responses` surface\n * the adapter uses.\n *\n * Satisfied by:\n * - The real `openai` `OpenAI` client (via `buildXaiClient` wrapper), pointed\n * at xAI's `https://api.x.ai/v1` base URL.\n * - `FakeXaiClient` from `@gullabs/testing`.\n */\nexport interface XaiClientLike {\n responses: {\n create(\n params: XaiResponseCreateParams,\n options?: { signal?: AbortSignal },\n ): Promise<XaiResponseShape>\n }\n}\n\n// ---------------------------------------------------------------------------\n// buildXaiClient — imports the real `openai` SDK\n// ---------------------------------------------------------------------------\n\n/**\n * Build a real `openai`-SDK-backed client from AuthMaterial, pointed at\n * xAI's Responses API endpoint.\n *\n * Only API-key authentication is supported.\n *\n * @param auth - API key credentials ({ apiKey }).\n */\nexport async function buildXaiClient(auth: AuthMaterial): Promise<XaiClientLike> {\n // Resolve and validate auth BEFORE importing the SDK so auth-rejection\n // tests never need to touch the real `openai` module (and thus never hit\n // the network).\n const apiKey = requireApiKey(auth)\n\n const { default: OpenAI } = await import('openai')\n\n const client = new OpenAI({\n apiKey,\n baseURL: 'https://api.x.ai/v1',\n maxRetries: 0,\n })\n\n return {\n responses: {\n async create(\n params: XaiResponseCreateParams,\n options?: { signal?: AbortSignal },\n ): Promise<XaiResponseShape> {\n // Cast needed: our structural types are subsets of the real SDK types,\n // and the real SDK's types do not exactly match xAI's actual response\n // shape (see module doc comment).\n return (\n client.responses.create as unknown as (\n p: unknown,\n o?: { signal?: AbortSignal },\n ) => Promise<XaiResponseShape>\n )(params, options)\n },\n },\n }\n}\n","/**\n * Structurally representable Zod schemas for xAI Live Search tools.\n *\n * Public config constraints are encoded as unions of exclusive shapes so\n * derived JSON Schema is exact (no `superRefine` / `check`).\n *\n * @module\n */\n\nimport { z } from 'zod'\n\nconst webSearchFlags = {\n enableImageUnderstanding: z.boolean().optional().meta({\n title: 'Enable Image Understanding',\n description: 'Ask xAI to analyze images found during web search.',\n }),\n enableImageSearch: z.boolean().optional().meta({\n title: 'Enable Image Search',\n description: 'Ask xAI to include image search results.',\n }),\n}\n\nexport const XaiWebSearchToolSchema = z\n .union([\n z.strictObject({\n type: z.literal('web_search'),\n allowedDomains: z.array(z.string()).max(5),\n ...webSearchFlags,\n }),\n z.strictObject({\n type: z.literal('web_search'),\n excludedDomains: z.array(z.string()).max(5),\n ...webSearchFlags,\n }),\n z.strictObject({\n type: z.literal('web_search'),\n ...webSearchFlags,\n }),\n ])\n .meta({\n title: 'XaiWebSearchTool',\n description:\n 'xAI web_search server tool. allowedDomains and excludedDomains are mutually exclusive (max 5).',\n })\n\nconst xSearchFlags = {\n fromDate: z.iso.date().optional().meta({\n title: 'From Date',\n description: 'Inclusive ISO-8601 date lower bound for X search.',\n }),\n toDate: z.iso.date().optional().meta({\n title: 'To Date',\n description: 'Inclusive ISO-8601 date upper bound for X search.',\n }),\n enableImageUnderstanding: z.boolean().optional().meta({\n title: 'Enable Image Understanding',\n description: 'Ask xAI to analyze images in matched posts.',\n }),\n enableVideoUnderstanding: z.boolean().optional().meta({\n title: 'Enable Video Understanding',\n description: 'Ask xAI to analyze videos in matched posts.',\n }),\n}\n\nexport const XaiXSearchToolSchema = z\n .union([\n z.strictObject({\n type: z.literal('x_search'),\n allowedXHandles: z.array(z.string()).max(20),\n ...xSearchFlags,\n }),\n z.strictObject({\n type: z.literal('x_search'),\n excludedXHandles: z.array(z.string()).max(20),\n ...xSearchFlags,\n }),\n z.strictObject({\n type: z.literal('x_search'),\n ...xSearchFlags,\n }),\n ])\n .meta({\n title: 'XaiXSearchTool',\n description:\n 'xAI x_search server tool. allowedXHandles and excludedXHandles are mutually exclusive (max 20).',\n })\n\n/**\n * Admitted tools combinations: at most one web_search and at most one x_search.\n * Both orders are admitted so callers are not rejected for listing order.\n */\nexport const XaiToolsSchema = z\n .union([\n z.tuple([XaiWebSearchToolSchema]),\n z.tuple([XaiXSearchToolSchema]),\n z.tuple([XaiWebSearchToolSchema, XaiXSearchToolSchema]),\n z.tuple([XaiXSearchToolSchema, XaiWebSearchToolSchema]),\n ])\n .meta({\n title: 'XaiTools',\n description:\n 'xAI Live Search tools. At most one web_search and at most one x_search.',\n })\n\nexport const XaiProviderOptionsSchema = z\n .strictObject({\n promptCacheKey: z\n .string()\n .min(1)\n .optional()\n .meta({\n title: 'Prompt Cache Key',\n description:\n 'xAI conversation-routing cache key — maps to Responses API ' +\n '`prompt_cache_key`.',\n }),\n tools: XaiToolsSchema.optional().meta({\n title: 'Live Search Tools',\n description: 'xAI server-side web_search / x_search tools.',\n }),\n parallelToolCalls: z.boolean().optional().meta({\n title: 'Parallel Tool Calls',\n description: 'xAI Responses parallel_tool_calls. Not a generic contract field.',\n }),\n })\n .meta({\n title: 'xAI Provider Options',\n description: 'Allowlisted xAI provider options.',\n })\n","/**\n * Strict Zod config schema for xAI's `grok-4.5` model.\n *\n * Mirrors `@gullabs/core`'s `packages/core/src/model-config/*.ts` doc-density\n * style, but is a single self-contained `z.strictObject` — unlike Gemini's\n * schemas, xai has no service-tier branching (no `z.union` of tier variants\n * needed), no `topK`, and a reasoning-effort union of `'low'|'medium'|'high'`\n * (live-verified 2026-08-24).\n *\n * @module\n */\n\nimport { z } from 'zod'\n\nimport { XaiProviderOptionsSchema } from './tools.js'\n\nexport const Grok45ConfigSchema = z\n .strictObject({\n temperature: z.number().optional().meta({\n title: 'Temperature',\n description: 'Sampling temperature forwarded verbatim to grok-4.5.',\n }),\n topP: z.number().optional().meta({\n title: 'Top P',\n description: 'Nucleus sampling parameter forwarded verbatim to grok-4.5.',\n }),\n maxOutputTokens: z\n .number()\n .int()\n .positive()\n .optional()\n .meta({\n title: 'Max Output Tokens',\n description:\n 'Maximum output token cap for grok-4.5. No artificial ceiling — xAI ' +\n 'accepts arbitrarily large values (live-verified); truncation surfaces ' +\n \"as finishReason:'length', not an error.\",\n }),\n reasoning: z\n .strictObject({\n effort: z.enum(['low', 'medium', 'high']).meta({\n title: 'Reasoning Effort',\n description:\n 'Reasoning effort for grok-4.5. \"low\", \"medium\", and \"high\" are ' +\n 'admitted (live-verified 2026-08-24). \"xhigh\" is rejected here even ' +\n 'though /v1/language-models lists it: the reasoning guide says it is ' +\n 'treated as high, and an echo does not prove a distinct level. ' +\n '\"none\" is rejected. Vendor default when omitted is \"high\".',\n }),\n })\n .optional()\n .meta({\n title: 'Reasoning',\n description:\n 'grok-4.5 effort-level reasoning configuration. No budgetTokens field — ' +\n 'xAI uses level-style reasoning, not token budgets.',\n }),\n serviceTier: z.literal('priority').optional().meta({\n title: 'Service Tier',\n description:\n 'xAI priority processing for grok-4.5, billed at 2× on input, cached input, and output tokens. Live-verified 2026-09-25.',\n }),\n timeoutMs: z.number().int().positive().optional().meta({\n title: 'Timeout',\n description: 'Logical request timeout in milliseconds.',\n }),\n providerOptions: z\n .strictObject({\n xai: XaiProviderOptionsSchema.optional(),\n })\n .optional()\n .meta({\n title: 'Provider Options',\n description: 'Provider-specific options accepted for grok-4.5.',\n }),\n })\n .meta({\n title: 'Grok45Config',\n description:\n 'Strict Responses API config for model grok-4.5. Level reasoning ' +\n '(low/medium/high), optional priority service tier, tunable sampling, ' +\n 'structured output, vision, Live Search tools, priced.',\n examples: [{ reasoning: { effort: 'high' } }],\n })\n","/**\n * Strict Zod config schema for xAI's `grok-4.6` model.\n *\n * Same Responses-API surface as grok-4.5, plus live-verified (2026-08-12)\n * `reasoning.effort` of `'low' | 'medium' | 'high' | 'xhigh'` and\n * `serviceTier: 'priority'`. `'none'` is rejected by the live API. Unknown\n * tiers (`flex`, `standard`, `batch`) are rejected — `flex` is silently\n * remapped to `default` by xAI, so this schema never admits it.\n *\n * @module\n */\n\nimport { z } from 'zod'\n\nimport { XaiProviderOptionsSchema } from './tools.js'\n\nexport const Grok46ConfigSchema = z\n .strictObject({\n temperature: z.number().optional().meta({\n title: 'Temperature',\n description: 'Sampling temperature forwarded verbatim to grok-4.6.',\n }),\n topP: z.number().optional().meta({\n title: 'Top P',\n description: 'Nucleus sampling parameter forwarded verbatim to grok-4.6.',\n }),\n maxOutputTokens: z\n .number()\n .int()\n .positive()\n .optional()\n .meta({\n title: 'Max Output Tokens',\n description:\n 'Maximum output token cap for grok-4.6. No artificial ceiling — xAI ' +\n 'accepts arbitrarily large values; truncation surfaces as ' +\n \"finishReason:'length', not an error.\",\n }),\n reasoning: z\n .strictObject({\n effort: z.enum(['low', 'medium', 'high', 'xhigh']).meta({\n title: 'Reasoning Effort',\n description:\n 'Reasoning effort for grok-4.6. Live-verified 2026-08-12: \"low\", ' +\n '\"medium\", \"high\", and \"xhigh\" are accepted; \"none\" is rejected. ' +\n 'Vendor default when omitted is \"high\".',\n }),\n })\n .optional()\n .meta({\n title: 'Reasoning',\n description:\n 'grok-4.6 effort-level reasoning configuration. No budgetTokens field — ' +\n 'xAI uses level-style reasoning, not token budgets.',\n }),\n serviceTier: z\n .literal('priority')\n .optional()\n .meta({\n title: 'Service Tier',\n description:\n 'xAI priority processing for grok-4.6 (Responses `service_tier: ' +\n '\"priority\"`). Echo live-verified 2026-08-12. Bills at 2× after the ' +\n 'cache discount (uncached standard-list 2× confirmed by live ticks; ' +\n 'cached/long-context legs follow the official 2× rule). ' +\n 'Omitted requests stay on xAI default. ' +\n '\"flex\"/\"standard\"/\"batch\" are rejected.',\n }),\n timeoutMs: z.number().int().positive().optional().meta({\n title: 'Timeout',\n description: 'Logical request timeout in milliseconds.',\n }),\n providerOptions: z\n .strictObject({\n xai: XaiProviderOptionsSchema.optional(),\n })\n .optional()\n .meta({\n title: 'Provider Options',\n description: 'Provider-specific options accepted for grok-4.6.',\n }),\n })\n .meta({\n title: 'Grok46Config',\n description:\n 'Strict Responses API config for model grok-4.6. Level reasoning ' +\n '(low/medium/high/xhigh), optional priority service tier, tunable sampling, ' +\n 'structured output, vision, priced.',\n examples: [{ reasoning: { effort: 'high' } }],\n })\n","/**\n * Strict Zod config schema for xAI's `grok-4.7` model.\n *\n * Same Responses-API surface as grok-4.6: `reasoning.effort` of\n * `'low' | 'medium' | 'high' | 'xhigh'` and `serviceTier: 'priority'`.\n * Shaped from the grok-4.6 contract. The 2026-09-25 priority success and\n * effort-none rejection and P-X3 encrypted-reasoning multi-turn replay are\n * fixture-backed. `'none'` stays rejected.\n * Unknown tiers (`flex`, `standard`, `batch`) are rejected.\n *\n * @module\n */\n\nimport { z } from 'zod'\n\nimport { XaiProviderOptionsSchema } from './tools.js'\n\nexport const Grok47ConfigSchema = z\n .strictObject({\n temperature: z.number().optional().meta({\n title: 'Temperature',\n description: 'Sampling temperature forwarded verbatim to grok-4.7.',\n }),\n topP: z.number().optional().meta({\n title: 'Top P',\n description: 'Nucleus sampling parameter forwarded verbatim to grok-4.7.',\n }),\n maxOutputTokens: z\n .number()\n .int()\n .positive()\n .optional()\n .meta({\n title: 'Max Output Tokens',\n description:\n 'Maximum output token cap for grok-4.7. No artificial ceiling — xAI ' +\n 'accepts arbitrarily large values; truncation surfaces as ' +\n \"finishReason:'length', not an error.\",\n }),\n reasoning: z\n .strictObject({\n effort: z.enum(['low', 'medium', 'high', 'xhigh']).meta({\n title: 'Reasoning Effort',\n description:\n 'Reasoning effort for grok-4.7. \"low\", ' +\n '\"medium\", \"high\", and \"xhigh\" are accepted; \"none\" is rejected. ' +\n 'Vendor default when omitted is \"high\".',\n }),\n })\n .optional()\n .meta({\n title: 'Reasoning',\n description:\n 'grok-4.7 effort-level reasoning configuration. No budgetTokens field — ' +\n 'xAI uses level-style reasoning, not token budgets.',\n }),\n serviceTier: z\n .literal('priority')\n .optional()\n .meta({\n title: 'Service Tier',\n description:\n 'xAI priority processing for grok-4.7 (Responses `service_tier: ' +\n '\"priority\"`). Bills at 2× after the ' +\n 'cache discount (uncached standard-list 2× ' +\n 'cached/long-context legs follow the official 2× rule). ' +\n 'Omitted requests stay on xAI default. ' +\n '\"flex\"/\"standard\"/\"batch\" are rejected.',\n }),\n timeoutMs: z.number().int().positive().optional().meta({\n title: 'Timeout',\n description: 'Logical request timeout in milliseconds.',\n }),\n providerOptions: z\n .strictObject({\n xai: XaiProviderOptionsSchema.optional(),\n })\n .optional()\n .meta({\n title: 'Provider Options',\n description: 'Provider-specific options accepted for grok-4.7.',\n }),\n })\n .meta({\n title: 'Grok47Config',\n description:\n 'Strict Responses API config for model grok-4.7. Level reasoning ' +\n '(low/medium/high/xhigh), optional priority service tier, tunable sampling, ' +\n 'structured output, vision, priced.',\n examples: [{ reasoning: { effort: 'high' } }],\n })\n","/**\n * Model descriptor + registry for @gullabs/xai.\n *\n * Ships `grok-4.5`, `grok-4.6`, and `grok-4.7`. xAI aliases\n * (`grok-4.5-latest`, `grok-build-latest`) visible in `/v1/models` are\n * intentionally NOT registered (reject-don't-map). `grok-4.6` has no\n * aliases as of the 2026-08-12 `/v1/models` listing.\n *\n * @module\n */\n\nimport type { ModelDescriptor, ModelRegistry } from '@gullabs/core'\nimport {\n createModelRegistry,\n toConfigJsonSchema,\n zodToStandardSchema,\n} from '@gullabs/core'\n\nimport { Grok45ConfigSchema } from './model-config/grok-4-5.js'\nimport { Grok46ConfigSchema } from './model-config/grok-4-6.js'\nimport { Grok47ConfigSchema } from './model-config/grok-4-7.js'\n\nexport { Grok45ConfigSchema } from './model-config/grok-4-5.js'\nexport { Grok46ConfigSchema } from './model-config/grok-4-6.js'\nexport { Grok47ConfigSchema } from './model-config/grok-4-7.js'\n\nexport const grok45ModelDescriptor: ModelDescriptor = {\n model: 'grok-4.5',\n provider: 'xai',\n pricingFamily: 'grok-4.5',\n capabilities: {\n reasoning: true,\n reasoningApi: 'level',\n admittedReasoningEfforts: ['low', 'medium', 'high'],\n structuredOutput: true,\n nativeStructuredOutput: true,\n vision: true,\n audioInput: false,\n sampling: 'tunable',\n caching: { explicit: false, minTokens: 0 },\n grounding: true,\n functionCalling: true,\n serviceTiers: ['priority'],\n },\n configSchema: Grok45ConfigSchema,\n configJsonSchema: toConfigJsonSchema(Grok45ConfigSchema),\n validateConfig: zodToStandardSchema(Grok45ConfigSchema),\n}\n\nexport const grok46ModelDescriptor: ModelDescriptor = {\n model: 'grok-4.6',\n provider: 'xai',\n pricingFamily: 'grok-4.6',\n capabilities: {\n reasoning: true,\n reasoningApi: 'level',\n admittedReasoningEfforts: ['low', 'medium', 'high', 'xhigh'],\n structuredOutput: true,\n nativeStructuredOutput: true,\n vision: true,\n audioInput: false,\n sampling: 'tunable',\n caching: { explicit: false, minTokens: 0 },\n grounding: true,\n structuredOutputWithTools: true,\n functionCalling: true,\n serviceTiers: ['priority'],\n },\n configSchema: Grok46ConfigSchema,\n configJsonSchema: toConfigJsonSchema(Grok46ConfigSchema),\n validateConfig: zodToStandardSchema(Grok46ConfigSchema),\n}\n\nexport const grok47ModelDescriptor: ModelDescriptor = {\n model: 'grok-4.7',\n provider: 'xai',\n pricingFamily: 'grok-4.7',\n capabilities: {\n reasoning: true,\n reasoningApi: 'level',\n admittedReasoningEfforts: ['low', 'medium', 'high', 'xhigh'],\n structuredOutput: true,\n nativeStructuredOutput: true,\n vision: true,\n audioInput: false,\n sampling: 'tunable',\n caching: { explicit: false, minTokens: 0 },\n grounding: true,\n functionCalling: true,\n statelessReasoningReplay: true,\n serviceTiers: ['priority'],\n },\n configSchema: Grok47ConfigSchema,\n configJsonSchema: toConfigJsonSchema(Grok47ConfigSchema),\n validateConfig: zodToStandardSchema(Grok47ConfigSchema),\n}\n\n/** Every model descriptor `@gullabs/xai` contributes. */\nexport const xaiModelDescriptors: ModelDescriptor[] = [\n grok45ModelDescriptor,\n grok46ModelDescriptor,\n grok47ModelDescriptor,\n]\n\nexport const xaiRegistry: ModelRegistry = createModelRegistry(xaiModelDescriptors)\n","/**\n * xAI pricing snapshot + cost computation for @gullabs/xai.\n *\n * All rates are in **micro-USD per million tokens** (µUSD/M), matching\n * `@gullabs/core`'s `ModelRates` convention exactly: `cost_µUSD = N *\n * ratePerM / 1_000_000`.\n *\n * Token arithmetic goes through core's `computeCost`. The xAI lookup resolves\n * the concrete per-tier rates (including the `priority` multiplier) before\n * that call, so core never sees an xAI tier name. Tool lanes stay here:\n * `computeCost` prices tokens only. `PricingSource` is provider-scoped by\n * contract (see `packages/core/src/ports.ts`).\n *\n * **Long-context tier.** grok-4.5 / grok-4.6 / grok-4.7 charge a premium when the GROSS\n * input token count is at or above 200,000. xAI's current pricing page\n * (https://docs.x.ai/developers/pricing) explicitly labels the band\n * \"Long context ≥ 200k tokens\"; the live listing returns 200000. Selected by\n * `inputTokens` (incl. cached), not by billable input. Core's selector is\n * strictly greater than 200,000; this module owns the `>=` predicate.\n *\n * **Service tiers.** grok-4.5, grok-4.6, and grok-4.7 admit `'priority'` at 2×\n * on every token type, cached included. The 4.5 tier was live-verified\n * 2026-09-25; the 4.6 tier is pinned by fixture 12. `'fast'` is an alias and\n * is not admitted. `'default'` (the value\n * xAI echoes when no priority is served) and `undefined` (no tier requested)\n * price at the standard list. Any other defined tier is unpriced\n * (reject-don't-map).\n *\n * **Conversion factor.** xAI's `/v1/models` raw `*_token_price` fields are\n * in hundred-thousandths of a dollar per token — cents per 100M tokens\n * (divide the raw integer by 10,000 to get USD per million tokens): e.g.\n * `grok-4.6`'s raw `prompt_text_token_price: 20000` ÷ 10,000 = $2.00/M.\n *\n * Grok 4.5/4.6 rates were verified against `/v1/models` on 2026-08-12.\n * Grok 4.7 rates are published in xAI's 2026-09-21 release notes:\n * https://docs.x.ai/developers/release-notes. Prior snapshot\n * `xai-2026-07-09` priced grok-4.5 cached input at $0.50 / $1.00; the live\n * listing now reports $0.30 / $0.60.\n *\n * @module\n */\n\nimport { computeCost } from '@gullabs/core'\nimport type { Cost, CostRatesLookup, PricingSource, Usage } from '@gullabs/core'\n\n/** Identifies this pricing snapshot — bump the date when rates change. */\nexport const xaiPricingVersion = 'xai-2026-09-25' as const\n\n/**\n * Tool rates in µUSD per unit.\n *\n * - `web_search_calls`: $5 / 1,000 calls (per invocation).\n * - `x_posts_fetched`: $5 / 1,000 posts (per item, since 2026-09-21).\n * - `x_users_fetched`: $10 / 1,000 profiles (per item, since 2026-09-21).\n *\n * The per-call `x_search_calls` rate is gone. Attachment search stays\n * unpriced until a live probe pins the counter name (P-X2); a file-ref call\n * is estimated, not billed at an invented counter.\n */\nexport const XAI_TOOL_RATE_MICRO_USD = {\n web_search_calls: 5_000,\n x_posts_fetched: 5_000,\n x_users_fetched: 10_000,\n} as const\n\nconst XAI_TOOL_COUNTER_KEYS = [\n 'web_search_calls',\n 'x_posts_fetched',\n 'x_users_fetched',\n] as const\n\n/** Counters needed for a computed x_search tool fee. */\nexport const X_SEARCH_ITEM_COUNTERS = ['x_posts_fetched', 'x_users_fetched'] as const\n\nconst LONG_CONTEXT_THRESHOLD = 200_000\n\n/**\n * Per-model rate entry (all values in µUSD per million tokens).\n *\n * `gt200k` (when present) applies when GROSS input tokens >= 200,000.\n */\nexport interface XaiModelRates {\n /** µUSD per million input tokens (billable = gross − cached). */\n inputPerM: number\n /** µUSD per million cache-read tokens. */\n cachedPerM: number\n /** µUSD per million output tokens (reasoning tokens are folded in). */\n outputPerM: number\n /** Optional high-tier rates for long-context (GROSS input >= 200_000). */\n gt200k?: {\n inputPerM: number\n cachedPerM: number\n outputPerM: number\n }\n /**\n * Multiplier for Responses `service_tier: \"priority\"`. Absent = this\n * model does not admit priority (unpriced). Uncached standard-list 2×\n * is confirmed by fixture `12-grok-4-6-xhigh-priority.json` ticks;\n * cached and `gt200k` legs follow the official 2×-after-cache-discount\n * docs rule (that fixture has cached=0 and input < 200k).\n */\n priorityFactor?: number\n}\n\n/**\n * Frozen xAI pricing snapshot (per-1M in µUSD).\n *\n * Keys are EXACT canonical model identifiers — no prefix or alias matching.\n * xAI aliases (e.g. `grok-4.5-latest`, `grok-build-latest`) are deliberately\n * NOT registered/priced (reject-don't-map): callers must use the canonical\n * id; anything else resolves to the unpriced path.\n */\nexport const XAI_PRICING: Readonly<Record<string, XaiModelRates>> = Object.freeze({\n // ── grok-4.5 ── $2.00/$6.00 (<200k), $4.00/$12.00 (>=200k); cached $0.30/$0.60\n 'grok-4.5': {\n inputPerM: 2_000_000,\n cachedPerM: 300_000,\n outputPerM: 6_000_000,\n gt200k: {\n inputPerM: 4_000_000,\n cachedPerM: 600_000,\n outputPerM: 12_000_000,\n },\n priorityFactor: 2,\n },\n // ── grok-4.6 ── $2.00/$6.00 (<200k), $4.00/$12.00 (>=200k); cached $0.50/$1.00\n 'grok-4.6': {\n inputPerM: 2_000_000,\n cachedPerM: 500_000,\n outputPerM: 6_000_000,\n gt200k: {\n inputPerM: 4_000_000,\n cachedPerM: 1_000_000,\n outputPerM: 12_000_000,\n },\n // Confirmed 2026-08-12 by fixture 12 cost_in_usd_ticks (2× list).\n priorityFactor: 2,\n },\n // ── grok-4.7 ── $2.00/$0.50/$6.00 (<200k), $4.00/$1.00/$12.00 (≥200k); priority 2×\n 'grok-4.7': {\n inputPerM: 2_000_000,\n cachedPerM: 500_000,\n outputPerM: 6_000_000,\n gt200k: {\n inputPerM: 4_000_000,\n cachedPerM: 1_000_000,\n outputPerM: 12_000_000,\n },\n priorityFactor: 2,\n },\n})\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Look up rates for a model — EXACT match only.\n *\n * Deliberately no prefix matching: xAI aliases\n * such as `grok-4.5-latest` would otherwise prefix-match `grok-4.5` and\n * silently reintroduce the alias behavior the model registry rejects. An id\n * that is not an exact `XAI_PRICING` key is unpriced.\n */\nfunction lookupRates(model: string): XaiModelRates | undefined {\n return Object.hasOwn(XAI_PRICING, model) ? XAI_PRICING[model] : undefined\n}\n\n/**\n * Resolve concrete token rates for `(model, tier)`.\n *\n * `undefined` and `'default'` are the standard list. `'priority'` returns\n * those rates scaled by `priorityFactor` when the model admits it. Any other\n * defined tier, or `'priority'` on a model without `priorityFactor`, is\n * unpriced (reject-don't-map) — the lookup returns `undefined` and\n * `computeCost` records the unpriced cost.\n */\nconst lookupConcreteRates: CostRatesLookup = (model, tier) => {\n const rates = lookupRates(model)\n if (rates === undefined) return undefined\n if (tier === undefined || tier === 'default') return rates\n if (tier === 'priority' && rates.priorityFactor !== undefined) {\n return scaleRates(rates, rates.priorityFactor)\n }\n return undefined\n}\n\n/**\n * Select base vs long-context rates. xAI's threshold is inclusive: 200,000\n * gross input tokens already pays the long-context list.\n */\nexport function selectXaiRates(\n rates: XaiModelRates,\n grossInputTokens: number,\n): { inputPerM: number; cachedPerM: number; outputPerM: number } {\n if (rates.gt200k !== undefined && grossInputTokens >= LONG_CONTEXT_THRESHOLD) {\n return rates.gt200k\n }\n return {\n inputPerM: rates.inputPerM,\n cachedPerM: rates.cachedPerM,\n outputPerM: rates.outputPerM,\n }\n}\n\nfunction scaleRates(rates: XaiModelRates, factor: number): XaiModelRates {\n const scaled: XaiModelRates = {\n inputPerM: rates.inputPerM * factor,\n cachedPerM: rates.cachedPerM * factor,\n outputPerM: rates.outputPerM * factor,\n }\n if (rates.gt200k !== undefined) {\n scaled.gt200k = {\n inputPerM: rates.gt200k.inputPerM * factor,\n cachedPerM: rates.gt200k.cachedPerM * factor,\n outputPerM: rates.gt200k.outputPerM * factor,\n }\n }\n return scaled\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the cost of an xAI LLM call given a model name and usage data.\n *\n * Pure function — no side effects, always returns a well-formed {@link Cost}.\n *\n * **Algorithm:**\n * 1. `lookupConcreteRates` resolves the model and tier. `undefined` or\n * `'default'` is the standard list. `'priority'` returns rates scaled by\n * `priorityFactor` when the model admits it. An unknown model, any other\n * defined tier, or `'priority'` on a model without `priorityFactor` is\n * unpriced (reject-don't-map) — `computeCost` returns `microUsd: null`.\n * 2. `selectXaiRates` applies long-context rates when GROSS input is\n * `>= 200_000` (xAI's inclusive threshold; core's selector stays `>`).\n * 4. Billable input = `inputTokens − (cachedInputTokens ?? 0)`, clamped to 0.\n * 5. Round each component (input, cached, output) independently to the\n * nearest integer micro-USD.\n * 6. `microUsd` is the sum of the four components — guarantees\n * `details.input + details.cached + details.output + details.tools === microUsd`.\n * 7. Tool lanes: `web_search_calls` per call; x_search is\n * `x_posts_fetched` × $5/1k + `x_users_fetched` × $10/1k. A missing\n * item counter leaves the call unpriced; the provider's billed ticks remain\n * in `usage.details` for reconciliation outside this rate snapshot.\n * File-ref still sets `attachment_search_unpinned` and the call is\n * estimated — the counter name is not pinned (P-X2).\n */\nexport function computeXaiCost(model: string, usage: Usage, tier?: string): Cost {\n const listed = lookupConcreteRates(model, tier)\n if (listed === undefined) {\n return computeCost(model, usage, tier, lookupConcreteRates, xaiPricingVersion)\n }\n const band = selectXaiRates(listed, usage.inputTokens)\n const bandLookup: CostRatesLookup = () => ({\n inputPerM: band.inputPerM,\n cachedPerM: band.cachedPerM,\n outputPerM: band.outputPerM,\n })\n const tokenCost = computeCost(model, usage, undefined, bandLookup, xaiPricingVersion)\n\n const inputCost = tokenCost.details.input\n const cachedCost = tokenCost.details.cached\n const outputCost = tokenCost.details.output\n\n const serverToolsRequested = usage.details['server_tools_requested'] === 1\n const xSearchRequested = usage.details['x_search_requested'] === 1\n const missingXSearchCounter =\n xSearchRequested &&\n X_SEARCH_ITEM_COUNTERS.some((key) => typeof usage.details[key] !== 'number')\n if (missingXSearchCounter || usage.details['server_tools_missing'] === 1) {\n // A live billed total is retained on Usage for reconciliation. It is not\n // a cost derived from this frozen rate snapshot, so do not put it in Cost.\n return {\n microUsd: null,\n usd: null,\n pricingVersion: xaiPricingVersion,\n confidence: 'estimated',\n details: { input: 0, cached: 0, output: 0, tools: 0 },\n unpricedReason: missingXSearchCounter\n ? 'x_search usage is missing x_posts_fetched or x_users_fetched; refusing to bill a per-call estimate.'\n : 'Server tool usage is missing a required counter; refusing to guess a tool cost.',\n }\n }\n\n const attachmentUnpinned = usage.details['attachment_search_unpinned'] === 1\n const missingWebCounter =\n serverToolsRequested &&\n !xSearchRequested &&\n !attachmentUnpinned &&\n !XAI_TOOL_COUNTER_KEYS.some((key) => key in usage.details)\n\n const toolsCost = missingWebCounter\n ? 0\n : XAI_TOOL_COUNTER_KEYS.reduce((sum, key) => {\n const count = usage.details[key]\n if (typeof count !== 'number' || count <= 0) return sum\n return sum + Math.round(count * XAI_TOOL_RATE_MICRO_USD[key])\n }, 0)\n\n const microUsd = inputCost + cachedCost + outputCost + toolsCost\n\n return {\n microUsd,\n usd: microUsd / 1_000_000,\n pricingVersion: xaiPricingVersion,\n confidence: missingWebCounter || attachmentUnpinned ? 'estimated' : 'exact',\n details: {\n input: inputCost,\n cached: cachedCost,\n output: outputCost,\n tools: toolsCost,\n },\n }\n}\n\n/**\n * Factory that returns the **xai-scoped** {@link PricingSource} port\n * implementation backed by {@link XAI_PRICING}.\n *\n * @example\n * ```ts\n * import { xaiPricingSource } from '@gullabs/xai'\n *\n * const pricing = xaiPricingSource()\n * const cost = pricing.price('grok-4.6', usage)\n * ```\n */\nexport function xaiPricingSource(): PricingSource {\n return {\n version: xaiPricingVersion,\n price(model: string, usage: Usage, tier?: string): Cost {\n return computeXaiCost(model, usage, tier)\n },\n hasModel(model: string): boolean {\n return lookupRates(model) !== undefined\n },\n listModels(): readonly string[] {\n return Object.keys(XAI_PRICING)\n },\n }\n}\n","/**\n * xaiAdapter — @gullabs/xai xAI Grok provider adapter.\n *\n * Pure request⇄response mapping over the xAI Responses API (via\n * XaiClientLike). Never persists, never computes cost, never loops.\n *\n * @module\n */\n\nimport { LlmError, classifyError, assertNever } from '@gullabs/core'\nimport type {\n ProviderAdapter,\n ResolvedRequest,\n AdapterCtx,\n AdapterResult,\n Usage,\n Warning,\n FinishReason,\n JsonValue,\n AuthMaterial,\n Part,\n Citation,\n TokenCountRequest,\n TokenCount,\n} from '@gullabs/core'\nimport { buildXaiClient, requireApiKey } from './client.js'\nimport { xaiRegistry } from './models.js'\nimport { X_SEARCH_ITEM_COUNTERS } from './pricing.js'\nimport type {\n XaiClientLike,\n XaiResponseCreateParams,\n XaiInputContentPart,\n XaiRequestInputItem,\n XaiResponseShape,\n XaiUsageShape,\n XaiMessageOutputItem,\n XaiReasoningOutputItem,\n XaiReplayState,\n} from './client.js'\n\n// ---------------------------------------------------------------------------\n// Small object-shape helpers (mirrors google adapter's local helpers)\n// ---------------------------------------------------------------------------\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isXaiMessageItem(\n item: XaiResponseShape['output'][number],\n): item is XaiMessageOutputItem {\n return item.type === 'message' && Array.isArray((item as XaiMessageOutputItem).content)\n}\n\nfunction isXaiReasoningItem(\n item: XaiResponseShape['output'][number],\n): item is XaiReasoningOutputItem {\n return (\n item.type === 'reasoning' && Array.isArray((item as { summary?: unknown }).summary)\n )\n}\n\nfunction badXaiRequest(message: string): LlmError {\n return new LlmError(message, { kind: 'bad_request', retryable: false })\n}\n\n// ---------------------------------------------------------------------------\n// Vision / media mapping\n// ---------------------------------------------------------------------------\n\nconst ALLOWED_XAI_IMAGE_MIME_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png'])\n\n/** 20 MiB, xAI's documented inline-image size ceiling. */\nconst MAX_XAI_INLINE_IMAGE_BYTES = 20 * 1024 * 1024\n\n/**\n * Map a single {@link Part} to its xAI Responses API input-content-part\n * equivalent.\n *\n * - `text` → `{ type: 'input_text', text }`\n * - `inline-media` → `{ type: 'input_image', image_url: 'data:<mime>;base64,<data>' }`;\n * rejected (`bad_request`) when `mimeType` is not jpg/jpeg/png, or when the\n * decoded payload exceeds 20 MiB.\n * - `file-uri` → `{ type: 'input_image', image_url: uri }` ONLY when\n * `uri` is a public `http(s)://` URL AND `mimeType` is an allowed image\n * type — a provider-hosted URI from another provider (e.g. Gemini's Files\n * API `https://generativelanguage.googleapis.com/...` — which itself\n * happens to be `https://`, but is not dereferenceable by xAI) is not\n * portable and callers should not reuse `FileUriPart` cross-provider.\n * - `file-ref` → `{ type: 'input_file', file_id }` for xAI Files uploads.\n * Attaching files implicitly enables xAI's `attachment_search` agentic tool\n * (extra tool billing may apply). Empty `fileId` → `bad_request`.\n *\n * Note: xAI enforces an undocumented server-side minimum image size\n * (observed ~8px/side, ~512 total px). This adapter does not pre-validate\n * pixel dimensions — a too-small image surfaces as a `bad_request` from the\n * live API, classified normally by {@link classifyXaiError}.\n */\nfunction mapPart(p: Part): XaiInputContentPart {\n switch (p.kind) {\n case 'text':\n return { type: 'input_text', text: p.text }\n\n case 'inline-media': {\n if (!ALLOWED_XAI_IMAGE_MIME_TYPES.has(p.mimeType)) {\n throw badXaiRequest(\n `xAI vision only supports image/jpeg and image/png; got mimeType \"${p.mimeType}\".`,\n )\n }\n const byteLength = Buffer.from(p.data, 'base64').length\n if (byteLength > MAX_XAI_INLINE_IMAGE_BYTES) {\n throw badXaiRequest(\n `xAI inline images must be at most 20 MiB; got ${byteLength} bytes.`,\n )\n }\n return { type: 'input_image', image_url: `data:${p.mimeType};base64,${p.data}` }\n }\n\n case 'file-uri': {\n const isPublicHttpUrl = p.uri.startsWith('http://') || p.uri.startsWith('https://')\n const isAllowedImageType = ALLOWED_XAI_IMAGE_MIME_TYPES.has(p.mimeType)\n if (!isPublicHttpUrl || !isAllowedImageType) {\n throw badXaiRequest(\n `xAI only accepts public http(s) image URLs via FileUriPart; got scheme of \"${p.uri}\" / mimeType \"${p.mimeType}\".`,\n )\n }\n // Reject known foreign provider hosts even when scheme+mime look valid.\n if (\n p.uri.includes('generativelanguage.googleapis.com') ||\n p.uri.includes('googleapis.com/v1beta/files')\n ) {\n throw badXaiRequest(\n `xAI cannot dereference Gemini/Google Files URIs via FileUriPart; upload to xAI Files and use FileRefPart (file_id) instead. Got \"${p.uri}\".`,\n )\n }\n return { type: 'input_image', image_url: p.uri }\n }\n\n case 'file-ref': {\n if (typeof p.fileId !== 'string' || p.fileId.trim() === '') {\n throw badXaiRequest('FileRefPart.fileId must be a non-empty string.')\n }\n return { type: 'input_file', file_id: p.fileId }\n }\n\n case 'tool-call':\n case 'tool-result':\n throw badXaiRequest(\n `xAI mapPart does not emit ${p.kind} as a content part; the request mapper handles replay items.`,\n )\n\n default:\n return assertNever(p)\n }\n}\n\n// ---------------------------------------------------------------------------\n// providerOptions.xai → explicit allowlisted mapping\n// ---------------------------------------------------------------------------\n\nconst XAI_PROVIDER_OPTION_KEYS = new Set(['promptCacheKey', 'tools', 'parallelToolCalls'])\n\ntype MappedXaiProviderOptions = {\n promptCacheKey?: string\n tools?: Array<Record<string, unknown>>\n parallelToolCalls?: boolean\n}\n\nfunction mapXaiProviderOptions(\n xaiOpts: unknown,\n model: string,\n): MappedXaiProviderOptions {\n if (xaiOpts === undefined) {\n return {}\n }\n\n if (!isPlainRecord(xaiOpts)) {\n throw badXaiRequest(`providerOptions.xai must be an object for model \"${model}\".`)\n }\n\n const unknownKeys = Object.keys(xaiOpts).filter(\n (key) => !XAI_PROVIDER_OPTION_KEYS.has(key),\n )\n if (unknownKeys.length > 0) {\n throw badXaiRequest(\n `providerOptions.xai contains unsupported keys [${unknownKeys.join(\n ', ',\n )}] for model \"${model}\". Allowed keys: promptCacheKey, tools, parallelToolCalls.`,\n )\n }\n\n const mapped: MappedXaiProviderOptions = {}\n if (xaiOpts['promptCacheKey'] !== undefined) {\n if (\n typeof xaiOpts['promptCacheKey'] !== 'string' ||\n xaiOpts['promptCacheKey'].length === 0\n ) {\n throw badXaiRequest(\n `providerOptions.xai.promptCacheKey must be a non-empty string for model \"${model}\".`,\n )\n }\n mapped.promptCacheKey = xaiOpts['promptCacheKey']\n }\n\n if (xaiOpts['tools'] !== undefined) {\n mapped.tools = mapXaiSearchTools(xaiOpts['tools'], model)\n }\n\n if (xaiOpts['parallelToolCalls'] !== undefined) {\n if (typeof xaiOpts['parallelToolCalls'] !== 'boolean') {\n throw badXaiRequest(\n `providerOptions.xai.parallelToolCalls must be a boolean for model \"${model}\".`,\n )\n }\n mapped.parallelToolCalls = xaiOpts['parallelToolCalls']\n }\n\n return mapped\n}\n\nfunction parseXaiReplayState(value: unknown, model: string): XaiReplayState | undefined {\n if (value === undefined) return undefined\n if (\n !isPlainRecord(value) ||\n value['model'] !== model ||\n !Array.isArray(value['input']) ||\n value['input'].length === 0 ||\n value['input'].some(\n (item) =>\n !isPlainRecord(item) ||\n (typeof item['type'] !== 'string' && typeof item['role'] !== 'string'),\n )\n ) {\n throw badXaiRequest(\n `transientProviderState must contain the full xAI wire input for model \"${model}\".`,\n )\n }\n return value as unknown as XaiReplayState\n}\n\nfunction mapXaiSearchTools(\n tools: unknown,\n model: string,\n): Array<Record<string, unknown>> {\n if (!Array.isArray(tools)) {\n throw badXaiRequest(\n `providerOptions.xai.tools must be an array for model \"${model}\".`,\n )\n }\n return tools.map((tool, index) => {\n if (!isPlainRecord(tool) || typeof tool['type'] !== 'string') {\n throw badXaiRequest(\n `providerOptions.xai.tools[${index}] must be an object with a type for model \"${model}\".`,\n )\n }\n if (tool['type'] === 'web_search') {\n const wire: Record<string, unknown> = { type: 'web_search' }\n if (tool['allowedDomains'] !== undefined)\n wire['allowed_domains'] = tool['allowedDomains']\n if (tool['excludedDomains'] !== undefined) {\n wire['excluded_domains'] = tool['excludedDomains']\n }\n if (tool['enableImageUnderstanding'] !== undefined) {\n wire['enable_image_understanding'] = tool['enableImageUnderstanding']\n }\n if (tool['enableImageSearch'] !== undefined) {\n wire['enable_image_search'] = tool['enableImageSearch']\n }\n return wire\n }\n if (tool['type'] === 'x_search') {\n const wire: Record<string, unknown> = { type: 'x_search' }\n if (tool['allowedXHandles'] !== undefined) {\n wire['allowed_x_handles'] = tool['allowedXHandles']\n }\n if (tool['excludedXHandles'] !== undefined) {\n wire['excluded_x_handles'] = tool['excludedXHandles']\n }\n if (tool['fromDate'] !== undefined) wire['from_date'] = tool['fromDate']\n if (tool['toDate'] !== undefined) wire['to_date'] = tool['toDate']\n if (tool['enableImageUnderstanding'] !== undefined) {\n wire['enable_image_understanding'] = tool['enableImageUnderstanding']\n }\n if (tool['enableVideoUnderstanding'] !== undefined) {\n wire['enable_video_understanding'] = tool['enableVideoUnderstanding']\n }\n return wire\n }\n throw badXaiRequest(\n `providerOptions.xai.tools[${index}].type \"${String(tool['type'])}\" is not supported for model \"${model}\".`,\n )\n })\n}\n\n// ---------------------------------------------------------------------------\n// FinishReason mapping (xAI status/incomplete_details → our FinishReason)\n// ---------------------------------------------------------------------------\n\nfunction mapFinishReason(response: XaiResponseShape): FinishReason {\n if (response.status === 'completed') {\n return 'stop'\n }\n if (\n response.status === 'incomplete' &&\n response.incomplete_details?.reason === 'max_output_tokens'\n ) {\n return 'length'\n }\n // Any other status/incomplete_details combination without fixture\n // evidence (or a status we don't recognize) maps to 'other' — the core\n // FinishReason union is closed to these four values.\n return 'other'\n}\n\n// ---------------------------------------------------------------------------\n// Usage mapping — #1 correctness rule\n// ---------------------------------------------------------------------------\n\n/**\n * Usage fields already mapped into canonical {@link Usage} counters — never\n * duplicated into `details` under their raw xAI names.\n */\nconst CANONICALLY_MAPPED_USAGE_KEYS = new Set([\n 'input_tokens',\n 'output_tokens',\n 'total_tokens',\n])\n\n/**\n * Map xAI's `usage` object to our {@link Usage} type.\n *\n * **GROSS convention (ADR-004):**\n * - `usage.input_tokens` is already GROSS (includes cached) → `inputTokens`.\n * - `usage.output_tokens` is already GROSS (includes reasoning) → `outputTokens`.\n * Unlike Gemini, xAI does not require us to sum sub-fields into the gross\n * total — the top-level fields are already gross.\n *\n * **xAI extras** (captured under raw names; not token-priced): every additional\n * NUMERIC top-level usage field (`num_sources_used`,\n * `num_server_side_tools_used` — e.g. after implicit `attachment_search` when\n * files are attached — `cost_in_usd_ticks`, and anything xAI adds later) is\n * surfaced into `details` under its raw name for host visibility. Non-numeric\n * extras (e.g. `context_details`) belong to `AdapterResult.providerMetadata`\n * (see the adapter) and the full raw payload always lands in `Usage.raw`\n * verbatim. Tool invocation fees are billed in `Cost.details.tools` from the\n * live-pinned counters (`web_search_calls`, `x_posts_fetched`, `x_users_fetched`).\n */\nfunction mapUsage(usage: XaiUsageShape): Usage {\n const inputTokens = usage.input_tokens\n const outputTokens = usage.output_tokens\n const cachedInputTokens = usage.input_tokens_details?.cached_tokens\n const thinkingTokens = usage.output_tokens_details?.reasoning_tokens\n const totalTokens = usage.total_tokens\n\n // Canonical details keys: input, output, cached, thinking.\n const details: Record<string, number> = {\n input: inputTokens,\n output: outputTokens,\n ...(cachedInputTokens !== undefined ? { cached: cachedInputTokens } : {}),\n ...(thinkingTokens !== undefined ? { thinking: thinkingTokens } : {}),\n }\n\n // Numeric xAI extras — surfaced under their raw names.\n for (const [key, value] of Object.entries(usage)) {\n if (typeof value === 'number' && !CANONICALLY_MAPPED_USAGE_KEYS.has(key)) {\n details[key] = value\n }\n }\n\n // The 2026-08-24 capture located per-call counters in the nested\n // `server_side_tool_usage_details` object. xAI's 2026-09-22 X Search docs\n // added the per-item `x_posts_fetched` and `x_users_fetched` names there.\n // Flatten numeric members under their raw names for provider pricing.\n const toolUsage = usage['server_side_tool_usage_details']\n if (isPlainRecord(toolUsage)) {\n for (const [key, value] of Object.entries(toolUsage)) {\n if (typeof value === 'number') {\n details[key] = value\n }\n }\n }\n\n const raw: JsonValue = usage as unknown as { [k: string]: JsonValue }\n\n const result: Usage = {\n inputTokens,\n outputTokens,\n details,\n raw,\n ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),\n ...(thinkingTokens !== undefined ? { thinkingTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n }\n\n return result\n}\n\n// ---------------------------------------------------------------------------\n// Error classification\n// ---------------------------------------------------------------------------\n\n/**\n * Structured-body auth-failure signature, taken verbatim from the recorded\n * live error taxonomy (`__fixtures__/09-error-taxonomy.json`,\n * `invalid_api_key` case): HTTP 400 with body\n * `{ code: 'invalid-argument', error: 'Incorrect API key provided. …' }`.\n *\n * The body `code` (`'invalid-argument'`) is NOT discriminating — xAI uses it\n * for genuinely bad requests too (e.g. `Model not found: grok-99`) — and the\n * `openai` SDK's `APIError` drops it (it hoists only the body's `error`\n * field onto `.error`). The exact message PREFIX xAI emits for bad keys is\n * therefore the signature.\n */\nconst XAI_AUTH_ERROR_MESSAGE_PREFIX = 'Incorrect API key provided'\n\n/**\n * Extract the STRUCTURED error-body text from a raw thrown value.\n *\n * Consulted shapes (both are parsed-body fields, never free-form\n * `Error.message` text):\n * - `rawErr.error` as a string — the `openai` SDK's `APIError` hoists the\n * response body's `error` field onto `.error`, which for xAI's\n * `{ code, error }` bodies is the message string itself.\n * - `rawErr.error` as an object — the full parsed body (test fakes and\n * hand-rolled throws of the fixture shape `{ status, error: <body> }`);\n * its `error` (xAI) or `message` (OpenAI-style) string field is read.\n *\n * Free-form `Error.message` is deliberately ignored so arbitrary request\n * content echoed into a message (e.g. a schema-validation error quoting user\n * text that mentions \"api key\") can never influence classification.\n */\nfunction extractXaiErrorBodyText(rawErr: unknown): string | undefined {\n if (rawErr === null || typeof rawErr !== 'object') {\n return undefined\n }\n const body = (rawErr as Record<string, unknown>)['error']\n if (typeof body === 'string') {\n return body\n }\n if (isPlainRecord(body)) {\n if (typeof body['error'] === 'string') {\n return body['error']\n }\n if (typeof body['message'] === 'string') {\n return body['message']\n }\n }\n return undefined\n}\n\n/** True iff the structured body matches xAI's recorded bad-API-key signature. */\nfunction isXaiAuthFailureBody(rawErr: unknown): boolean {\n const text = extractXaiErrorBodyText(rawErr)\n return text !== undefined && text.startsWith(XAI_AUTH_ERROR_MESSAGE_PREFIX)\n}\n\n/**\n * Structured-body safety-check signature, taken from the live 2026-08-14\n * capture (`__fixtures__/15-safety-check-403.json`): HTTP 403 with\n * `err.error` as the plain string\n * `\"Content violates usage guidelines. Failed check: SAFETY_CHECK_TYPE_CYBER\"`.\n *\n * Match the PREFIX only — `SAFETY_CHECK_TYPE_*` suffixes vary. Free-form\n * `Error.message` is never scanned (same anti-echo rule as the auth overlay).\n */\nconst XAI_SAFETY_CHECK_MESSAGE_PREFIX = 'Content violates usage guidelines'\n\n/** True iff the structured body matches xAI's recorded safety-check signature. */\nfunction isXaiSafetyCheckBody(rawErr: unknown): boolean {\n const text = extractXaiErrorBodyText(rawErr)\n return text !== undefined && text.startsWith(XAI_SAFETY_CHECK_MESSAGE_PREFIX)\n}\n\n/**\n * Message/errno signatures of a transport-level failure: the request never\n * reached xAI's servers (or the connection was severed mid-flight), so there\n * is no HTTP response for {@link classifyHttpStatus} to route by status.\n * Covers the `openai` SDK's own default message (`\"Connection error.\"`,\n * thrown by `APIConnectionError`) plus the Node/undici errno codes that\n * surface when the underlying `fetch` rejects before a response arrives.\n */\nconst XAI_TRANSPORT_ERROR_PATTERN =\n /connection error|econnreset|econnrefused|etimedout|eai_again|epipe|socket hang up|fetch failed/i\n\n/** True iff `err.message` or `err.code` matches a known transport-failure signature. */\nfunction matchesXaiTransportSignature(err: unknown): boolean {\n if (!(err instanceof Error)) return false\n if (XAI_TRANSPORT_ERROR_PATTERN.test(err.message)) return true\n const code = (err as { code?: unknown }).code\n return typeof code === 'string' && XAI_TRANSPORT_ERROR_PATTERN.test(code)\n}\n\n/**\n * True iff `rawErr` is (or wraps) a transport-level connection failure —\n * observed live killing Temporal-orchestrated host runs when the `openai`\n * SDK's `APIConnectionError` (\"Connection error.\") fell through\n * `classifyError`'s generic HTTP-status classification to `kind: 'unknown',\n * retryable: false`.\n *\n * Detection order:\n * 1. `rawErr.constructor.name` matches the `openai` SDK's\n * `APIConnectionError` / `APIConnectionTimeoutError` classes. Matched by\n * constructor name rather than `instanceof` so this file does not need a\n * runtime import of `openai` — per `client.ts`, that package is imported\n * ONLY in `buildXaiClient`, keeping unit tests independent of the real\n * SDK.\n * 2. `rawErr.message` / `rawErr.code` matches a known transport-failure\n * signature (handles the SDK's default message text directly, without\n * relying on the class name surviving minification).\n * 3. A wrapped `rawErr.cause` matches either of the above —\n * `APIConnectionError` attaches the underlying fetch/socket error as\n * `.cause`.\n */\nfunction isXaiTransportError(rawErr: unknown): boolean {\n if (!(rawErr instanceof Error)) return false\n\n const ctorName = rawErr.constructor.name\n if (ctorName === 'APIConnectionError' || ctorName === 'APIConnectionTimeoutError') {\n return true\n }\n\n if (matchesXaiTransportSignature(rawErr)) return true\n\n const cause = (rawErr as { cause?: unknown }).cause\n if (cause instanceof Error) {\n const causeCtorName = cause.constructor.name\n if (\n causeCtorName === 'APIConnectionError' ||\n causeCtorName === 'APIConnectionTimeoutError'\n ) {\n return true\n }\n if (matchesXaiTransportSignature(cause)) return true\n }\n\n return false\n}\n\n/**\n * Classify a raw error thrown from the xAI Responses API call into a typed\n * {@link LlmError}.\n *\n * HTTP status is a hint, not a kind. Overlays inspect the STRUCTURED parsed\n * body only — never free-form `Error.message` — so echoed user content cannot\n * change classification.\n *\n * 1. Already an {@link LlmError} → returned unchanged (including an untagged\n * one).\n * 2. HTTP 400 whose structured body starts with\n * `\"Incorrect API key provided\"` (fixture 09; prefix only — the SDK may\n * drop `code`) → `invalid_auth`.\n * 3. HTTP 403 whose structured body starts with\n * `\"Content violates usage guidelines\"` (fixture 15; `SAFETY_CHECK_TYPE_*`\n * suffixes vary) → `content_filter`. A bare 403 without that body stays\n * the core default, `invalid_auth`.\n * 4. `kind: 'unknown'` with a known transport-failure signature (see\n * {@link isXaiTransportError}) → `server`, retryable. A connection that\n * never reached xAI is not the caller's fault.\n * 5. Else rebuild the core classification tagged `provider: 'xai'`.\n */\nexport function classifyXaiError(rawErr: unknown): LlmError {\n if (rawErr instanceof LlmError) {\n return rawErr\n }\n\n const base = classifyError(rawErr)\n\n if (base.httpStatus === 400 && isXaiAuthFailureBody(rawErr)) {\n return new LlmError(base.message, {\n kind: 'invalid_auth',\n retryable: false,\n httpStatus: base.httpStatus,\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n }\n\n if (base.httpStatus === 403 && isXaiSafetyCheckBody(rawErr)) {\n const bodyText = extractXaiErrorBodyText(rawErr)\n return new LlmError(bodyText ?? base.message, {\n kind: 'content_filter',\n retryable: false,\n httpStatus: base.httpStatus,\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n }\n\n if (base.kind === 'unknown' && isXaiTransportError(rawErr)) {\n return new LlmError(base.message, {\n kind: 'server',\n retryable: true,\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n }\n\n return new LlmError(base.message, {\n kind: base.kind,\n retryable: base.retryable,\n ...(base.httpStatus !== undefined ? { httpStatus: base.httpStatus } : {}),\n ...(base.retryAfterMs !== undefined ? { retryAfterMs: base.retryAfterMs } : {}),\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n}\n\n// ---------------------------------------------------------------------------\n// Adapter options\n// ---------------------------------------------------------------------------\n\nexport interface XaiAdapterOptions {\n /**\n * Inject a pre-built client (real or fake).\n * When omitted, `buildXaiClient` is called with `ctx.auth` at call time,\n * inside the classified try/catch so any construction failure is wrapped\n * as a typed `LlmError`.\n */\n client?: XaiClientLike\n /**\n * @internal Testing-only.\n *\n * Override the default `buildXaiClient` factory. Allows unit tests to\n * simulate construction failures without importing the real `openai` SDK.\n * Never set this in production code. Mirrors `GeminiAdapterOptions._clientFactory`.\n */\n _clientFactory?: (auth: AuthMaterial) => XaiClientLike | Promise<XaiClientLike>\n /**\n * @internal Testing-only.\n *\n * Override `fetch` for `POST /v1/tokenize-text` (not on the openai SDK).\n */\n _fetch?: typeof fetch\n}\n\n// ---------------------------------------------------------------------------\n// xaiAdapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create an xAI Grok provider adapter (Responses API).\n *\n * @param opts.client - Optional pre-built client (e.g. for testing).\n */\nexport function xaiAdapter(opts?: XaiAdapterOptions): ProviderAdapter {\n return {\n id: 'xai',\n\n async run(req: ResolvedRequest, ctx: AdapterCtx): Promise<AdapterResult> {\n if (req.provider !== 'xai') {\n throw new LlmError(\n `xaiAdapter received a request for provider \"${req.provider}\", expected \"xai\".`,\n { kind: 'bad_request', retryable: false },\n )\n }\n\n const warnings: Warning[] = []\n const model = req.model\n if (\n req.modelDescriptor !== undefined &&\n (req.modelDescriptor.model !== model || req.modelDescriptor.provider !== 'xai')\n ) {\n throw badXaiRequest(`Mismatched xAI model descriptor for \"${model}\".`)\n }\n if (\n xaiRegistry.resolve('xai', model)?.capabilities?.statelessReasoningReplay ===\n true &&\n req.modelDescriptor?.capabilities?.statelessReasoningReplay !== true\n ) {\n throw badXaiRequest(\n `A matching xAI model descriptor with statelessReasoningReplay is required for \"${model}\".`,\n )\n }\n const genConfig = req.config\n const xaiProviderConfig = mapXaiProviderOptions(\n genConfig.providerOptions?.['xai'],\n model,\n )\n\n // ------------------------------------------------------------------\n // 1. Map messages → input\n // ------------------------------------------------------------------\n const replayRequired =\n req.modelDescriptor?.capabilities?.statelessReasoningReplay === true\n const replayState = parseXaiReplayState(req.transientProviderState, model)\n if (replayState !== undefined && !replayRequired) {\n throw badXaiRequest(\n `transientProviderState requires a statelessReasoningReplay model descriptor for \"${model}\".`,\n )\n }\n if (replayState !== undefined && req.messages.length === 0) {\n throw badXaiRequest(\n `Stateless conversation replay for model \"${model}\" requires new messages to append.`,\n )\n }\n const input: XaiRequestInputItem[] = [...(replayState?.input ?? [])]\n const replayCallIds = new Set(\n replayState?.input\n .filter((item) => isPlainRecord(item) && item['type'] === 'function_call')\n .map((item) => (isPlainRecord(item) ? item['call_id'] : undefined))\n .filter((id): id is string => typeof id === 'string') ?? [],\n )\n const replayedResultIds = new Set(\n replayState?.input\n .filter(\n (item) => isPlainRecord(item) && item['type'] === 'function_call_output',\n )\n .map((item) => (isPlainRecord(item) ? item['call_id'] : undefined))\n .filter((id): id is string => typeof id === 'string') ?? [],\n )\n for (const msg of req.messages) {\n if (replayState !== undefined && msg.role === 'assistant') {\n throw badXaiRequest(\n `New messages for model \"${model}\" cannot contain assistant history when transientProviderState is supplied.`,\n )\n }\n if (\n replayRequired &&\n replayState === undefined &&\n msg.parts.some(\n (part) => part.kind === 'tool-call' || part.kind === 'tool-result',\n )\n ) {\n throw badXaiRequest(\n `Function-call history for model \"${model}\" requires transientProviderState from the prior result.`,\n )\n }\n const contentParts: XaiInputContentPart[] = []\n for (const part of msg.parts) {\n if (part.kind === 'tool-call') {\n if (contentParts.length > 0) {\n input.push({\n role: msg.role === 'assistant' ? 'assistant' : 'user',\n content: contentParts.splice(0),\n })\n }\n input.push({\n type: 'function_call',\n call_id: part.toolCallId,\n name: part.toolName,\n arguments: JSON.stringify(part.args),\n })\n continue\n }\n if (part.kind === 'tool-result') {\n if (\n replayState !== undefined &&\n (!replayCallIds.has(part.toolCallId) ||\n replayedResultIds.has(part.toolCallId))\n ) {\n throw badXaiRequest(\n `Tool result \"${part.toolCallId}\" must match an unanswered function call in transientProviderState.`,\n )\n }\n replayedResultIds.add(part.toolCallId)\n if (contentParts.length > 0) {\n input.push({\n role: msg.role === 'assistant' ? 'assistant' : 'user',\n content: contentParts.splice(0),\n })\n }\n input.push({\n type: 'function_call_output',\n call_id: part.toolCallId,\n output: JSON.stringify(part.result),\n })\n continue\n }\n contentParts.push(mapPart(part))\n }\n if (contentParts.length > 0) {\n input.push({\n role: msg.role === 'assistant' ? 'assistant' : 'user',\n content: contentParts,\n })\n }\n }\n // ------------------------------------------------------------------\n // 2. Build request params\n // ------------------------------------------------------------------\n const params: XaiResponseCreateParams = {\n model,\n input,\n store: false,\n }\n\n if (req.system !== undefined) {\n params.instructions = req.system\n }\n\n // Sampling — forwarded verbatim, no clamping (schema enforces bounds\n // upstream of the adapter).\n if (genConfig.temperature !== undefined) {\n params.temperature = genConfig.temperature\n }\n if (genConfig.topP !== undefined) {\n params.top_p = genConfig.topP\n }\n\n // max_output_tokens — no artificial ceiling; truncation surfaces as\n // finishReason:'length', not an error (see mapFinishReason).\n if (genConfig.maxOutputTokens !== undefined) {\n params.max_output_tokens = genConfig.maxOutputTokens\n }\n\n // serviceTier — descriptor-driven. All three registered models admit\n // priority (4.5 live-verified 2026-09-25; 4.6 on 2026-08-12).\n // xAI silently remaps flex to default, so the strict schemas reject it.\n const admittedTiers = req.modelDescriptor?.capabilities?.serviceTiers\n if (genConfig.serviceTier !== undefined) {\n if (\n admittedTiers === undefined ||\n !admittedTiers.includes(genConfig.serviceTier)\n ) {\n throw badXaiRequest(\n `serviceTier is not supported for xai model \"${model}\" (got \"${genConfig.serviceTier}\").`,\n )\n }\n if (genConfig.serviceTier !== 'priority') {\n throw badXaiRequest(\n `serviceTier \"${genConfig.serviceTier}\" is not supported for xai model \"${model}\" (only \"priority\" is admitted).`,\n )\n }\n params.service_tier = 'priority'\n }\n\n // ------------------------------------------------------------------\n // 3. Reasoning → { effort }\n //\n // Admitted efforts are descriptor-owned. grok-4.5: `'low' | 'medium' | 'high'`\n // (live-verified 2026-08-24). grok-4.6: `'low' | 'medium' | 'high' | 'xhigh'`\n // (live-verified 2026-08-12). `'none'` is rejected by both. budgetTokens\n // is not supported (level-style reasoning). includeThoughts is a no-op\n // for xAI — reasoning summaries come back unconditionally whenever\n // reasoning ran, so reasoningText is always surfaced below regardless\n // of this flag; we do not throw on it since it is a legitimate\n // ReasoningIntent field this provider simply doesn't need.\n // ------------------------------------------------------------------\n const reasoning = genConfig.reasoning\n if (reasoning !== undefined) {\n if (reasoning.budgetTokens !== undefined) {\n throw badXaiRequest(\n `reasoning.budgetTokens is not supported for model \"${model}\" (xAI uses effort-level reasoning, not token budgets); use reasoning.effort instead.`,\n )\n }\n\n if (reasoning.effort !== undefined) {\n const effort = reasoning.effort\n if (effort === 'none' || effort === 'max') {\n throw badXaiRequest(\n `reasoning.effort \"${effort}\" is not supported for xai model \"${model}\".`,\n )\n }\n const admitted = req.modelDescriptor?.capabilities?.admittedReasoningEfforts\n // Fail-closed without a descriptor, matching the serviceTier branch:\n // a host-supplied descriptor that omits admittedReasoningEfforts\n // must not silently re-admit medium/xhigh onto grok-4.5.\n if (admitted === undefined || !admitted.includes(effort)) {\n throw badXaiRequest(\n `reasoning.effort \"${effort}\" is not supported for xai model \"${model}\".`,\n )\n }\n params.reasoning = { effort }\n }\n }\n\n // ------------------------------------------------------------------\n // 4. Structured output → text.format (NOT response_format)\n // ------------------------------------------------------------------\n const structuredOutputRequested = req.outputJsonSchema !== undefined\n if (structuredOutputRequested) {\n const schema = req.outputJsonSchema\n const name =\n isPlainRecord(schema) &&\n typeof schema['title'] === 'string' &&\n schema['title'].length > 0\n ? schema['title']\n : 'structured_output'\n params.text = {\n format: { type: 'json_schema', name, schema, strict: true },\n }\n }\n\n // ------------------------------------------------------------------\n // 5. providerOptions.xai → prompt_cache_key\n // ------------------------------------------------------------------\n if (xaiProviderConfig.promptCacheKey !== undefined) {\n params.prompt_cache_key = xaiProviderConfig.promptCacheKey\n }\n\n const hasFileRef = input.some(\n (item) =>\n isPlainRecord(item) &&\n Array.isArray(item['content']) &&\n item['content'].some(\n (part) => isPlainRecord(part) && part['type'] === 'input_file',\n ),\n )\n const searchTools = xaiProviderConfig.tools\n if (searchTools !== undefined) {\n if (req.modelDescriptor?.capabilities?.grounding !== true) {\n throw badXaiRequest(\n `providerOptions.xai.tools requires capabilities.grounding on the model descriptor for \"${model}\".`,\n )\n }\n if (\n structuredOutputRequested &&\n req.modelDescriptor.capabilities.structuredOutputWithTools !== true\n ) {\n throw badXaiRequest(\n `Structured output with providerOptions.xai.tools is not supported for model \"${model}\".`,\n )\n }\n params.tools = searchTools\n }\n\n if (req.tools !== undefined && req.tools.length > 0) {\n if (req.modelDescriptor?.capabilities?.functionCalling !== true) {\n throw badXaiRequest(\n `tools is not supported for xai model \"${model}\" (capabilities.functionCalling is not true).`,\n )\n }\n const functionTools = req.tools.map((tool) => ({\n type: 'function',\n name: tool.name,\n description: tool.description,\n parameters: tool.inputJsonSchema,\n }))\n params.tools = [...(params.tools ?? []), ...functionTools]\n if (req.toolChoice !== undefined) {\n params.tool_choice =\n typeof req.toolChoice === 'string'\n ? req.toolChoice\n : { type: 'function', name: req.toolChoice.name }\n }\n }\n if (xaiProviderConfig.parallelToolCalls !== undefined) {\n params.parallel_tool_calls = xaiProviderConfig.parallelToolCalls\n }\n\n // ------------------------------------------------------------------\n // 6. Client construction + SDK call — inside the classifier so ANY\n // failure (including bad auth construction) is rethrown as a typed\n // LlmError(provider:'xai').\n // ------------------------------------------------------------------\n let response: XaiResponseShape\n try {\n const buildClient = opts?._clientFactory ?? buildXaiClient\n const client: XaiClientLike =\n opts?.client !== undefined ? opts.client : await buildClient(ctx.auth)\n ctx.logger.debug(\n { model, configKeys: Object.keys(params) },\n 'llm.adapter.dispatch',\n )\n response = await client.responses.create(\n params,\n ctx.signal !== undefined ? { signal: ctx.signal } : undefined,\n )\n } catch (rawErr) {\n throw classifyXaiError(rawErr)\n }\n\n // ------------------------------------------------------------------\n // 7. Map response\n // ------------------------------------------------------------------\n let text = ''\n let reasoningText: string | undefined\n const messageItems: XaiMessageOutputItem[] = []\n const toolCalls: NonNullable<AdapterResult['toolCalls']> = []\n\n for (const item of response.output) {\n if (isXaiMessageItem(item)) {\n messageItems.push(item)\n } else if (isXaiReasoningItem(item)) {\n const joined = item.summary.map((s) => s.text).join('')\n if (joined.length > 0) {\n reasoningText = (reasoningText ?? '') + joined\n }\n } else if (item.type === 'function_call') {\n const callId = typeof item['call_id'] === 'string' ? item['call_id'] : ''\n const name = typeof item['name'] === 'string' ? item['name'] : ''\n let args: JsonValue = {}\n if (typeof item['arguments'] === 'string') {\n try {\n args = JSON.parse(item['arguments']) as JsonValue\n } catch {\n args = item['arguments']\n }\n }\n if (callId.length > 0 && name.length > 0) {\n toolCalls.push({ toolCallId: callId, toolName: name, args })\n }\n }\n }\n\n // xAI's Responses API convention: when multiple `type: 'message'`\n // output items are present, the LAST one is the response — earlier\n // ones are superseded (observed live in strict json_schema mode,\n // grok-4.5, reasoning effort high: two complete-JSON message items in\n // one response). Concatenating across items corrupts the payload\n // (e.g. two JSON documents back-to-back); joining `output_text` parts\n // WITHIN a single message item is still correct (segmentation, not\n // duplication).\n if (messageItems.length > 0) {\n const lastMessage = messageItems[messageItems.length - 1] as XaiMessageOutputItem\n text = lastMessage.content.map((part) => part.text).join('')\n\n if (messageItems.length > 1) {\n warnings.push({\n type: 'other',\n message: `xai: response contained ${messageItems.length} message output items; using the last one and discarding ${\n messageItems.length - 1\n } earlier message item(s).`,\n })\n }\n }\n\n // Parse structured output (JSON text → rawStructured).\n let rawStructured: unknown\n if (structuredOutputRequested && text.length > 0) {\n try {\n rawStructured = JSON.parse(text)\n } catch {\n // Core reports unparsed via absence of rawStructured; callers own\n // validation/retry policy (ADR-009).\n }\n }\n\n const usage = mapUsage(response.usage)\n const finishReason = mapFinishReason(response)\n\n const expectedToolCounters = expectedServerToolCounters(\n xaiProviderConfig.tools,\n hasFileRef,\n )\n if (expectedToolCounters.length > 0 || hasFileRef) {\n usage.details['server_tools_requested'] = 1\n if (\n xaiProviderConfig.tools?.some((tool) => tool['type'] === 'x_search') === true\n ) {\n usage.details['x_search_requested'] = 1\n }\n const missing = expectedToolCounters.filter((key) => !(key in usage.details))\n if (missing.length > 0) {\n usage.details['server_tools_missing'] = 1\n warnings.push({\n type: 'other',\n message: `xai: server tools were requested but usage is missing counters [${missing.join(\n ', ',\n )}]; the call is unpriced.`,\n })\n }\n if (hasFileRef) {\n // Attachment_search counter is not live-pinned (ZDR blocks file\n // attach). Never claim exact $0 for a file-ref call.\n usage.details['attachment_search_unpinned'] = 1\n warnings.push({\n type: 'other',\n message:\n 'xai: file-ref enables attachment_search but that counter is not live-pinned; tool cost is estimated.',\n })\n }\n }\n\n const citations = collectXaiCitations(response, messageItems)\n\n // Response-level metadata → providerMetadata: usage.context_details\n // (non-numeric usage extra) and response.metadata (e.g.\n // system_fingerprint). Numeric usage extras live in usage.details; the\n // full raw usage payload is already in usage.raw.\n const providerMeta: { [k: string]: JsonValue } = {}\n const contextDetails = response.usage['context_details']\n if (isPlainRecord(contextDetails)) {\n providerMeta['context_details'] = contextDetails as unknown as JsonValue\n }\n if (isPlainRecord(response.metadata)) {\n providerMeta['metadata'] = response.metadata as unknown as JsonValue\n }\n let transientProviderState: JsonValue | undefined\n if (replayRequired) {\n // Preserve every provider output item in wire order. This includes\n // messages and encrypted server-tool items that normalized Message\n // cannot represent. The next request appends only new user/tool-result\n // messages; callers do not repeat normalized history with state.\n const state: XaiReplayState = {\n model,\n input: [...params.input, ...response.output],\n }\n transientProviderState = state as unknown as JsonValue\n }\n\n // Surface the echoed tier verbatim. xAI can remap (flex → default);\n // discarding non-priority values would let the engine fall back to the\n // requested tier and bill 2× on a default-served call.\n const servedServiceTier =\n typeof response.service_tier === 'string' && response.service_tier.length > 0\n ? response.service_tier\n : undefined\n\n const result: AdapterResult = {\n model: response.model,\n usage,\n warnings,\n finishReason,\n responseId: response.id,\n ...(text.length > 0 ? { text } : {}),\n ...(reasoningText !== undefined ? { reasoningText } : {}),\n ...(rawStructured !== undefined ? { rawStructured } : {}),\n ...(servedServiceTier !== undefined ? { servedServiceTier } : {}),\n ...(Object.keys(providerMeta).length > 0\n ? { providerMetadata: providerMeta }\n : {}),\n ...(transientProviderState !== undefined ? { transientProviderState } : {}),\n ...(citations.length > 0 ? { citations } : {}),\n ...(toolCalls.length > 0 ? { toolCalls, finishReason: 'tool_calls' } : {}),\n }\n\n return result\n },\n\n async countTokens(req: TokenCountRequest, ctx: AdapterCtx): Promise<TokenCount> {\n if (req.provider !== 'xai') {\n throw new LlmError(\n `xaiAdapter received a request for provider \"${req.provider}\", expected \"xai\".`,\n { kind: 'bad_request', retryable: false },\n )\n }\n if (req.tools !== undefined && req.tools.length > 0) {\n throw badXaiRequest(\n 'xAI countTokens rejects tools; tokenize-text cannot represent tool declarations.',\n )\n }\n\n const text = concatenateTokenizeText(req)\n const apiKey = requireApiKey(ctx.auth)\n const fetchImpl = opts?._fetch ?? fetch\n\n try {\n const res = await fetchImpl('https://api.x.ai/v1/tokenize-text', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ model: req.model, text }),\n ...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),\n })\n\n if (!res.ok) {\n let parsed: unknown\n try {\n parsed = await res.json()\n } catch {\n parsed = await res.text().catch(() => '')\n }\n throw Object.assign(new Error(`xAI tokenize-text HTTP ${res.status}`), {\n status: res.status,\n error: parsed,\n })\n }\n\n const raw: unknown = await res.json()\n if (!isPlainRecord(raw) || !Array.isArray(raw['token_ids'])) {\n throw new LlmError(\n 'xAI tokenize-text response is malformed: missing required field: token_ids',\n { kind: 'server', retryable: true, provider: 'xai' },\n )\n }\n const n = raw['token_ids'].length\n return {\n totalTokens: n,\n accuracy: 'lower-bound',\n details: { textTokens: n },\n raw: raw as JsonValue,\n }\n } catch (rawErr) {\n if (rawErr instanceof Error && rawErr.name === 'AbortError') {\n throw new LlmError('xAI tokenize-text aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n cause: rawErr,\n })\n }\n throw classifyXaiError(rawErr)\n }\n },\n }\n}\n\n/** Counter names from `usage.server_side_tool_usage_details`. */\nconst WEB_SEARCH_COUNTER = 'web_search_calls'\nfunction expectedServerToolCounters(\n tools: Array<Record<string, unknown>> | undefined,\n _hasFileRef: boolean,\n): string[] {\n const keys: string[] = []\n if (tools !== undefined) {\n for (const tool of tools) {\n if (tool['type'] === 'web_search') keys.push(WEB_SEARCH_COUNTER)\n if (tool['type'] === 'x_search') keys.push(...X_SEARCH_ITEM_COUNTERS)\n }\n }\n return keys\n}\n\nfunction collectXaiCitations(\n response: XaiResponseShape,\n messageItems: XaiMessageOutputItem[],\n): Citation[] {\n const seen = new Set<string>()\n const citations: Citation[] = []\n\n const push = (url: unknown, title: unknown) => {\n if (typeof url !== 'string' || url.length === 0) return\n if (seen.has(url)) return\n seen.add(url)\n const citation: Citation = { url }\n if (typeof title === 'string' && title.length > 0 && title !== url) {\n citation.title = title\n }\n try {\n const parsed = new URL(url)\n if (parsed.hostname.length > 0) {\n citation.sourceName = parsed.hostname.startsWith('www.')\n ? parsed.hostname.slice(4)\n : parsed.hostname\n }\n } catch {\n /* keep url-only */\n }\n citations.push(citation)\n }\n\n if (Array.isArray(response.citations)) {\n for (const item of response.citations) {\n if (typeof item === 'string') {\n push(item, undefined)\n } else if (isPlainRecord(item)) {\n push(item['url'] ?? item['uri'], item['title'])\n }\n }\n }\n\n const lastMessage = messageItems.at(-1)\n const citationMessages = lastMessage === undefined ? [] : [lastMessage]\n for (const item of citationMessages) {\n for (const part of item.content) {\n const annotations = part.annotations\n if (!Array.isArray(annotations)) continue\n for (const ann of annotations) {\n if (!isPlainRecord(ann)) continue\n if (ann['type'] !== undefined && ann['type'] !== 'url_citation') continue\n push(ann['url'], ann['title'])\n }\n }\n }\n\n return citations\n}\n\nfunction concatenateTokenizeText(req: TokenCountRequest): string {\n const chunks: string[] = []\n if (req.system !== undefined && req.system.length > 0) {\n chunks.push(req.system)\n }\n for (const message of req.messages) {\n for (const part of message.parts) {\n switch (part.kind) {\n case 'text':\n chunks.push(part.text)\n break\n case 'inline-media':\n case 'file-uri':\n case 'file-ref':\n case 'tool-call':\n case 'tool-result':\n throw badXaiRequest(\n `xAI countTokens rejects ${part.kind} parts; tokenize-text is text-only.`,\n )\n default:\n return assertNever(part)\n }\n }\n }\n return chunks.join('\\n')\n}\n","/**\n * XaiFileStore — thin wrapper over the xAI Files REST API.\n *\n * Upload / get / list / delete / content over injectable `fetch`.\n * No READY-state polling (upload returns metadata immediately).\n * No ambient credential reads — auth is injected at construction.\n *\n * @module\n */\n\nimport type { AuthMaterial, JsonValue, Logger } from '@gullabs/core'\nimport { LlmError, classifyError, redactSecrets } from '@gullabs/core'\n\nimport { requireApiKey } from './client.js'\nimport { classifyXaiError } from './adapter.js'\n\n// ---------------------------------------------------------------------------\n// Public constants\n// ---------------------------------------------------------------------------\n\n/** xAI minimum `expires_after` (1 hour), inclusive. */\nexport const XAI_FILE_TTL_MIN_SECONDS = 3_600\n\n/** xAI maximum `expires_after` (30 days), inclusive. */\nexport const XAI_FILE_TTL_MAX_SECONDS = 2_592_000\n\n/**\n * Conservative max upload size (48 MiB). Managing-files docs say ~48 MB;\n * upload REST says 50 MB — we take the lower bound.\n */\nexport const XAI_FILE_MAX_BYTES = 48 * 1024 * 1024\n\n/** Default Files API base (includes `/v1`). */\nexport const XAI_FILES_DEFAULT_BASE_URL = 'https://api.x.ai/v1'\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** A handle to a file stored in the xAI Files API. */\nexport interface XaiFileHandle {\n /** File id, e.g. `\"file_a128090d-…\"`. Use as `FileRefPart.fileId`. */\n id: string\n filename?: string\n bytes?: number\n purpose?: string\n createdAt?: Date\n /** Present when the file has a TTL; key omitted when permanent / unknown. */\n expiresAt?: Date\n /** Full vendor JSON object for forward-compat (P2 raw lane). */\n raw?: { [k: string]: JsonValue }\n}\n\nexport interface XaiFileUploadInput {\n data: Uint8Array | Blob\n filename: string\n mimeType?: string\n /**\n * TTL in seconds. Must be an integer in\n * `[XAI_FILE_TTL_MIN_SECONDS, XAI_FILE_TTL_MAX_SECONDS]` when set.\n * Omit only for permanent storage (discouraged for ephemeral corpus).\n */\n expiresAfterSeconds?: number\n /** Default `\"assistants\"` (OpenAI SDK convention; xAI does not enforce). */\n purpose?: string\n}\n\nexport interface XaiFileListOptions {\n /** 1..100. Server default is 100 when omitted. */\n limit?: number\n order?: 'asc' | 'desc'\n sortBy?: 'created_at' | 'filename' | 'size'\n paginationToken?: string\n}\n\nexport interface XaiFileListResult {\n files: XaiFileHandle[]\n paginationToken?: string\n}\n\n/**\n * Options for {@link XaiFileStore.delete} / {@link XaiFileStore.deleteAll}.\n *\n * Default is fail-open (P5 side-effect style). Pass `failClosed: true` when\n * the host gates durable state (e.g. `released_at`) on known delete success.\n */\nexport interface FileDeleteOptions {\n signal?: AbortSignal\n /**\n * When true, non-404 failures throw typed `LlmError`.\n * When false/omitted, non-404 failures invoke `onDeleteError` and resolve.\n * HTTP 404 is success in both modes (idempotent).\n */\n failClosed?: boolean\n}\n\nexport interface XaiFileStoreOptions {\n auth: AuthMaterial\n /** Default {@link XAI_FILES_DEFAULT_BASE_URL}. */\n baseUrl?: string\n /** Injectable fetch for tests. Default: global `fetch`. */\n fetch?: typeof fetch\n /**\n * Delete failures that are NOT already-gone (404).\n * Default: `logger.error` or `console.error` with a redacted message.\n */\n onDeleteError?: (fileId: string, err: unknown) => void\n logger?: Logger\n /** Injectable clock for tests. Default: `Date.now`. */\n now?: () => number\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\ntype VendorFileObject = {\n id?: unknown\n filename?: unknown\n bytes?: unknown\n purpose?: unknown\n created_at?: unknown\n expires_at?: unknown\n object?: unknown\n [k: string]: unknown\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction badRequest(message: string): LlmError {\n return new LlmError(message, {\n kind: 'bad_request',\n retryable: false,\n provider: 'xai',\n })\n}\n\nfunction resolveFileId(fileIdOrHandle: string | Pick<XaiFileHandle, 'id'>): string {\n if (typeof fileIdOrHandle === 'string') {\n return fileIdOrHandle\n }\n return fileIdOrHandle.id\n}\n\nfunction unixSecondsToDate(value: unknown): Date | undefined {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return undefined\n }\n return new Date(value * 1000)\n}\n\nfunction makeHandle(raw: VendorFileObject): XaiFileHandle {\n if (typeof raw.id !== 'string' || raw.id.length === 0) {\n throw new LlmError('File response missing required field (id)', {\n kind: 'server',\n retryable: false,\n provider: 'xai',\n })\n }\n\n const handle: XaiFileHandle = {\n id: raw.id,\n raw: raw as { [k: string]: JsonValue },\n }\n\n if (typeof raw.filename === 'string' && raw.filename.length > 0) {\n handle.filename = raw.filename\n }\n if (typeof raw.bytes === 'number' && Number.isFinite(raw.bytes)) {\n handle.bytes = raw.bytes\n }\n if (typeof raw.purpose === 'string') {\n handle.purpose = raw.purpose\n }\n\n const createdAt = unixSecondsToDate(raw.created_at)\n if (createdAt !== undefined) {\n handle.createdAt = createdAt\n }\n\n // expires_at is null for permanent files — omit the key entirely (Google parity).\n if (raw.expires_at !== null && raw.expires_at !== undefined) {\n const expiresAt = unixSecondsToDate(raw.expires_at)\n if (expiresAt !== undefined) {\n handle.expiresAt = expiresAt\n }\n }\n\n return handle\n}\n\nfunction byteLengthOf(data: Uint8Array | Blob): number {\n return data instanceof Uint8Array ? data.byteLength : data.size\n}\n\nfunction toBlob(data: Uint8Array | Blob, mimeType: string | undefined): Blob {\n if (data instanceof Blob) {\n return data\n }\n // Copy into a plain ArrayBuffer-backed view for BlobPart typing.\n const copy = Uint8Array.from(data)\n return mimeType !== undefined && mimeType.length > 0\n ? new Blob([copy], { type: mimeType })\n : new Blob([copy])\n}\n\n/**\n * Shape a non-2xx fetch response into a throw value that\n * {@link classifyXaiError} / {@link classifyError} understand:\n * - `.status` for HTTP routing\n * - `.error` for structured body (auth-body detection)\n */\n/**\n * Error shaped for {@link classifyError} / {@link classifyXaiError}:\n * numeric `.status` for HTTP routing, `.error` for structured body text.\n */\nclass XaiFilesHttpError extends Error {\n readonly status: number\n readonly error: unknown\n\n constructor(status: number, message: string, errorBody: unknown) {\n super(message)\n this.name = 'XaiFilesHttpError'\n this.status = status\n this.error = errorBody\n }\n}\n\nasync function throwHttpFailure(res: Response): Promise<never> {\n const status = res.status\n let bodyText = ''\n try {\n bodyText = await res.text()\n } catch {\n bodyText = ''\n }\n\n let parsed: unknown = bodyText\n if (bodyText.length > 0) {\n try {\n parsed = JSON.parse(bodyText) as unknown\n } catch {\n parsed = bodyText\n }\n }\n\n let message = `xAI Files API HTTP ${status}`\n if (typeof parsed === 'string' && parsed.length > 0) {\n message = parsed\n } else if (isPlainRecord(parsed) && typeof parsed['error'] === 'string') {\n message = parsed['error']\n }\n\n throw new XaiFilesHttpError(status, message, parsed)\n}\n\nfunction isNotFoundError(err: unknown): boolean {\n if (err instanceof LlmError && err.httpStatus === 404) {\n return true\n }\n if (typeof err === 'object' && err !== null) {\n const status = (err as { status?: unknown }).status\n if (status === 404) return true\n const httpStatus = (err as { httpStatus?: unknown }).httpStatus\n if (httpStatus === 404) return true\n }\n return false\n}\n\nfunction notFoundError(fileId: string, operation: string): LlmError {\n return new LlmError(`xAI file not found during ${operation}: \"${fileId}\"`, {\n kind: 'bad_request',\n retryable: false,\n httpStatus: 404,\n provider: 'xai',\n })\n}\n\nfunction maybeZdrHint(message: string): string {\n if (\n /zero\\s*data\\s*retention|\\bzdr\\b|files?\\s+(api\\s+)?(disabled|unavailable|not supported)/i.test(\n message,\n )\n ) {\n return `${message} (xAI Zero Data Retention blocks new file uploads and file_id attachments for this team.)`\n }\n return message\n}\n\n/** Prefer structured body text / explicit message over generic `HTTP NNN`. */\nfunction extractThrownMessage(raw: unknown): string | undefined {\n if (raw === null || typeof raw !== 'object') return undefined\n const obj = raw as Record<string, unknown>\n if (typeof obj['message'] === 'string' && obj['message'].length > 0) {\n return obj['message']\n }\n const err = obj['error']\n if (typeof err === 'string' && err.length > 0) return err\n if (typeof err === 'object' && err !== null) {\n const nested = err as Record<string, unknown>\n if (typeof nested['error'] === 'string' && nested['error'].length > 0) {\n return nested['error']\n }\n if (typeof nested['message'] === 'string' && nested['message'].length > 0) {\n return nested['message']\n }\n }\n return undefined\n}\n\nfunction classifyStoreError(raw: unknown): LlmError {\n if (raw instanceof LlmError) {\n return raw\n }\n const classified = classifyXaiError(raw)\n const bodyMessage = extractThrownMessage(raw)\n // classifyError maps plain `{ status }` throws to generic \"HTTP NNN\" — prefer\n // the structured body text we attached in throwHttpFailure when present.\n const baseMessage =\n bodyMessage !== undefined &&\n (classified.message.startsWith('HTTP ') || classified.message.length === 0)\n ? bodyMessage\n : classified.message\n const hinted = maybeZdrHint(baseMessage)\n if (\n hinted === classified.message &&\n classified.provider === 'xai' &&\n bodyMessage === undefined\n ) {\n return classified\n }\n return new LlmError(hinted, {\n kind: classified.kind,\n retryable: classified.retryable,\n ...(classified.httpStatus !== undefined ? { httpStatus: classified.httpStatus } : {}),\n ...(classified.retryAfterMs !== undefined\n ? { retryAfterMs: classified.retryAfterMs }\n : {}),\n provider: 'xai',\n cause: classified.cause ?? raw,\n })\n}\n\n// ---------------------------------------------------------------------------\n// XaiFileStore\n// ---------------------------------------------------------------------------\n\n/**\n * **Auth snapshot note:** captures `AuthMaterial` at construction and holds\n * the resolved API key for the store lifetime. Correct for static API keys.\n * Refreshable credentials would need a resolver callback (see GoogleFileStore\n * / ADR-020).\n */\nexport class XaiFileStore {\n private readonly apiKey: string\n private readonly baseUrl: string\n private readonly fetchImpl: typeof fetch\n private readonly onDeleteError: (fileId: string, err: unknown) => void\n private readonly logger: Logger | undefined\n\n constructor(opts: XaiFileStoreOptions) {\n this.apiKey = requireApiKey(opts.auth)\n this.baseUrl = (opts.baseUrl ?? XAI_FILES_DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.fetchImpl = opts.fetch ?? fetch\n this.logger = opts.logger\n this.onDeleteError =\n opts.onDeleteError ??\n ((fileId, err) => {\n const message = redactSecrets(classifyError(err).message)\n if (this.logger !== undefined) {\n this.logger.error({ fileId, error: message }, 'xai.file.delete.failed')\n } else {\n console.error(`[XaiFileStore] delete failed for \"${fileId}\":`, message)\n }\n })\n }\n\n private authHeaders(): Headers {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${this.apiKey}`)\n return headers\n }\n\n private filesUrl(path = ''): string {\n if (path.length === 0) return `${this.baseUrl}/files`\n return `${this.baseUrl}/files/${path.replace(/^\\//, '')}`\n }\n\n /** Build RequestInit without writing `signal: undefined` (exactOptionalPropertyTypes). */\n private requestInit(\n method: string,\n opts?: { body?: FormData; signal?: AbortSignal },\n ): RequestInit {\n const init: RequestInit = {\n method,\n headers: this.authHeaders(),\n }\n if (opts?.body !== undefined) {\n init.body = opts.body\n }\n if (opts?.signal !== undefined) {\n init.signal = opts.signal\n }\n return init\n }\n\n /**\n * Upload bytes to xAI Files. Returns immediately with metadata (no poll).\n *\n * Multipart field order is load-bearing: `expires_after` then `purpose`\n * then `file` — reversing order yields HTTP 400 from xAI.\n */\n async upload(input: XaiFileUploadInput, signal?: AbortSignal): Promise<XaiFileHandle> {\n if (typeof input.filename !== 'string' || input.filename.trim() === '') {\n throw badRequest('XaiFileUploadInput.filename must be a non-empty string.')\n }\n\n const size = byteLengthOf(input.data)\n if (size > XAI_FILE_MAX_BYTES) {\n throw badRequest(\n `xAI file uploads must be at most ${XAI_FILE_MAX_BYTES} bytes (48 MiB); got ${size}.`,\n )\n }\n\n if (input.expiresAfterSeconds !== undefined) {\n const ttl = input.expiresAfterSeconds\n if (\n typeof ttl !== 'number' ||\n !Number.isInteger(ttl) ||\n ttl < XAI_FILE_TTL_MIN_SECONDS ||\n ttl > XAI_FILE_TTL_MAX_SECONDS\n ) {\n throw badRequest(\n `expiresAfterSeconds must be an integer in [${XAI_FILE_TTL_MIN_SECONDS}, ${XAI_FILE_TTL_MAX_SECONDS}]; got ${String(ttl)}.`,\n )\n }\n }\n\n const purpose = input.purpose ?? 'assistants'\n const form = new FormData()\n\n // Order: expires_after → purpose → file (xAI multipart requirement).\n if (input.expiresAfterSeconds !== undefined) {\n form.append('expires_after', String(input.expiresAfterSeconds))\n }\n form.append('purpose', purpose)\n form.append('file', toBlob(input.data, input.mimeType), input.filename)\n\n let res: Response\n try {\n res = await this.fetchImpl(\n this.filesUrl(),\n this.requestInit('POST', {\n body: form,\n ...(signal !== undefined ? { signal } : {}),\n }),\n )\n } catch (e) {\n if (signal?.aborted === true) {\n throw new LlmError('xAI file upload aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n })\n }\n throw classifyStoreError(e)\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res)\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n let json: unknown\n try {\n json = await res.json()\n } catch (e) {\n throw new LlmError('xAI file upload returned non-JSON body', {\n kind: 'server',\n retryable: false,\n provider: 'xai',\n cause: e,\n })\n }\n\n return makeHandle(json as VendorFileObject)\n }\n\n async get(fileId: string, signal?: AbortSignal): Promise<XaiFileHandle> {\n if (typeof fileId !== 'string' || fileId.trim() === '') {\n throw badRequest('fileId must be a non-empty string.')\n }\n\n let res: Response\n try {\n res = await this.fetchImpl(\n this.filesUrl(fileId),\n this.requestInit('GET', signal !== undefined ? { signal } : {}),\n )\n } catch (e) {\n if (signal?.aborted === true) {\n throw new LlmError('xAI file get aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n })\n }\n throw classifyStoreError(e)\n }\n\n if (res.status === 404) {\n throw notFoundError(fileId, 'get')\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res)\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n const json = (await res.json()) as VendorFileObject\n return makeHandle(json)\n }\n\n async list(\n opts: XaiFileListOptions = {},\n signal?: AbortSignal,\n ): Promise<XaiFileListResult> {\n if (opts.limit !== undefined) {\n if (\n typeof opts.limit !== 'number' ||\n !Number.isInteger(opts.limit) ||\n opts.limit < 1 ||\n opts.limit > 100\n ) {\n throw badRequest('list.limit must be an integer in [1, 100].')\n }\n }\n\n const params = new URLSearchParams()\n if (opts.limit !== undefined) params.set('limit', String(opts.limit))\n if (opts.order !== undefined) params.set('order', opts.order)\n if (opts.sortBy !== undefined) params.set('sort_by', opts.sortBy)\n if (opts.paginationToken !== undefined) {\n params.set('pagination_token', opts.paginationToken)\n }\n\n const qs = params.toString()\n const url = qs.length > 0 ? `${this.filesUrl()}?${qs}` : this.filesUrl()\n\n let res: Response\n try {\n res = await this.fetchImpl(\n url,\n this.requestInit('GET', signal !== undefined ? { signal } : {}),\n )\n } catch (e) {\n if (signal?.aborted === true) {\n throw new LlmError('xAI file list aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n })\n }\n throw classifyStoreError(e)\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res)\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n const json = (await res.json()) as {\n data?: VendorFileObject[]\n pagination_token?: string\n }\n const files = Array.isArray(json.data) ? json.data.map((f) => makeHandle(f)) : []\n const result: XaiFileListResult = { files }\n if (typeof json.pagination_token === 'string' && json.pagination_token.length > 0) {\n result.paginationToken = json.pagination_token\n }\n return result\n }\n\n /**\n * Delete a file. Idempotent: HTTP 404 → success.\n *\n * Default (`failClosed` omitted/false): non-404 errors go to `onDeleteError`\n * and resolve (P5 fail-open). With `failClosed: true`, non-404 errors throw\n * typed `LlmError` and `onDeleteError` is not called.\n *\n * Empty/blank ids always throw `bad_request` (caller fault).\n */\n async delete(\n fileIdOrHandle: string | Pick<XaiFileHandle, 'id'>,\n opts?: FileDeleteOptions,\n ): Promise<void> {\n const fileId = resolveFileId(fileIdOrHandle)\n if (typeof fileId !== 'string' || fileId.trim() === '') {\n throw badRequest('fileId must be a non-empty string.')\n }\n\n const failClosed = opts?.failClosed === true\n const signal = opts?.signal\n\n try {\n const res = await this.fetchImpl(\n this.filesUrl(fileId),\n this.requestInit('DELETE', signal !== undefined ? { signal } : {}),\n )\n\n if (res.status === 404) {\n return\n }\n\n if (!res.ok) {\n await throwHttpFailure(res)\n }\n } catch (err) {\n if (isNotFoundError(err)) {\n return\n }\n\n // Abort during fetch: surface as aborted LlmError through the same path.\n const classified =\n signal?.aborted === true && !(err instanceof LlmError)\n ? new LlmError('xAI file delete aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n cause: err,\n })\n : classifyStoreError(err)\n\n if (failClosed) {\n throw classified\n }\n this.onDeleteError(fileId, classified)\n }\n }\n\n /**\n * Delete many files.\n *\n * Fail-open (default): `Promise.allSettled` — each failure → `onDeleteError`.\n * Fail-closed: `Promise.all` — first throw rejects; in-flight siblings are\n * not cancelled (partial deletes may already have succeeded at the provider).\n * Prefer per-id delete + host DB mark when gating durable release state.\n */\n async deleteAll(\n ids: ReadonlyArray<string | Pick<XaiFileHandle, 'id'>>,\n opts?: FileDeleteOptions,\n ): Promise<void> {\n if (opts?.failClosed === true) {\n await Promise.all(ids.map((id) => this.delete(id, opts)))\n return\n }\n await Promise.allSettled(ids.map((id) => this.delete(id, opts)))\n }\n\n /** Download raw file bytes. */\n async getContent(fileId: string, signal?: AbortSignal): Promise<Uint8Array> {\n if (typeof fileId !== 'string' || fileId.trim() === '') {\n throw badRequest('fileId must be a non-empty string.')\n }\n\n let res: Response\n try {\n res = await this.fetchImpl(\n this.filesUrl(`${fileId}/content`),\n this.requestInit('GET', signal !== undefined ? { signal } : {}),\n )\n } catch (e) {\n if (signal?.aborted === true) {\n throw new LlmError('xAI file content download aborted', {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n })\n }\n throw classifyStoreError(e)\n }\n\n if (res.status === 404) {\n throw notFoundError(fileId, 'getContent')\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res)\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n const buf = await res.arrayBuffer()\n return new Uint8Array(buf)\n }\n}\n","/**\n * `xaiProvider` — {@link ProviderPlugin} factory for @gullabs/xai.\n *\n * Bundles the xAI Grok adapter, the `grok-4.5` / `grok-4.6` model\n * descriptors, and the xai pricing source into a single plugin for\n * {@link composeProviders}.\n *\n * @module\n */\n\nimport type { ProviderPlugin } from '@gullabs/core'\n\nimport { xaiAdapter } from './adapter.js'\nimport type { XaiAdapterOptions } from './adapter.js'\nimport { xaiModelDescriptors } from './models.js'\nimport { xaiPricingSource } from './pricing.js'\n\n/**\n * Create a {@link ProviderPlugin} for the xAI Grok provider.\n *\n * @param opts - Forwarded to {@link xaiAdapter}.\n * @returns A plugin bundling the xAI adapter, the `grok-4.5` / `grok-4.6`\n * model descriptors, and the built-in xai pricing source.\n *\n * @example\n * ```ts\n * import { createClient, composeProviders } from '@gullabs/core'\n * import { xaiProvider } from '@gullabs/xai'\n *\n * const client = createClient({\n * ...composeProviders([xaiProvider()]),\n * })\n * ```\n */\nexport function xaiProvider(opts?: XaiAdapterOptions): ProviderPlugin {\n return {\n adapter: xaiAdapter(opts),\n modelDescriptors: xaiModelDescriptors,\n pricingSource: xaiPricingSource(),\n }\n}\n"]}