@gullabs/xai 0.8.0 → 0.16.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/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,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;AAkPA,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;AC9SA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AO,GAAI,EAAE;AAAA,OAChE;AAAA,IACF,SAAS,CAAA,EAAG;AACV,MAAA,IAAI,MAAA,EAAQ,YAAY,IAAA,EAAM;AAC5B,QAAA,MAAM,IAAIA,SAAS,mCAAA,EAAqC;AAAA,UACtD,IAAA,EAAM,SAAA;AAAA,UACN,SAAA,EAAW,KAAA;AAAA,UACX,QAAA,EAAU;AAAA,SACX,CAAA;AAAA,MACH;AACA,MAAA,MAAM,mBAAmB,CAAC,CAAA;AAAA,IAC5B;AAEA,IAAA,IAAI,GAAA,CAAI,WAAW,GAAA,EAAK;AACtB,MAAA,MAAM,aAAA,CAAc,QAAQ,YAAY,CAAA;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"]}
1
+ {"version":3,"sources":["../src/sse.ts","../src/stream.ts","../src/client.ts","../src/model-limits.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/json-schema.ts","../src/pricing.ts","../src/adapter.ts","../src/file-store.ts","../src/provider.ts"],"names":["status","offset","item","z","maxOutputTokensSchema","LlmError","length","isPlainRec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ACH;AACF;AAMA,eAAe,YAAA,CACb,GAAA,EACA,MAAA,EACA,SAAA,EACkB;AAClB,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,IAAI,IAAA,EAAK;AAAA,EACxB,SAAS,CAAA,EAAG;AACV,IAAA,IAAI,MAAA,CAAO,SAAS,MAAM,YAAA,CAAa,QAAQ,CAAA,SAAA,EAAY,SAAS,YAAY,CAAC,CAAA;AACjF,IAAA,MAAM,IAAIA,QAAAA,CAAS,CAAA,SAAA,EAAY,SAAS,CAAA,yBAAA,CAAA,EAA6B;AAAA,MACnE,IAAA,EAAM,QAAA;AAAA,MACN,SAAA,EAAW,KAAA;AAAA,MACX,QAAA,EAAU,KAAA;AAAA,MACV,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF;;;ACrwBO,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 * A minimal server-sent-events frame reader over a response body (ADR-040).\n *\n * The client reads the body itself instead of through the `openai` SDK's stream\n * iterator for three reasons the SDK iterator cannot serve: every chunk of raw\n * bytes (a `: heartbeat` comment included) is activity for the optional idle\n * timer, a frame that carries no event JSON (a bare `event: keepalive`) must be\n * skipped, not thrown as a `SyntaxError`, and the reducer, not the SDK, decides\n * what an `error` frame means.\n *\n * Follows the WHATWG EventSource framing: lines end in LF, CRLF or CR, a blank\n * line dispatches a frame, `:` starts a comment, `data` lines join with LF, and a\n * frame still open when the body ends is dropped.\n *\n * @module\n */\n\n/** One dispatched frame. `data` is `''` for a frame with no `data` line. */\nexport interface SseFrame {\n event: string | undefined\n data: string\n}\n\ninterface SseReadOptions {\n /** Called once for every chunk of bytes read, before it is parsed. */\n onChunk?: () => void\n /**\n * Rejects when the request is aborted. Every read waits on it too, so a body\n * that does not itself react to the abort cannot hold the call open.\n */\n aborted?: Promise<never>\n}\n\n/**\n * Reads `body` to its end, yielding each dispatched frame. Cancels the body when\n * the consumer stops early or the read fails.\n *\n * Linear in the bytes read: only each new chunk is scanned for line ends, and the\n * pieces of a line still open are joined once when it ends, so one event of many\n * megabytes in small chunks costs no more than the same bytes in few.\n */\nexport async function* readSseFrames(\n body: ReadableStream<Uint8Array>,\n options: SseReadOptions = {},\n): AsyncGenerator<SseFrame, void, undefined> {\n const reader = body.getReader()\n const decoder = new TextDecoder('utf-8')\n /** The pieces of the line still open (no line end seen yet). */\n let pieces: string[] = []\n /** The last chunk ended with CR: a LF opening the next chunk is the same line end. */\n let skipLf = false\n let event: string | undefined\n let data: string[] = []\n let first = true\n /** Applies one non-blank line to the open frame. */\n const field = (line: string): void => {\n if (line.startsWith(':')) return\n const colon = line.indexOf(':')\n const name = colon === -1 ? line : line.slice(0, colon)\n let value = colon === -1 ? '' : line.slice(colon + 1)\n if (value.startsWith(' ')) value = value.slice(1)\n if (name === 'event') event = value\n else if (name === 'data') data.push(value)\n }\n // One reaction on `aborted` for the whole read, not one per chunk.\n const abort: { happened: boolean; error: Error } = {\n happened: false,\n error: new Error('aborted'),\n }\n let wake: ((error: unknown) => void) | undefined\n options.aborted?.catch((error: unknown) => {\n abort.happened = true\n abort.error = error instanceof Error ? error : new Error(String(error))\n wake?.(error)\n })\n const nextChunk = (): Promise<\n Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>['read']>>\n > => {\n if (abort.happened) return Promise.reject(abort.error)\n return new Promise((resolve, reject) => {\n wake = reject\n reader.read().then(resolve, reject)\n })\n }\n try {\n for (;;) {\n const result = await nextChunk()\n if (!result.done) options.onChunk?.()\n let text = result.done\n ? decoder.decode()\n : decoder.decode(result.value, { stream: true })\n if (first && text.length > 0) {\n text = text.replace(/^\\uFEFF/, '')\n first = false\n }\n let start = 0\n if (skipLf && text.length > 0) {\n skipLf = false\n if (text.charCodeAt(0) === 0x0a) start = 1\n }\n const lineEnd = /[\\r\\n]/g\n lineEnd.lastIndex = start\n for (let end = lineEnd.exec(text); end !== null; end = lineEnd.exec(text)) {\n pieces.push(text.slice(start, end.index))\n const line = pieces.length === 1 ? (pieces[0] as string) : pieces.join('')\n pieces = []\n start = end.index + 1\n if (text.charCodeAt(end.index) === 0x0d) {\n if (start < text.length) {\n if (text.charCodeAt(start) === 0x0a) start += 1\n } else if (!result.done) {\n skipLf = true\n }\n }\n lineEnd.lastIndex = start\n if (line !== '') {\n field(line)\n } else {\n if (event !== undefined || data.length > 0) {\n yield { event, data: data.join('\\n') }\n }\n event = undefined\n data = []\n }\n }\n if (start < text.length) pieces.push(text.slice(start))\n // A frame still open when the body ends was cut off and is dropped, as the\n // EventSource specification says: it never reached its blank line.\n if (result.done) return\n }\n } finally {\n wake = undefined\n // Release the connection whether the consumer finished, stopped or failed.\n reader.cancel().catch(() => undefined)\n }\n}\n","/**\n * Server-sent-event reduction for the xAI Responses API (ADR-040).\n *\n * `run()` sends `stream: true` and reads the SSE stream to its terminal event.\n * The terminal event carries the same response object a non-streamed call\n * returns, and live capture P9a showed that object can be INCOMPLETE: two of\n * two streamed search runs returned a final `output` without the `reasoning`\n * item the non-streamed call had. Everything downstream (the assistant\n * message, citations, the `'state'` continuation that replays the provider's\n * own output items) is built from `output`, so this module rebuilds the output\n * item list from the events and reconciles it with the final object.\n *\n * **Reconciliation is enrichment, never a gate (ADR-040 Amendment A).** Once the\n * terminal event carries a response object, the call is billed and answered:\n * the final object is the authority and nothing the events say can fail it.\n * What the events cannot place or what disagrees with the final object is\n * skipped and reported in the notes.\n *\n * Reconciliation rules (a pure function of the events; no I/O):\n *\n * 1. Items are matched by `id` and occurrence (xAI repeats an id inside one\n * `output`: live fixtures carry two `message` items with one `msg_` id); an\n * item with no id is matched to the same type's n-th id-less item on the\n * other side. When the two sides hold a different number of items under one\n * id, the occurrences are aligned from the start or from the end, whichever\n * pairs more items of identical content (a tie goes to the end).\n * 2. The final object is authoritative for an item it carries. A field it lacks\n * that a completed (`output_item.done`) event carries is filled from the\n * event; a field both carry with different values keeps the final's value\n * and, for the item types the adapter consumes, is reported in the notes. An\n * item the same id carries with a different type keeps the final's item.\n * 3. An item the events completed and the final object lacks is inserted at its\n * `output_index`, unless an unmatched final item has the same content under\n * another id (then they are one item).\n * 4. An item that only ever got `output_item.added` plus deltas, and that the\n * final object lacks, is assembled from the deltas (text, annotations,\n * summary parts, function arguments, custom tool input) and marked finished;\n * the notes say so.\n * 5. An event with no integer `output_index` or no typed item cannot be placed\n * and is skipped; a final `output` that is not an array of objects is\n * replaced by the items the events built.\n *\n * @module\n */\n\nimport type { XaiResponseShape, XaiUsageShape } from './client.js'\n\n/** Why a streamed call failed outside an HTTP error response. */\ntype XaiStreamFailure =\n | { kind: 'ended_early'; lastEventType: string | undefined }\n | { kind: 'error_event'; code: string | undefined; message: string | undefined }\n | { kind: 'malformed'; detail: string }\n | { kind: 'deadline'; timeoutMs: number }\n | { kind: 'idle'; idleTimeoutMs: number }\n /** The connection failed after output began; `cause` is the transport error. */\n | { kind: 'cut'; detail: string }\n /**\n * The engine's deadline or the caller's signal stopped the call after output\n * began; `cause` is the abort reason.\n */\n | { kind: 'aborted' }\n /**\n * `transport.fetch` answered 200 with a body that is not an event stream.\n * `bodySnippet` is the first 500 characters of that body, secrets redacted.\n */\n | { kind: 'not_event_stream'; contentType: string; bodySnippet?: string }\n\n/**\n * What a stream had delivered when it failed. Output events mean the model was\n * generating (a reasoning call burns tokens before its first visible event), so\n * a retry would repeat that spend and cannot resume it.\n */\ninterface XaiStreamProgress {\n /** True once any output event or the terminal event arrived. */\n progressed: boolean\n /** Characters of text, reasoning summary, arguments and tool input received. */\n outputChars: number\n}\n\n/** What a stream failure carries beside its {@link XaiStreamFailure}. */\ninterface XaiStreamErrorContext {\n progress?: XaiStreamProgress\n /** The terminal response's usage, exact (ticks included), when one arrived. */\n terminalUsage?: XaiUsageShape\n serviceTier?: string\n cause?: unknown\n}\n\n/**\n * A streamed xAI call that failed mid-stream. `classifyXaiError` turns it into a\n * typed `LlmError`. A failure after the terminal event carries the terminal\n * usage (exact); one before it carries only {@link XaiStreamProgress}, from\n * which the adapter derives a lower-bound ESTIMATE: snapshot usage in\n * `response.created` / `response.in_progress` is not used (every live capture\n * had `usage: null`, and a snapshot is by definition a lower bound).\n *\n * @internal\n */\nexport class XaiStreamError extends Error {\n readonly failure: XaiStreamFailure\n readonly progress: XaiStreamProgress\n readonly terminalUsage: XaiUsageShape | undefined\n readonly servedServiceTier: string | undefined\n\n constructor(failure: XaiStreamFailure, context: XaiStreamErrorContext = {}) {\n super(describeFailure(failure, context.cause), { cause: context.cause })\n this.name = 'XaiStreamError'\n this.failure = failure\n this.progress = context.progress ?? { progressed: false, outputChars: 0 }\n this.terminalUsage = context.terminalUsage\n this.servedServiceTier = context.serviceTier\n }\n}\n\nfunction describeFailure(failure: XaiStreamFailure, cause: unknown): string {\n switch (failure.kind) {\n case 'ended_early':\n return `xAI stream ended before response.completed${\n failure.lastEventType !== undefined\n ? ` (last event: ${failure.lastEventType})`\n : ' (no events)'\n }`\n case 'error_event':\n return `xAI stream reported an error${\n failure.code !== undefined ? ` (code \"${failure.code}\")` : ''\n }${failure.message !== undefined ? `: ${failure.message}` : ''}`\n case 'malformed':\n return `xAI stream is malformed: ${failure.detail}`\n case 'deadline':\n return `the stream was still open after the ${failure.timeoutMs} ms request timeout`\n case 'aborted':\n return `xAI stream was stopped after output began${\n cause instanceof Error ? `: ${cause.message}` : ''\n }`\n case 'idle':\n return `the stream sent no bytes (heartbeats included) for ${failure.idleTimeoutMs} ms`\n case 'cut':\n return `xAI stream was cut after output began: ${\n cause instanceof Error ? cause.message : failure.detail\n }`\n case 'not_event_stream':\n return `xAI transport returned a non-event-stream body (content-type \"${failure.contentType}\"); transport.fetch must return the text/event-stream response of the request unchanged`\n }\n}\n\ntype PlainRecord = Record<string, unknown>\n\nfunction isRecord(value: unknown): value is PlainRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (Array.isArray(a)) {\n return (\n Array.isArray(b) && a.length === b.length && a.every((v, i) => deepEqual(v, b[i]))\n )\n }\n if (isRecord(a) && isRecord(b)) {\n const keys = Object.keys(a)\n return (\n keys.length === Object.keys(b).length &&\n keys.every((k) => k in b && deepEqual(a[k], b[k]))\n )\n }\n return false\n}\n\n/** Two items are one item when only their `id` and `status` differ. */\nfunction sameItemContent(a: PlainRecord, b: PlainRecord): boolean {\n const strip = (item: PlainRecord): PlainRecord => {\n const { id: _id, status: _status, ...rest } = item\n return rest\n }\n return deepEqual(strip(a), strip(b))\n}\n\nfunction clone<T>(value: T): T {\n return structuredClone(value)\n}\n\n/** The event-side view of one output item. */\ninterface StreamItem {\n item: PlainRecord\n /** True once `response.output_item.done` delivered the finished item. */\n done: boolean\n}\n\n/** One dispatched SSE frame, as `readSseFrames` yields it. */\nexport interface XaiSseFrame {\n event: string | undefined\n data: string\n}\n\n/** The reduced result of a stream that reached a terminal event. */\ninterface ReducedXaiStream {\n /** The terminal event's response, with `output` reconciled. */\n response: XaiResponseShape\n /** Diagnostics for what reconciliation did; empty when events and final agree. */\n notes: string[]\n /**\n * True when output events arrived before the terminal event (the terminal\n * event itself does not count). A `response.failed` after output began is\n * not retried: the run already spent tokens.\n */\n outputBegan: boolean\n}\n\nconst TERMINAL_EVENTS = new Set([\n 'response.completed',\n 'response.incomplete',\n 'response.failed',\n])\n\n/**\n * The largest event index (`output_index`, `content_index`, `summary_index`,\n * `annotation_index`) the reducer accepts. Real responses have a handful of items\n * and parts; an index beyond this is a broken or hostile upstream, and writing\n * it would make a sparse list millions of entries long.\n */\nconst MAX_STREAM_INDEX = 10_000\n\n/** A string field of an `error` event: at its top level, else in a nested `error` object. */\nfunction errorField(event: PlainRecord, name: string): string | undefined {\n const nested = isRecord(event['error']) ? event['error'] : undefined\n const value = event[name] ?? nested?.[name]\n return typeof value === 'string' ? value : undefined\n}\n\n/** Item types whose content the adapter reads; a divergence in one is reported. */\nconst CONSUMED_ITEM_TYPES = new Set(['message', 'reasoning', 'function_call'])\n\n/** Response-level events that open a stream without any output in them. */\nconst OPENING_EVENTS = new Set([\n 'response.created',\n 'response.in_progress',\n 'response.queued',\n])\n\n/** Numeric usage a response object carries, if it carries token counts. */\nfunction usageOf(response: PlainRecord | undefined): XaiUsageShape | undefined {\n const usage = response?.['usage']\n if (\n isRecord(usage) &&\n typeof usage['input_tokens'] === 'number' &&\n typeof usage['output_tokens'] === 'number'\n ) {\n return usage as XaiUsageShape\n }\n return undefined\n}\n\n/** Characters of model output an item holds: text, summaries, arguments, tool input. */\nfunction itemOutputChars(item: PlainRecord): number {\n let chars = 0\n const text = (value: unknown): void => {\n if (isRecord(value) && typeof value['text'] === 'string')\n chars += value['text'].length\n }\n if (Array.isArray(item['content'])) item['content'].forEach(text)\n if (Array.isArray(item['summary'])) item['summary'].forEach(text)\n if (typeof item['arguments'] === 'string') chars += item['arguments'].length\n if (typeof item['input'] === 'string') chars += item['input'].length\n return chars\n}\n\n/**\n * Folds Responses API stream events into one response object.\n *\n * Feed every frame to {@link pushFrame} (or every parsed event to {@link push})\n * until it returns `true`, then call {@link result}. When the stream ends before\n * a terminal event, call {@link endedEarly} for the error to throw.\n */\nexport class XaiStreamReducer {\n private readonly items = new Map<number, StreamItem>()\n private snapshot: PlainRecord | undefined\n private terminal: { type: string; response: PlainRecord } | undefined\n private lastType: string | undefined\n private progressed = false\n private readonly skipped: string[] = []\n\n /**\n * Applies one SSE frame. A frame with no `data` (a bare `event: keepalive`) or\n * the `[DONE]` sentinel carries nothing and is skipped. A body that is not JSON\n * is a malformed stream; JSON that is not an event is skipped and reported.\n * Returns `true` once the terminal event has been seen.\n */\n pushFrame(frame: XaiSseFrame): boolean {\n if (frame.data === '' || frame.data === '[DONE]') return false\n let parsed: unknown\n try {\n parsed = JSON.parse(frame.data)\n } catch (cause) {\n throw new XaiStreamError(\n {\n kind: 'malformed',\n detail: `an event body is not valid JSON (${\n cause instanceof Error ? cause.message : String(cause)\n })`,\n },\n { ...this.context(), cause },\n )\n }\n if (isRecord(parsed) && typeof parsed['type'] !== 'string') {\n // An `event: error` frame, or a payload that is only an error object, is\n // the stream's error event; anything else typeless is not an event.\n if (frame.event === 'error' || isRecord(parsed['error'])) {\n return this.push({ ...parsed, type: 'error' })\n }\n }\n return this.push(parsed)\n }\n\n /** Applies one event. Returns `true` once the terminal event has been seen. */\n push(event: unknown): boolean {\n if (!isRecord(event) || typeof event['type'] !== 'string') {\n this.skipped.push('an event that has no string `type`')\n return false\n }\n const type = event['type']\n this.lastType = type\n if (TERMINAL_EVENTS.has(type)) {\n const response = event['response']\n if (!isRecord(response)) {\n throw new XaiStreamError(\n { kind: 'malformed', detail: `${type} carries no response object` },\n this.context(),\n )\n }\n this.terminal = { type, response }\n return true\n }\n if (!OPENING_EVENTS.has(type) && type !== 'error' && type.startsWith('response.')) {\n this.progressed = true\n }\n switch (type) {\n case 'response.created':\n case 'response.in_progress':\n if (isRecord(event['response'])) this.snapshot = event['response']\n return false\n case 'error':\n throw new XaiStreamError(\n {\n kind: 'error_event',\n code: errorField(event, 'code'),\n message: errorField(event, 'message'),\n },\n this.context(),\n )\n case 'response.output_item.added':\n case 'response.output_item.done': {\n const rawIndex = event['output_index']\n const index =\n typeof rawIndex === 'number' && Number.isInteger(rawIndex) && rawIndex >= 0\n ? this.index(rawIndex, 'output_index')\n : undefined\n const item = event['item']\n if (index === undefined || !isRecord(item) || typeof item['type'] !== 'string') {\n this.skipped.push(`a ${type} event with no integer output_index or typed item`)\n return false\n }\n this.items.set(index, { item: clone(item), done: type.endsWith('.done') })\n return false\n }\n default:\n this.applyDelta(type, event)\n return false\n }\n }\n\n /**\n * An event index, or `undefined` when the event has none or it is not a\n * non-negative integer (the event is then skipped, noted). An index above\n * {@link MAX_STREAM_INDEX} is a malformed stream, not a value to write.\n */\n private index(value: unknown, name: string): number | undefined {\n if (typeof value !== 'number') return undefined\n if (!Number.isInteger(value) || value < 0) {\n this.skipped.push(`an event whose ${name} is not a non-negative integer`)\n return undefined\n }\n if (value > MAX_STREAM_INDEX) {\n throw new XaiStreamError(\n {\n kind: 'malformed',\n detail: `${name} ${value} is above the ${MAX_STREAM_INDEX} this client accepts`,\n },\n this.context(),\n )\n }\n return value\n }\n\n /** The error for a stream that ended without a terminal event. */\n endedEarly(): XaiStreamError {\n return new XaiStreamError(\n { kind: 'ended_early', lastEventType: this.lastType },\n this.context(),\n )\n }\n\n /** What the stream had delivered so far. */\n progress(): XaiStreamProgress {\n let outputChars = 0\n for (const entry of this.items.values()) outputChars += itemOutputChars(entry.item)\n return { progressed: this.progressed || this.terminal !== undefined, outputChars }\n }\n\n /** The progress, the terminal usage when one arrived, and the tier, for a failure. */\n context(): Omit<XaiStreamErrorContext, 'cause'> {\n const terminalUsage = usageOf(this.terminal?.response)\n const tier = (this.terminal?.response ?? this.snapshot)?.['service_tier']\n return {\n progress: this.progress(),\n ...(terminalUsage !== undefined ? { terminalUsage } : {}),\n ...(typeof tier === 'string' && tier.length > 0 ? { serviceTier: tier } : {}),\n }\n }\n\n /**\n * The terminal response with its output reconciled against the events. Never\n * fails once a terminal event with a response arrived.\n *\n * @throws XaiStreamError only when the stream has no terminal event yet.\n */\n result(): ReducedXaiStream {\n const terminal = this.terminal\n if (terminal === undefined) throw this.endedEarly()\n const response = terminal.response\n if (terminal.type === 'response.failed') {\n // The event type is the authority for failure: a failed event whose\n // response object forgot to say so must still be a failure downstream.\n const status = response['status']\n return {\n response: {\n ...response,\n status: status === 'failed' || status === 'cancelled' ? status : 'failed',\n } as unknown as XaiResponseShape,\n notes: [],\n outputBegan: this.progressed,\n }\n }\n // Likewise `response.incomplete` is an incomplete response whatever its object says.\n const status =\n terminal.type === 'response.incomplete' ? 'incomplete' : response['status']\n const { output, notes } = this.reconcile(response['output'], status)\n return {\n response: { ...response, status, output } as unknown as XaiResponseShape,\n notes: [...this.skippedNotes(), ...notes],\n outputBegan: this.progressed,\n }\n }\n\n private skippedNotes(): string[] {\n if (this.skipped.length === 0) return []\n const counts = new Map<string, number>()\n for (const what of this.skipped) counts.set(what, (counts.get(what) ?? 0) + 1)\n return [...counts].map(\n ([what, n]) =>\n `xai: skipped ${n} stream event(s) that could not be used (${what}); the final response was used for them.`,\n )\n }\n\n /**\n * Deltas build up the item an `added` event opened. A delta for an item the\n * stream never opened is ignored: the terminal object or a `done` event still\n * carries the item, and a lost delta must not fail a billed call.\n */\n private applyDelta(type: string, event: PlainRecord): void {\n const entry = this.items.get(\n typeof event['output_index'] === 'number' ? event['output_index'] : -1,\n )\n if (entry === undefined) return\n const item = entry.item\n const contentIndex = this.index(event['content_index'], 'content_index')\n const summaryIndex = this.index(event['summary_index'], 'summary_index')\n const textAt = (\n list: unknown,\n index: unknown,\n defaults: PlainRecord,\n ): PlainRecord => {\n if (!Array.isArray(list) || typeof index !== 'number') return {}\n const existing: unknown = list[index]\n if (isRecord(existing)) return existing\n const created = { ...defaults }\n list[index] = created\n return created\n }\n const content = (): unknown[] => {\n if (!Array.isArray(item['content'])) item['content'] = []\n return item['content'] as unknown[]\n }\n const summary = (): unknown[] => {\n if (!Array.isArray(item['summary'])) item['summary'] = []\n return item['summary'] as unknown[]\n }\n const append = (target: PlainRecord, key: string, delta: unknown): void => {\n if (typeof delta !== 'string') return\n target[key] = `${typeof target[key] === 'string' ? target[key] : ''}${delta}`\n }\n switch (type) {\n case 'response.content_part.added':\n case 'response.content_part.done':\n if (typeof contentIndex === 'number' && isRecord(event['part'])) {\n content()[contentIndex] = clone(event['part'])\n }\n return\n case 'response.output_text.delta':\n append(\n textAt(content(), contentIndex, { type: 'output_text', text: '' }),\n 'text',\n event['delta'],\n )\n return\n case 'response.output_text.done': {\n const part = textAt(content(), contentIndex, { type: 'output_text', text: '' })\n if (typeof event['text'] === 'string') part['text'] = event['text']\n return\n }\n case 'response.output_text.annotation.added': {\n const part = textAt(content(), contentIndex, { type: 'output_text', text: '' })\n if (!Array.isArray(part['annotations'])) part['annotations'] = []\n const index = this.index(event['annotation_index'], 'annotation_index')\n if (index !== undefined && event['annotation'] !== undefined) {\n ;(part['annotations'] as unknown[])[index] = clone(event['annotation'])\n }\n return\n }\n case 'response.reasoning_summary_part.added':\n case 'response.reasoning_summary_part.done':\n if (typeof summaryIndex === 'number' && isRecord(event['part'])) {\n summary()[summaryIndex] = clone(event['part'])\n }\n return\n case 'response.reasoning_summary_text.delta':\n append(\n textAt(summary(), summaryIndex, { type: 'summary_text', text: '' }),\n 'text',\n event['delta'],\n )\n return\n case 'response.reasoning_summary_text.done': {\n const part = textAt(summary(), summaryIndex, { type: 'summary_text', text: '' })\n if (typeof event['text'] === 'string') part['text'] = event['text']\n return\n }\n case 'response.function_call_arguments.delta':\n append(item, 'arguments', event['delta'])\n return\n case 'response.function_call_arguments.done':\n if (typeof event['arguments'] === 'string') item['arguments'] = event['arguments']\n return\n // xAI streams the input of a server tool call (x_search) as a custom tool call.\n case 'response.custom_tool_call_input.delta':\n append(item, 'input', event['delta'])\n return\n case 'response.custom_tool_call_input.done':\n if (typeof event['input'] === 'string') item['input'] = event['input']\n return\n default:\n // `response.web_search_call.*`, heartbeats and event types this\n // version does not know carry nothing the item events do not.\n return\n }\n }\n\n /** The items the events built, in output order, finished for a response that ended. */\n private eventItems(responseStatus: unknown): PlainRecord[] {\n return [...this.items.entries()]\n .sort(([a], [b]) => a - b)\n .map(([, entry]) => {\n const item = clone(entry.item)\n if (!entry.done) item['status'] = finishedStatus(responseStatus)\n return item\n })\n }\n\n private reconcile(\n finalOutput: unknown,\n responseStatus: unknown,\n ): { output: unknown[]; notes: string[] } {\n if (finalOutput !== undefined && !Array.isArray(finalOutput)) {\n return {\n output: this.eventItems(responseStatus),\n notes: [\n 'xai: the final response `output` is not an array; the output items were built from the stream events.',\n ],\n }\n }\n const finalItems: PlainRecord[] = []\n let dropped = 0\n for (const item of finalOutput ?? []) {\n if (isRecord(item)) finalItems.push(clone(item))\n else dropped++\n }\n const notes: string[] = []\n if (dropped > 0) {\n notes.push(\n `xai: dropped ${dropped} non-object item(s) from the final response \\`output\\`.`,\n )\n }\n\n // Real xAI responses repeat an id within one `output` (two `message` items\n // sharing one `msg_` id, two `reasoning` items sharing one `rs_` id), so an\n // id alone is not a key. Items are grouped by id (or by type when they have\n // none) and the groups are aligned from the END: the final object omits\n // earlier items of a group, never later ones.\n const groupOf = (item: PlainRecord): string => {\n const id = item['id']\n return typeof id === 'string' && id.length > 0\n ? `id:${id}`\n : `anon:${String(item['type'])}`\n }\n const labelOf = (item: PlainRecord): string =>\n typeof item['id'] === 'string' && item['id'].length > 0\n ? `${String(item['type'])} ${item['id']}`\n : String(item['type'])\n\n const finalGroups = new Map<string, PlainRecord[]>()\n for (const item of finalItems) {\n const group = groupOf(item)\n finalGroups.set(group, [...(finalGroups.get(group) ?? []), item])\n }\n const eventGroups = new Map<string, Array<[number, StreamItem]>>()\n for (const entry of [...this.items.entries()].sort(([a], [b]) => a - b)) {\n const group = groupOf(entry[1].item)\n eventGroups.set(group, [...(eventGroups.get(group) ?? []), entry])\n }\n\n const bound = new Set<PlainRecord>()\n const unbound: Array<[number, StreamItem]> = []\n for (const [group, entries] of eventGroups) {\n const finals = finalGroups.get(group) ?? []\n // The final object omits items from either end of a group, so the group\n // is aligned from the start or from the end, whichever pairs more items\n // of identical content (a tie goes to the end: the final object omits\n // earlier items, never later ones, in every capture).\n const endOffset = finals.length - entries.length\n const matches = (offset: number): number =>\n entries.filter(([, streamed], i) => {\n const finalItem = finals[i + offset]\n return finalItem !== undefined && sameItemContent(finalItem, streamed.item)\n }).length\n const offset = matches(0) > matches(endOffset) ? 0 : endOffset\n entries.forEach((entry, i) => {\n const finalItem = finals[i + offset]\n if (finalItem === undefined) {\n unbound.push(entry)\n return\n }\n bound.add(finalItem)\n const [, streamed] = entry\n if (finalItem['type'] !== streamed.item['type']) {\n notes.push(\n `xai: output item ${labelOf(finalItem)} is a \"${String(streamed.item['type'])}\" in the stream and a \"${String(finalItem['type'])}\" in the final response; the final response is used.`,\n )\n return\n }\n if (!streamed.done) return\n const filled: string[] = []\n const diverged: string[] = []\n for (const [field, value] of Object.entries(streamed.item)) {\n if (!(field in finalItem)) {\n finalItem[field] = clone(value)\n filled.push(field)\n } else if (!deepEqual(finalItem[field], value)) {\n diverged.push(field)\n }\n }\n if (filled.length > 0) {\n notes.push(\n `xai: output item ${labelOf(finalItem)} lacked field(s) [${filled.join(', ')}] in the final response; taken from the stream.`,\n )\n }\n // Server tool items (a search call) are replayed verbatim from the final\n // object and the adapter reads nothing in them; xAI's final object also\n // reports a search call's `action.sources` cumulatively for the whole\n // run (live, 2026-10-03), so a difference there is not news.\n if (diverged.length > 0 && CONSUMED_ITEM_TYPES.has(String(finalItem['type']))) {\n notes.push(\n `xai: output item ${labelOf(finalItem)} differs between the stream and the final response in field(s) [${diverged.join(', ')}]; the final response is used.`,\n )\n }\n })\n }\n\n // An item the final object lacks under its id may still be there under\n // another one: the same content is one item, not a second.\n const spare = finalItems.filter((item) => !bound.has(item))\n const insertions: Array<{ index: number; item: PlainRecord }> = []\n const rebuilt: string[] = []\n const assembled: string[] = []\n for (const [index, entry] of unbound.sort(([a], [b]) => a - b)) {\n const twin = spare.findIndex((item) => sameItemContent(item, entry.item))\n if (twin !== -1) {\n spare.splice(twin, 1)\n continue\n }\n const item = clone(entry.item)\n if (!entry.done) {\n // Never finished by an `output_item.done` and absent from the final\n // object: what the deltas built is all there is. The response ended, so\n // the item is finished too (a replayed `in_progress` item is not valid).\n item['status'] = finishedStatus(responseStatus)\n assembled.push(labelOf(item))\n } else {\n rebuilt.push(labelOf(item))\n }\n insertions.push({ index, item })\n }\n\n const output: PlainRecord[] = [...finalItems]\n for (const { index, item } of insertions) {\n output.splice(Math.min(index, output.length), 0, item)\n }\n if (rebuilt.length > 0) {\n notes.push(\n `xai: the final response lacked ${rebuilt.length} output item(s) [${rebuilt.join(', ')}] that the stream completed; they were rebuilt from the stream events.`,\n )\n }\n if (assembled.length > 0) {\n notes.push(\n `xai: the final response lacked ${assembled.length} output item(s) [${assembled.join(', ')}] that the stream never completed; they were assembled from the stream deltas and may lack provider-only fields.`,\n )\n }\n return { output, notes }\n }\n}\n\nfunction finishedStatus(responseStatus: unknown): string {\n return responseStatus === 'incomplete' ? 'incomplete' : 'completed'\n}\n","/**\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, redactSecrets } from '@gullabs/core'\nimport type { AuthMaterial } from '@gullabs/core'\nimport { readSseFrames } from './sse.js'\nimport { XaiStreamError, XaiStreamReducer } from './stream.js'\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 * a private upload made through {@link XaiFileStore}. Attaching one implicitly\n * enables xAI's `attachment_search` agentic tool.\n */\nexport interface XaiInputFilePart {\n type: 'input_file'\n file_id: 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. */\ninterface XaiFunctionCallInputItem {\n type: 'function_call'\n call_id: string\n name: string\n arguments: string\n}\n\n/** Live-verified store:false replay item. */\ninterface 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/**\n * Full wire history for stateless continuation (`continuation: 'state'`),\n * scoped under the provider key and bound to the requested model string.\n */\nexport interface XaiReplayState {\n xai: { model: string; 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 interface XaiTextFormat {\n type: 'json_schema'\n name: string\n schema: unknown\n strict: boolean\n}\n\n/**\n * Parameters for `client.responses.create`.\n * Structurally modeled from live-captured xAI Responses API fixtures\n * (see docs/archive/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 max_turns?: number\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/**\n * A refusal content segment of a `type: 'message'` output item (the OpenAI\n * Responses grammar xAI mirrors; not yet captured from xAI).\n */\nexport interface XaiRefusalPart {\n type: 'refusal'\n refusal: string\n}\n\n/**\n * A `type: 'message'` item in `output`. A part of any other type may arrive at\n * runtime; the adapter ignores it with a warning.\n */\nexport interface XaiMessageOutputItem {\n type: 'message'\n id?: string\n role?: string\n status?: string\n content: Array<XaiOutputTextPart | XaiRefusalPart>\n}\n\n/** Server-tool or function-call output items we do not collapse as messages. */\ninterface 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\"; the API\n * also documents \"failed\" and \"cancelled\" (never captured). Kept as a plain\n * `string` since xAI may add further status values over time.\n */\n status: string\n incomplete_details?: { reason?: string } | null\n /**\n * Error object the Responses API puts on a response that failed after the\n * HTTP 200 (documented shape, never captured).\n */\n error?: { code?: string; message?: 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?: XaiRequestOptions,\n ): Promise<XaiResponseShape>\n }\n}\n\n/**\n * What the HTTP response of a successful `responses.create` says outside its\n * body: xAI's request id (quote it in a support ticket) and the remaining-quota\n * headers.\n */\nexport interface XaiResponseMeta {\n /** The `x-request-id` response header. Absent when xAI sent none. */\n requestId?: string\n /**\n * Response headers that state remaining quota (`x-ratelimit-remaining-*`, the names xAI sent in\n * every captured response), lower-cased name to the verbatim value. Absent when\n * the response carried none.\n */\n rateLimitRemaining?: Record<string, string>\n /**\n * What reconciling the streamed events with the final response object did\n * (ADR-040): items the final object lacked and the stream completed, fields\n * taken from the stream, fields that differed. Absent when they agreed. The\n * adapter reports each as a warning.\n */\n streamNotes?: string[]\n /**\n * True when output events arrived before the response's terminal event. A\n * `response.failed` after output began is not retried (the run already spent\n * tokens). Set by the real client; absent from a fake one.\n */\n streamProgressed?: boolean\n}\n\n/** Per-request options the adapter passes to `responses.create`. */\nexport interface XaiRequestOptions {\n signal?: AbortSignal\n /**\n * The request's whole-call deadline in milliseconds. The real client sends\n * the request as a stream (ADR-040) and applies it twice: as the SDK's\n * `timeout`, which for a stream covers only the wait for response headers,\n * and as its own timer over the remaining stream, so the deadline bounds the\n * whole call. It does not move Node's header and body timers; see\n * {@link XaiTransport}.\n */\n timeout?: number\n /**\n * Called with the response's {@link XaiResponseMeta} once the response\n * is complete, before `create` resolves. Only the real client calls it; a\n * fake client may ignore it.\n */\n onResponse?: (meta: XaiResponseMeta) => void\n}\n\n/** The headers {@link XaiResponseMeta.rateLimitRemaining} keeps. */\nfunction isRemainingQuotaHeader(name: string): boolean {\n return name.startsWith('x-ratelimit-remaining')\n}\n\n/**\n * Reads {@link XaiResponseMeta} from a response's headers. `requestId` is the\n * SDK's own reading of `x-request-id` when it has one.\n *\n * @internal\n */\nexport function readXaiResponseMeta(\n headers: Headers,\n sdkRequestId?: string | null,\n): XaiResponseMeta {\n const requestId = sdkRequestId ?? headers.get('x-request-id') ?? undefined\n const remaining: Record<string, string> = {}\n headers.forEach((value, name) => {\n const lower = name.toLowerCase()\n if (isRemainingQuotaHeader(lower)) remaining[lower] = value\n })\n return {\n ...(requestId !== undefined && requestId !== '' ? { requestId } : {}),\n ...(Object.keys(remaining).length > 0 ? { rateLimitRemaining: remaining } : {}),\n }\n}\n\n/**\n * Host-supplied HTTP transport for every `responses.create` call.\n *\n * Node's `fetch` enforces its own 300 s header and body timers, independent of\n * the SDK `timeout`. A call whose response headers take longer than that (a\n * tool-using call that streams nothing for minutes) is killed unless the host\n * passes a `fetch` whose dispatcher raises those timers (for example undici's\n * `fetch` with `new Agent({ headersTimeout, bodyTimeout })` in\n * `fetchOptions.dispatcher`). See ADR-032 and the package README.\n *\n * `fetch` must return the request's own `text/event-stream` response: the call\n * always streams (ADR-040), and a `fetch` that buffers the answer into a JSON\n * body (a record/replay or caching wrapper) fails every call with a non-retryable\n * error naming the cause.\n */\nexport interface XaiTransport {\n fetch: typeof fetch\n /**\n * Extra `fetch` init (for example `{ dispatcher }`). `headers`, `signal`,\n * `body` and `method` belong to the request and are rejected.\n */\n fetchOptions?: Omit<RequestInit, 'headers' | 'signal' | 'body' | 'method'>\n /**\n * Ends a stream that sends no bytes at all (heartbeat comments included) for\n * this many milliseconds, as a non-retryable `timeout` with\n * `reason: 'transport_timeout'`. Off by default. The request deadline bounds\n * the whole call; this bounds a half-open connection (a NAT drop with no\n * reset) that the deadline would hold for up to an hour. Integer, at least 1.\n * Set it above the longest quiet gap you expect: live reasoning runs showed a\n * longest gap of 15 s.\n */\n idleTimeoutMs?: number\n}\n\n/** `fetchOptions` keys the SDK owns; a host-supplied value would override the request. */\nexport const XAI_RESERVED_FETCH_OPTION_KEYS = [\n 'headers',\n 'signal',\n 'body',\n 'method',\n] as const\n\n/**\n * SDK deadline for a request with no `timeoutMs`: one hour. xAI reasoning and\n * agentic calls can run for many minutes; the SDK default (10 minutes) would\n * cut them off.\n */\nexport const XAI_DEFAULT_TIMEOUT_MS = 3_600_000\n\n/**\n * Added to `timeoutMs` for the SDK deadline, so the engine's own deadline\n * (armed at exactly `timeoutMs`) always fires first and the caller sees the\n * engine's clean timeout rather than a raw SDK error.\n */\nexport const XAI_TIMEOUT_BUFFER_MS = 5_000\n\n/**\n * Largest `timeoutMs` the grok config schemas accept. Node timers fire after\n * 1 ms (with a warning) above 2^31 - 1 ms, and the SDK deadline is `timeoutMs`\n * plus {@link XAI_TIMEOUT_BUFFER_MS}; a larger value is rejected, not clamped.\n */\nexport const XAI_MAX_TIMEOUT_MS = 2_147_483_647 - XAI_TIMEOUT_BUFFER_MS\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 * @param transport - Optional host-supplied `fetch` and `fetchOptions` passed to\n * the SDK client unchanged.\n */\nexport async function buildXaiClient(\n auth: AuthMaterial,\n transport?: XaiTransport,\n): 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 ...(transport !== undefined\n ? {\n fetch: transport.fetch,\n ...(transport.fetchOptions !== undefined\n ? { fetchOptions: transport.fetchOptions }\n : {}),\n }\n : {}),\n })\n const idleTimeoutMs = transport?.idleTimeoutMs\n\n return {\n responses: {\n async create(\n params: XaiResponseCreateParams,\n options?: XaiRequestOptions,\n ): Promise<XaiResponseShape> {\n // `onResponse` is ours, not an SDK request option.\n const { onResponse, timeout, signal } = options ?? {}\n // The call always streams (ADR-040): the stream keeps the connection\n // busy, so Node's 300 s body timer never sees a quiet gap, and the\n // events rebuild what the terminal object can omit. Cast needed: our\n // structural types are subsets of the real SDK types, and the real\n // SDK's types do not exactly match xAI's actual response shape (see\n // module doc comment). `asResponse()` hands over the raw HTTP response:\n // the SDK still sends the request and turns an HTTP error status into\n // its `APIError`, but the body is read here (see `sse.ts`).\n type Pending = { asResponse(): Promise<Response> }\n const send = (p: unknown, o: unknown): Pending =>\n (client.responses.create as unknown as (p: unknown, o: unknown) => Pending)(\n p,\n o,\n )\n // The SDK `timeout` stops at the response headers for a stream, so the\n // call gets its own controller: the caller's signal is forwarded\n // (reason included), and a timer started once the headers arrive\n // aborts it at the same whole-call deadline.\n const controller = new AbortController()\n const forwardAbort = (): void => {\n controller.abort(signal?.reason)\n }\n if (signal?.aborted === true) forwardAbort()\n else signal?.addEventListener('abort', forwardAbort, { once: true })\n const startedAt = performance.now()\n let deadlineTimer: ReturnType<typeof setTimeout> | undefined\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n const ended = { deadline: false, idle: false }\n const reducer = new XaiStreamReducer()\n const failure = (): XaiStreamError | undefined => {\n if (ended.deadline) {\n return new XaiStreamError(\n { kind: 'deadline', timeoutMs: timeout ?? 0 },\n reducer.context(),\n )\n }\n if (ended.idle) {\n return new XaiStreamError(\n { kind: 'idle', idleTimeoutMs: idleTimeoutMs ?? 0 },\n reducer.context(),\n )\n }\n return undefined\n }\n /** Why the call stopped when it did not reach a terminal event, if known. */\n const stopped = (): unknown => {\n const ours = failure()\n if (ours !== undefined) return ours\n if (signal?.aborted === true) return abortFailure(signal, reducer)\n return undefined\n }\n try {\n const response = await send(\n { ...params, stream: true },\n {\n signal: controller.signal,\n headers: { accept: 'text/event-stream' },\n ...(timeout !== undefined ? { timeout } : {}),\n },\n ).asResponse()\n if (timeout !== undefined) {\n deadlineTimer = setTimeout(\n () => {\n ended.deadline = true\n controller.abort()\n },\n Math.max(0, timeout - (performance.now() - startedAt)),\n )\n }\n const touch = (): void => {\n if (idleTimeoutMs === undefined) return\n if (idleTimer !== undefined) clearTimeout(idleTimer)\n idleTimer = setTimeout(() => {\n ended.idle = true\n controller.abort()\n }, idleTimeoutMs)\n }\n touch()\n const aborted = new Promise<never>((_resolve, reject) => {\n const onAbort = (): void => {\n reject(new Error('aborted'))\n }\n if (controller.signal.aborted) onAbort()\n else controller.signal.addEventListener('abort', onAbort, { once: true })\n })\n aborted.catch(() => undefined)\n const contentType = response.headers.get('content-type')\n if (contentType !== null && !/text\\/event-stream/i.test(contentType)) {\n const bodySnippet = await readBodySnippet(response.body, aborted)\n // `readBodySnippet` swallows a read that was cut short, so a deadline or an\n // abort that ended the read would otherwise be reported as the unexpected\n // body. The stop reason is the answer, and comes first.\n const why = stopped()\n if (why instanceof Error) throw why\n throw new XaiStreamError(\n {\n kind: 'not_event_stream',\n contentType,\n ...(bodySnippet !== undefined ? { bodySnippet } : {}),\n },\n {\n cause: {\n contentType,\n ...(bodySnippet !== undefined ? { bodySnippet } : {}),\n },\n },\n )\n }\n if (response.body === null) throw reducer.endedEarly()\n let terminal = false\n try {\n for await (const frame of readSseFrames(response.body, {\n onChunk: touch,\n aborted,\n })) {\n if (reducer.pushFrame(frame)) {\n terminal = true\n break\n }\n }\n } catch (err) {\n const why: unknown = stopped() ?? streamFailure(err, reducer)\n throw why\n }\n if (!terminal) {\n const why: unknown = stopped() ?? reducer.endedEarly()\n throw why\n }\n const { response: reduced, notes, outputBegan } = reducer.result()\n onResponse?.({\n ...readXaiResponseMeta(response.headers),\n ...(notes.length > 0 ? { streamNotes: notes } : {}),\n streamProgressed: outputBegan,\n })\n return reduced\n } finally {\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer)\n if (idleTimer !== undefined) clearTimeout(idleTimer)\n signal?.removeEventListener('abort', forwardAbort)\n }\n },\n },\n }\n}\n\n/**\n * The error an aborted caller signal ends in: its reason when that is an\n * `LlmError` (the engine's deadline), else an `AbortError` carrying it.\n */\nfunction abortError(signal: AbortSignal): unknown {\n const reason: unknown = signal.reason\n if (reason instanceof LlmError) return reason\n return Object.assign(new Error('Request was aborted.'), {\n name: 'AbortError',\n cause: reason,\n })\n}\n\n/**\n * The failure of a call the engine's deadline or the caller's signal stopped\n * while it streamed. Once output began it is an {@link XaiStreamError} of kind\n * `aborted` carrying what was received (so the adapter can attach the usage\n * ESTIMATE) with the abort reason as `cause`; before that it is the plain abort\n * error, which carries no usage and is booked unpriced.\n */\nfunction abortFailure(signal: AbortSignal, reducer: XaiStreamReducer): unknown {\n if (!reducer.progress().progressed) return abortError(signal)\n return new XaiStreamError(\n { kind: 'aborted' },\n { ...reducer.context(), cause: signal.reason },\n )\n}\n\n/** Characters of an unexpected 200 body kept in the error's cause. */\nconst BODY_SNIPPET_CHARS = 500\n\n/**\n * The start of a body that was not an event stream, for the error's `cause`:\n * at most {@link BODY_SNIPPET_CHARS} characters, secrets redacted. A body that\n * will not read (aborted, reset) gives no snippet. Cancels the body.\n */\nasync function readBodySnippet(\n body: ReadableStream<Uint8Array> | null,\n aborted: Promise<never>,\n): Promise<string | undefined> {\n if (body === null) return undefined\n const reader = body.getReader()\n const decoder = new TextDecoder('utf-8')\n let text = ''\n try {\n while (text.length < 2 * BODY_SNIPPET_CHARS) {\n const chunk = await Promise.race([reader.read(), aborted])\n if (chunk.done) break\n text += decoder.decode(chunk.value, { stream: true })\n }\n } catch {\n // An unreadable body only loses the snippet.\n } finally {\n reader.cancel().catch(() => undefined)\n }\n // Redacted before it is cut, so a cut never leaves half a secret behind.\n const snippet = redactSecrets(text).slice(0, BODY_SNIPPET_CHARS)\n return snippet.length > 0 ? snippet : undefined\n}\n\n/**\n * What an error thrown while reading the stream means. A transport failure after\n * output began is an {@link XaiStreamError} of kind `cut` (the raw error is its\n * `cause`): the model was generating, so a retry would repeat that spend. A\n * failure before any output is returned untouched, and classifies as it always\n * has (a reset connection is a retryable `server` error, an undici timer a\n * transport timeout).\n */\nfunction streamFailure(err: unknown, reducer: XaiStreamReducer): unknown {\n if (err instanceof XaiStreamError) return err\n if (!reducer.progress().progressed) return err\n return new XaiStreamError(\n { kind: 'cut', detail: err instanceof Error ? err.message : String(err) },\n { ...reducer.context(), cause: err },\n )\n}\n","/**\n * Token limits and admitted input media types for the registered xAI models,\n * read from xAI's own documentation (re-read 2026-10-03).\n *\n * One table feeds both the descriptors (`limits`, `inputMimeTypes`) and the\n * per-model config schemas (`maxOutputTokens` is capped only when a number is\n * documented), so a descriptor and its schema cannot drift.\n *\n * Sources, all read 2026-10-03:\n *\n * - `https://docs.x.ai/developers/models/<model-id>` (grok-4.5, grok-4.6,\n * grok-4.7): \"Context window: 500,000 tokens\", \"Modalities: text, image →\n * text\". No page states a maximum output size, so `maxOutputTokens` is\n * `null` (see {@link ModelLimits.maxOutputTokens}): no figure is invented and\n * the schema applies no cap. xAI has been seen to accept far larger values\n * (live 2026-10-02: 150,000, and 100,000,000 earlier); the docs name 128,000\n * only as the default when the field is unset.\n * - `https://docs.x.ai/developers/model-capabilities/images/understanding`:\n * \"Supported image file types: jpg/jpeg or png\"; WebP is not listed. Maximum\n * image size 20 MiB. The page names file extensions, not media types. The IANA\n * types for them are `image/jpeg` and `image/png`; `image/jpg` is not a\n * registered media type and the page does not list it as a media type, so it\n * is rejected rather than treated as an alias.\n *\n * @module\n */\n\nimport type { ModelLimits } from '@gullabs/core'\n\ntype XaiModelId = 'grok-4.5' | 'grok-4.6' | 'grok-4.7'\n\n/** One frozen object per model: no descriptor can change another's limits. */\nconst grok4Limits = (): ModelLimits =>\n Object.freeze({ contextWindow: 500_000, maxOutputTokens: null })\n\nexport const XAI_MODEL_LIMITS: Readonly<Record<XaiModelId, ModelLimits>> = {\n 'grok-4.5': grok4Limits(),\n 'grok-4.6': grok4Limits(),\n 'grok-4.7': grok4Limits(),\n}\n\n/** Media types xAI accepts for image input. WebP and `image/jpg` are not among them. */\nexport const XAI_INPUT_MIME_TYPES: readonly string[] = Object.freeze([\n 'image/jpeg',\n 'image/png',\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. The one exception is the cross-field rule that\n * `providerOptions.xai.searchBudget` needs the tools it counts: a `superRefine`\n * on the provider options, which JSON Schema cannot express.\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\nconst 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\nconst 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 */\nconst 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\nconst maxWebSearchCalls = z\n .number()\n .int()\n .min(1)\n .meta({\n title: 'Max Web Search Calls',\n description:\n \"Ceiling on web_search calls. Requires a web_search tool. Compared with xAI's \" +\n 'reported counter after the call.',\n })\n\nconst maxXItems = z\n .number()\n .int()\n .min(1)\n .meta({\n title: 'Max X Items',\n description:\n 'Ceiling on X posts plus users fetched. Requires an x_search tool. Compared ' +\n \"with xAI's reported counters after the call.\",\n })\n\n/**\n * At least one ceiling, as a union of shapes so the derived JSON Schema says it\n * exactly: `{}` is not a budget.\n */\nconst XaiSearchBudgetSchema = z\n .union([\n z.strictObject({ maxWebSearchCalls, maxXItems: maxXItems.optional() }),\n z.strictObject({ maxWebSearchCalls: maxWebSearchCalls.optional(), maxXItems }),\n ])\n .meta({\n title: 'Search Budget',\n description:\n 'Observed after the call, never sent to xAI (which has no per-call search ' +\n 'ceiling). Over budget: a warning and usage.details.search_budget_exceeded = 1; ' +\n 'the already-billed result is still returned. Needs at least one ceiling, and ' +\n 'the tool each ceiling counts (maxWebSearchCalls: web_search, maxXItems: ' +\n 'x_search) in tools.',\n })\n\n/**\n * `toolChoice` and `maxTurns` need a non-empty `tools`; the adapter enforces\n * that dependency. Encoding it here as a union of shapes made zod report an\n * invalid `toolChoice` value as an unrecognized key.\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 toolChoice: z\n .enum(['auto', 'required', 'none'])\n .optional()\n .meta({\n title: 'Server Tool Choice',\n description:\n 'xAI Responses `tool_choice` for the server-side search tools; `required` ' +\n 'forces at least one search, `none` disables them. Requires `tools`. Cannot ' +\n 'be combined with function tools, file attachments or the request-level ' +\n 'toolChoice.',\n }),\n maxTurns: z\n .number()\n .int()\n .min(1)\n .optional()\n .meta({\n title: 'Max Turns',\n description:\n 'xAI Responses `max_turns`: cap on agentic tool-calling turns for the ' +\n 'server-side search tools. Requires `tools`. A turn can run several ' +\n 'searches. Not enforced by xAI as of 2026-10-02.',\n }),\n searchBudget: XaiSearchBudgetSchema.optional(),\n })\n .superRefine((options, ctx) => {\n // `searchBudget` counts what the search tools did, so each ceiling needs its\n // tool. Stated here, not left to the adapter, so the schema accepts exactly\n // what the adapter does and a bad budget never reaches a ledger row.\n const budget = options.searchBudget\n if (budget === undefined) return\n const kinds = new Set((options.tools ?? []).map((tool) => tool.type))\n const need = (ceiling: 'maxWebSearchCalls' | 'maxXItems', tool: string): void => {\n if (\n budget[ceiling] !== undefined &&\n !kinds.has(tool as 'web_search' | 'x_search')\n ) {\n ctx.addIssue({\n code: 'custom',\n path: ['searchBudget', ceiling],\n message: `searchBudget.${ceiling} requires ${tool === 'x_search' ? 'an' : 'a'} ${tool} tool in tools.`,\n })\n }\n }\n need('maxWebSearchCalls', 'web_search')\n need('maxXItems', 'x_search')\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 { maxOutputTokensSchema } from '@gullabs/core'\nimport { z } from 'zod'\n\nimport { XAI_MODEL_LIMITS } from '../model-limits.js'\nimport { XAI_MAX_TIMEOUT_MS } from '../client.js'\nimport { XaiProviderOptionsSchema } from './tools.js'\n\nexport const Grok45ConfigSchema = z\n .strictObject({\n temperature: z.number().min(0).max(2).optional().meta({\n title: 'Temperature',\n description:\n 'Sampling temperature forwarded verbatim to grok-4.5, from 0 to 2 (the range xAI documents for the Responses API: \"between 0 and 2\"); a value outside it is rejected.',\n }),\n topP: z.number().min(0).max(1).optional().meta({\n title: 'Top P',\n description:\n 'Nucleus sampling probability forwarded verbatim to grok-4.5, from 0 to 1 (xAI documents no range for it; a probability mass outside 0 to 1 is meaningless); a value outside it is rejected.',\n }),\n maxOutputTokens: maxOutputTokensSchema(XAI_MODEL_LIMITS['grok-4.5'])\n .optional()\n .meta({\n title: 'Max Output Tokens',\n description:\n 'Maximum output token cap for grok-4.5, including reasoning tokens. No ' +\n 'ceiling is applied: xAI documents no output limit and has accepted very ' +\n \"large values (live-verified). Truncation surfaces as finishReason:'length', \" +\n '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().max(XAI_MAX_TIMEOUT_MS).optional().meta({\n title: 'Timeout',\n description: 'Logical request timeout in milliseconds (at most 2147478647).',\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 { maxOutputTokensSchema } from '@gullabs/core'\nimport { z } from 'zod'\n\nimport { XAI_MODEL_LIMITS } from '../model-limits.js'\nimport { XAI_MAX_TIMEOUT_MS } from '../client.js'\nimport { XaiProviderOptionsSchema } from './tools.js'\n\nexport const Grok46ConfigSchema = z\n .strictObject({\n temperature: z.number().min(0).max(2).optional().meta({\n title: 'Temperature',\n description:\n 'Sampling temperature forwarded verbatim to grok-4.6, from 0 to 2 (the range xAI documents for the Responses API: \"between 0 and 2\"); a value outside it is rejected.',\n }),\n topP: z.number().min(0).max(1).optional().meta({\n title: 'Top P',\n description:\n 'Nucleus sampling probability forwarded verbatim to grok-4.6, from 0 to 1 (xAI documents no range for it; a probability mass outside 0 to 1 is meaningless); a value outside it is rejected.',\n }),\n maxOutputTokens: maxOutputTokensSchema(XAI_MODEL_LIMITS['grok-4.6'])\n .optional()\n .meta({\n title: 'Max Output Tokens',\n description:\n 'Maximum output token cap for grok-4.6, including reasoning tokens. No ' +\n 'ceiling is applied: xAI documents no output limit and has accepted very ' +\n \"large values (live-verified). Truncation surfaces as finishReason:'length', \" +\n '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().max(XAI_MAX_TIMEOUT_MS).optional().meta({\n title: 'Timeout',\n description: 'Logical request timeout in milliseconds (at most 2147478647).',\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 the encrypted-reasoning multi-turn replay captured\n * live on 2026-09-26, are fixture-backed. `'none'` stays rejected.\n * Unknown tiers (`flex`, `standard`, `batch`) are rejected.\n *\n * @module\n */\n\nimport { maxOutputTokensSchema } from '@gullabs/core'\nimport { z } from 'zod'\n\nimport { XAI_MODEL_LIMITS } from '../model-limits.js'\nimport { XAI_MAX_TIMEOUT_MS } from '../client.js'\nimport { XaiProviderOptionsSchema } from './tools.js'\n\nexport const Grok47ConfigSchema = z\n .strictObject({\n temperature: z.number().min(0).max(2).optional().meta({\n title: 'Temperature',\n description:\n 'Sampling temperature forwarded verbatim to grok-4.7, from 0 to 2 (the range xAI documents for the Responses API: \"between 0 and 2\"); a value outside it is rejected.',\n }),\n topP: z.number().min(0).max(1).optional().meta({\n title: 'Top P',\n description:\n 'Nucleus sampling probability forwarded verbatim to grok-4.7, from 0 to 1 (xAI documents no range for it; a probability mass outside 0 to 1 is meaningless); a value outside it is rejected.',\n }),\n maxOutputTokens: maxOutputTokensSchema(XAI_MODEL_LIMITS['grok-4.7'])\n .optional()\n .meta({\n title: 'Max Output Tokens',\n description:\n 'Maximum output token cap for grok-4.7, including reasoning tokens. No ' +\n 'ceiling is applied: xAI documents no output limit and has accepted very ' +\n \"large values (live-verified). Truncation surfaces as finishReason:'length', \" +\n '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().max(XAI_MAX_TIMEOUT_MS).optional().meta({\n title: 'Timeout',\n description: 'Logical request timeout in milliseconds (at most 2147478647).',\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 toConfigKeys,\n zodToStandardSchema,\n} from '@gullabs/core'\n\nimport { XAI_INPUT_MIME_TYPES, XAI_MODEL_LIMITS } from './model-limits.js'\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 limits: XAI_MODEL_LIMITS['grok-4.5'],\n pricingFamily: 'grok-4.5',\n capabilities: {\n inputMimeTypes: XAI_INPUT_MIME_TYPES,\n reasoning: true,\n reasoningApi: 'level',\n admittedReasoningEfforts: ['low', 'medium', 'high'],\n structuredOutput: true,\n nativeStructuredOutput: true,\n sampling: 'tunable',\n caching: { explicit: false, minTokens: 0 },\n grounding: true,\n structuredOutputWithTools: true,\n functionCalling: true,\n serviceTiers: ['priority'],\n },\n configSchema: Grok45ConfigSchema,\n configKeys: toConfigKeys(Grok45ConfigSchema),\n configJsonSchema: toConfigJsonSchema(Grok45ConfigSchema),\n validateConfig: zodToStandardSchema(Grok45ConfigSchema),\n}\n\nexport const grok46ModelDescriptor: ModelDescriptor = {\n model: 'grok-4.6',\n provider: 'xai',\n limits: XAI_MODEL_LIMITS['grok-4.6'],\n pricingFamily: 'grok-4.6',\n capabilities: {\n inputMimeTypes: XAI_INPUT_MIME_TYPES,\n reasoning: true,\n reasoningApi: 'level',\n admittedReasoningEfforts: ['low', 'medium', 'high', 'xhigh'],\n structuredOutput: true,\n nativeStructuredOutput: true,\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 configKeys: toConfigKeys(Grok46ConfigSchema),\n configJsonSchema: toConfigJsonSchema(Grok46ConfigSchema),\n validateConfig: zodToStandardSchema(Grok46ConfigSchema),\n}\n\nexport const grok47ModelDescriptor: ModelDescriptor = {\n model: 'grok-4.7',\n provider: 'xai',\n limits: XAI_MODEL_LIMITS['grok-4.7'],\n pricingFamily: 'grok-4.7',\n capabilities: {\n inputMimeTypes: XAI_INPUT_MIME_TYPES,\n reasoning: true,\n reasoningApi: 'level',\n admittedReasoningEfforts: ['low', 'medium', 'high', 'xhigh'],\n structuredOutput: true,\n nativeStructuredOutput: true,\n sampling: 'tunable',\n caching: { explicit: false, minTokens: 0 },\n grounding: true,\n structuredOutputWithTools: true,\n functionCalling: true,\n continuation: 'state',\n providerState: true,\n serviceTiers: ['priority'],\n },\n configSchema: Grok47ConfigSchema,\n configKeys: toConfigKeys(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 * json-schema.ts — the JSON Schema keywords xAI enforces (ADR-034).\n *\n * The adapter sends `output.jsonSchema` as `text.format` (`strict: true`) and a\n * tool's `inputJsonSchema` as the function `parameters`; xAI applies the same\n * schema rules to both. xAI accepts keywords it does not enforce, so the\n * adapter declares the enforced set and rejects the rest (`bad_request`, with\n * the path) before dispatch.\n *\n * Source: xAI's structured-outputs guide, read 2026-10-03\n * (https://docs.x.ai/developers/model-capabilities/text/structured-outputs),\n * pinned in `__fixtures__/structured-output-schema-docs-2026-10-03.json`:\n * - Enforced: `string number integer boolean null enum const array object\n * anyOf`, `$ref` / `$defs` (non-circular only), `additionalProperties`,\n * `required`, `format` for date, time, date-time, email, uuid, ipv4, ipv6\n * and uri, `minimum`/`maximum`/`exclusiveMinimum`/`exclusiveMaximum`,\n * `minLength`/`maxLength` up to 2,048, `minItems`/`maxItems` up to 256,\n * `minProperties`/`maxProperties` up to 64, `pattern` (a regex subset).\n * - `oneOf` \"behaves identically to `anyOf`\": reinterpreted, so rejected.\n * - `allOf` is enforced for a single subschema only; the adapter rejects it\n * outright rather than inspect the arity.\n * - Best-effort (accepted, not enforced): `not`, `if`/`then`/`else`, other\n * `format` values, constraints above the limits. Rejected.\n * - `multipleOf`, `uniqueItems`, `propertyNames` and `patternProperties` are\n * not documented as enforced. Rejected.\n * - xAI answers 400 to `items` as an array and to boolean property schemas.\n * `items: false` (a closed tuple) is undocumented, so it is rejected.\n *\n * @module\n */\n\nimport type { JsonSchemaProfile } from '@gullabs/core'\n\nexport const XAI_JSON_SCHEMA_PROFILE: JsonSchemaProfile = {\n provider: 'xai',\n keywords: [\n 'type',\n 'properties',\n 'required',\n 'additionalProperties',\n 'enum',\n 'const',\n 'anyOf',\n '$ref',\n '$defs',\n 'items',\n 'prefixItems',\n 'minItems',\n 'maxItems',\n 'minimum',\n 'maximum',\n 'exclusiveMinimum',\n 'exclusiveMaximum',\n 'minLength',\n 'maxLength',\n 'minProperties',\n 'maxProperties',\n 'pattern',\n 'format',\n ],\n formats: ['date', 'time', 'date-time', 'email', 'uuid', 'ipv4', 'ipv6', 'uri'],\n limits: {\n minLength: 2048,\n maxLength: 2048,\n minItems: 256,\n maxItems: 256,\n minProperties: 64,\n maxProperties: 64,\n },\n circularRefs: false,\n booleanItems: false,\n patternSubset: true,\n}\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 (blocked, see BACKLOG.md); 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 * How this snapshot treats each server-tool usage counter xAI reports in\n * `usage.server_side_tool_usage_details` (names live-captured in fixtures 17-33).\n *\n * - `priced`: billed by a lane of {@link computeXaiCost}.\n * - `superseded`: no fee of its own (`x_search_calls` is replaced by the per-item\n * `x_posts_fetched` / `x_users_fetched`).\n * - `fee_unpriced`: xAI charges per use and this snapshot has no rate, so a\n * non-zero count makes the call `'estimated'`: code execution $5/1k calls\n * (`code_interpreter_calls`), collections search $2.50/1k (`file_search_calls`),\n * file attachments $5/1k (`document_search_calls`, whose counter name is not\n * pinned, see BACKLOG.md), image generation at Imagine API rates.\n * - `token_only`: xAI lists the tool as token-priced with no invocation fee, so\n * the tokens already priced are the whole cost. `mcp_calls` (Remote MCP Tools)\n * is the only token-only counter whose name has been captured. Image\n * understanding and X video understanding are token-only too (\"you will not be\n * charged for the tool invocation itself but will be charged for the image\n * tokens used\"; web-search image search is billed as web search, so it is\n * `web_search_calls`), but the page names no counter for them and none has been\n * captured, so none is listed.\n *\n * Source: https://docs.x.ai/developers/pricing (\"Tools pricing\"), re-read\n * 2026-10-03 (the page carries no date). A counter that is not in this table and\n * is non-zero is unknown: it keeps the call `'estimated'` like `fee_unpriced`\n * does, but the adapter's warning does not claim it understates (see\n * {@link classifyUnpricedXaiToolCounters}).\n */\nconst XAI_SERVER_TOOL_COUNTERS: Readonly<\n Record<string, 'priced' | 'superseded' | 'fee_unpriced' | 'token_only'>\n> = Object.freeze({\n web_search_calls: 'priced',\n x_posts_fetched: 'priced',\n x_users_fetched: 'priced',\n x_search_calls: 'superseded',\n code_interpreter_calls: 'fee_unpriced',\n file_search_calls: 'fee_unpriced',\n document_search_calls: 'fee_unpriced',\n image_generation_calls: 'fee_unpriced',\n mcp_calls: 'token_only',\n})\n\n/**\n * The non-zero server-tool counters this snapshot cannot price, split by why:\n * `feeUnpriced` are the counters {@link XAI_SERVER_TOOL_COUNTERS} lists as\n * `fee_unpriced` (xAI charges per use, this snapshot has no rate), `unknown` are\n * counters the table does not know at all (xAI may bill them or may not). A call\n * that reports either is priced `'estimated'`, and the adapter warns.\n *\n * Candidates are the members of `usage.raw.server_side_tool_usage_details` (the\n * object xAI reports tool counters in; `usage.details` flattens it together with\n * unrelated numeric usage fields, so it cannot tell a counter from, say,\n * `num_sources_used`) plus the table's own names found in `usage.details`.\n */\nexport function classifyUnpricedXaiToolCounters(usage: Usage): {\n feeUnpriced: string[]\n unknown: string[]\n} {\n const candidates = new Map<string, unknown>()\n const raw = usage.raw\n if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {\n const nested = (raw as Record<string, unknown>)['server_side_tool_usage_details']\n if (typeof nested === 'object' && nested !== null && !Array.isArray(nested)) {\n for (const [key, value] of Object.entries(nested)) candidates.set(key, value)\n }\n }\n for (const [key, value] of Object.entries(usage.details)) {\n if (Object.hasOwn(XAI_SERVER_TOOL_COUNTERS, key) && !candidates.has(key)) {\n candidates.set(key, value)\n }\n }\n const feeUnpriced: string[] = []\n const unknown: string[] = []\n for (const [key, value] of candidates) {\n if (typeof value !== 'number' || !(value > 0)) continue\n if (!Object.hasOwn(XAI_SERVER_TOOL_COUNTERS, key)) unknown.push(key)\n else if (XAI_SERVER_TOOL_COUNTERS[key] === 'fee_unpriced') feeUnpriced.push(key)\n }\n return { feeUnpriced, unknown }\n}\n\n/**\n * Names of the non-zero server-tool counters this snapshot cannot price (both\n * groups of {@link classifyUnpricedXaiToolCounters}); any makes the call\n * `'estimated'`.\n */\nexport function unpricedXaiToolCounters(usage: Usage): string[] {\n const { feeUnpriced, unknown } = classifyUnpricedXaiToolCounters(usage)\n return [...feeUnpriced, ...unknown]\n}\n\n/**\n * `usage.details` marker the adapter sets on usage it ESTIMATED for a stream that\n * failed after output began (ADR-040 Amendment A). Such a call is priced\n * `'estimated'`: the tokens are a lower bound, never the provider's count.\n */\nexport const XAI_ESTIMATED_USAGE_KEY = 'usage_estimated'\n\n/** 1 tick = 1e-10 USD, so 10,000 ticks are 1 µUSD. */\nconst TICKS_PER_MICRO_USD = 10_000\n\n/**\n * The call total xAI reported (`usage.cost_in_usd_ticks`) in whole µUSD, rounded\n * like every lane of {@link computeXaiCost}; `undefined` when absent or not a\n * finite non-negative number.\n */\nfunction providerReportedCost(usage: Usage): Cost['providerReported'] {\n const ticks = usage.details['cost_in_usd_ticks']\n if (typeof ticks !== 'number' || !Number.isFinite(ticks) || ticks < 0) return undefined\n return { microUsd: Math.round(ticks / TICKS_PER_MICRO_USD) }\n}\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; the\n * cached leg (2× its standard rate) by fixture `35-priority-warm-cache.json`\n * (warm-cache priority calls on all three models). The `gt200k` leg follows\n * the official 2×-after-cache-discount docs rule: no priority capture reaches\n * 200k input tokens.\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. `cost_in_usd_ticks` (1 tick = 1e-10 USD) is converted to µUSD with the same\n * rounding and reported as `Cost.providerReported`; `microUsd` stays this\n * snapshot's price. The engine warns when the two totals drift.\n * 8. A non-zero server-tool counter that xAI bills per use (or that is unknown)\n * and this snapshot has no rate for ({@link unpricedXaiToolCounters}, driven\n * by {@link XAI_SERVER_TOOL_COUNTERS}) makes the call `'estimated'`. Token-only\n * tools (`mcp_calls`) do not.\n * 9. 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` and, as `Cost.providerReported`, on the returned cost.\n * File-ref still sets `attachment_search_unpinned` and the call is\n * estimated — the counter name is not pinned.\n */\nexport function computeXaiCost(model: string, usage: Usage, tier?: string): Cost {\n const cost = priceXaiCall(model, usage, tier)\n const providerReported = providerReportedCost(usage)\n return providerReported === undefined ? cost : { ...cost, providerReported }\n}\n\nfunction priceXaiCall(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 // `microUsd` stays null: the snapshot cannot price this call. The total xAI\n // billed rides on `Cost.providerReported` (added by `computeXaiCost`).\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 const unpricedCounters = unpricedXaiToolCounters(usage)\n\n return {\n microUsd,\n usd: microUsd / 1_000_000,\n pricingVersion: xaiPricingVersion,\n confidence:\n missingWebCounter ||\n attachmentUnpinned ||\n unpricedCounters.length > 0 ||\n usage.details[XAI_ESTIMATED_USAGE_KEY] === 1\n ? 'estimated'\n : '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 {\n LlmError,\n classifyError,\n causeChain,\n assertNever,\n assertJsonSchemaProfile,\n assertInputMimeTypesAdmitted,\n assertModelMatchesDescriptor,\n} 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 {\n buildXaiClient,\n requireApiKey,\n XAI_DEFAULT_TIMEOUT_MS,\n XAI_MAX_TIMEOUT_MS,\n XAI_RESERVED_FETCH_OPTION_KEYS,\n XAI_TIMEOUT_BUFFER_MS,\n} from './client.js'\nimport { xaiRegistry } from './models.js'\nimport { XAI_JSON_SCHEMA_PROFILE } from './json-schema.js'\nimport {\n X_SEARCH_ITEM_COUNTERS,\n XAI_ESTIMATED_USAGE_KEY,\n classifyUnpricedXaiToolCounters,\n} from './pricing.js'\nimport { XaiStreamError } from './stream.js'\nimport type {\n XaiClientLike,\n XaiRequestOptions,\n XaiResponseMeta,\n XaiTransport,\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\n/** A message content part's text, or `undefined` for a part that carries none. */\nfunction partText(part: unknown): string | undefined {\n return isPlainRecord(part) && typeof part['text'] === 'string'\n ? part['text']\n : undefined\n}\n\n/** `value` cut to 500 characters, for a note that quotes provider text. */\nfunction boundedNote(value: string): string {\n return value.length > 500 ? `${value.slice(0, 500)}...` : value\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\n/** 20 MiB, xAI's documented inline-image size ceiling. */\nconst MAX_XAI_INLINE_IMAGE_BYTES = 20 * 1024 * 1024\n\n/**\n * Decoded size of a base64 string, from its length and padding (no `Buffer`).\n * ASCII whitespace (line breaks in wrapped base64) is not data and is not counted;\n * it is only scanned for when the plain length is already over the ceiling.\n */\nfunction decodedBase64Length(data: string): number {\n const plain = (length: number, tail: string) => {\n let padding = 0\n while (padding < 2 && tail.charCodeAt(tail.length - 1 - padding) === 0x3d)\n padding += 1\n return Math.floor(((length - padding) * 3) / 4)\n }\n const upper = plain(data.length, data)\n if (upper <= MAX_XAI_INLINE_IMAGE_BYTES) return upper\n let length = 0\n let end = data.length\n for (let i = 0; i < data.length; i += 1) {\n const c = data.charCodeAt(i)\n if (c !== 0x20 && c !== 0x0a && c !== 0x0d && c !== 0x09) {\n length += 1\n end = i + 1\n }\n }\n return plain(length, data.slice(0, end))\n}\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 the decoded payload exceeds 20 MiB. The\n * media type itself is checked against the descriptor's\n * `capabilities.inputMimeTypes` (jpeg and png; WebP is not accepted) before\n * any part is mapped.\n * - `file-uri` → `{ type: 'input_image', image_url: uri }` ONLY when\n * `uri` is a public `http(s)://` URL (its media type is checked like an\n * inline part's) — 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 const byteLength = decodedBase64Length(p.data)\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 if (!isPublicHttpUrl) {\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([\n 'promptCacheKey',\n 'tools',\n 'parallelToolCalls',\n 'toolChoice',\n 'maxTurns',\n 'searchBudget',\n])\n\n/** The structured-output `name` used when the schema has no `title`. */\nconst XAI_DEFAULT_SCHEMA_NAME = 'structured_output'\n\n/**\n * The names `text.format.name` may take: the Responses API's rule. xAI\n * documents none (docs.x.ai, read 2026-10-03), so this is the mirrored API's.\n */\nconst XAI_SCHEMA_NAME = /^[a-zA-Z0-9_-]{1,64}$/\n\nconst XAI_SERVER_TOOL_CHOICES = new Set(['auto', 'required', 'none'])\n\ntype MappedXaiProviderOptions = {\n promptCacheKey?: string\n tools?: Array<Record<string, unknown>>\n parallelToolCalls?: boolean\n toolChoice?: 'auto' | 'required' | 'none'\n maxTurns?: number\n /** Observed after the call, never sent to xAI. */\n searchBudget?: XaiSearchBudget\n}\n\n/**\n * `providerOptions.xai.searchBudget`: ceilings the adapter compares with the\n * search counters xAI reports after the call. xAI offers no per-call ceiling\n * on search volume (`maxTurns` is not enforced), so this only tells the host\n * the call exceeded what it expected to pay for.\n */\ntype XaiSearchBudget = { maxWebSearchCalls?: number; maxXItems?: number }\n\nconst XAI_SEARCH_BUDGET_KEYS = ['maxWebSearchCalls', 'maxXItems'] as const\n\nfunction mapXaiSearchBudget(\n value: unknown,\n tools: Array<Record<string, unknown>> | undefined,\n model: string,\n): XaiSearchBudget {\n if (!isPlainRecord(value)) {\n throw badXaiRequest(\n `providerOptions.xai.searchBudget must be an object for model \"${model}\".`,\n )\n }\n const unknown = Object.keys(value).filter(\n (key) => !(XAI_SEARCH_BUDGET_KEYS as readonly string[]).includes(key),\n )\n if (unknown.length > 0) {\n throw badXaiRequest(\n `providerOptions.xai.searchBudget contains unsupported keys [${unknown.join(\n ', ',\n )}] for model \"${model}\". Allowed keys: ${XAI_SEARCH_BUDGET_KEYS.join(', ')}.`,\n )\n }\n const budget: XaiSearchBudget = {}\n for (const key of XAI_SEARCH_BUDGET_KEYS) {\n const entry = value[key]\n if (entry === undefined) continue\n if (typeof entry !== 'number' || !Number.isInteger(entry) || entry < 1) {\n throw badXaiRequest(\n `providerOptions.xai.searchBudget.${key} must be an integer >= 1 for model \"${model}\".`,\n )\n }\n budget[key] = entry\n }\n if (budget.maxWebSearchCalls === undefined && budget.maxXItems === undefined) {\n throw badXaiRequest(\n `providerOptions.xai.searchBudget must set maxWebSearchCalls or maxXItems for model \"${model}\".`,\n )\n }\n const hasTool = (type: string): boolean =>\n tools?.some((tool) => tool['type'] === type) === true\n if (budget.maxWebSearchCalls !== undefined && !hasTool('web_search')) {\n throw badXaiRequest(\n `providerOptions.xai.searchBudget.maxWebSearchCalls requires a web_search tool in providerOptions.xai.tools for model \"${model}\".`,\n )\n }\n if (budget.maxXItems !== undefined && !hasTool('x_search')) {\n throw badXaiRequest(\n `providerOptions.xai.searchBudget.maxXItems requires an x_search tool in providerOptions.xai.tools for model \"${model}\".`,\n )\n }\n return budget\n}\n\n/**\n * Names the budget lines the observed counters exceed. A counter xAI did not\n * report cannot be compared, so it never counts as exceeded.\n */\nfunction exceededSearchBudget(\n budget: XaiSearchBudget,\n details: Record<string, number>,\n): string[] {\n const over: string[] = []\n const webCalls = details[WEB_SEARCH_COUNTER]\n if (\n budget.maxWebSearchCalls !== undefined &&\n webCalls !== undefined &&\n webCalls > budget.maxWebSearchCalls\n ) {\n over.push(\n `${WEB_SEARCH_COUNTER} ${webCalls} > maxWebSearchCalls ${budget.maxWebSearchCalls}`,\n )\n }\n if (budget.maxXItems !== undefined) {\n const reported = X_SEARCH_ITEM_COUNTERS.filter((key) => details[key] !== undefined)\n const items = reported.reduce((sum, key) => sum + (details[key] as number), 0)\n if (reported.length > 0 && items > budget.maxXItems) {\n over.push(`X items ${items} > maxXItems ${budget.maxXItems}`)\n }\n }\n return over\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, toolChoice, maxTurns, searchBudget.`,\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 const toolChoice = xaiOpts['toolChoice']\n if (toolChoice !== undefined) {\n if (typeof toolChoice !== 'string' || !XAI_SERVER_TOOL_CHOICES.has(toolChoice)) {\n throw badXaiRequest(\n `providerOptions.xai.toolChoice must be \"auto\", \"required\" or \"none\" for model \"${model}\".`,\n )\n }\n if (mapped.tools === undefined || mapped.tools.length === 0) {\n throw badXaiRequest(\n `providerOptions.xai.toolChoice requires a non-empty providerOptions.xai.tools for model \"${model}\".`,\n )\n }\n mapped.toolChoice = toolChoice as 'auto' | 'required' | 'none'\n }\n\n const maxTurns = xaiOpts['maxTurns']\n if (maxTurns !== undefined) {\n if (typeof maxTurns !== 'number' || !Number.isInteger(maxTurns) || maxTurns < 1) {\n throw badXaiRequest(\n `providerOptions.xai.maxTurns must be an integer >= 1 for model \"${model}\".`,\n )\n }\n if (mapped.tools === undefined || mapped.tools.length === 0) {\n throw badXaiRequest(\n `providerOptions.xai.maxTurns requires a non-empty providerOptions.xai.tools for model \"${model}\".`,\n )\n }\n mapped.maxTurns = maxTurns\n }\n\n if (xaiOpts['searchBudget'] !== undefined) {\n mapped.searchBudget = mapXaiSearchBudget(xaiOpts['searchBudget'], mapped.tools, model)\n }\n\n return mapped\n}\n\nfunction parseXaiReplayState(value: unknown, model: string): XaiReplayState | undefined {\n if (value === undefined) return undefined\n const keys = isPlainRecord(value) ? Object.keys(value) : []\n if (keys.some((key) => key !== 'xai')) {\n throw badXaiRequest(\n `transientProviderState has unexpected key(s) [${keys.join(', ')}]; xAI state is exactly { xai: { model, input } } (another provider's state is rejected).`,\n )\n }\n const inner = isPlainRecord(value) ? value['xai'] : undefined\n if (\n !isPlainRecord(inner) ||\n inner['model'] !== model ||\n !Array.isArray(inner['input']) ||\n inner['input'].length === 0 ||\n inner['input'].some(\n (item) =>\n !isPlainRecord(item) ||\n (typeof item['type'] !== 'string' && typeof item['role'] !== 'string'),\n )\n ) {\n throw badXaiRequest(\n `transientProviderState must be { xai: { model, input } } with the full xAI wire input, bound to the requested 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 * Credits-exhausted / spending-limit signature. DOC-DERIVED, NOT A CAPTURE:\n * the account could not be driven to its limit (probe P7 was not runnable), and\n * xAI's own error reference (docs.x.ai/docs/key-information/debugging, read\n * 2026-10-03) documents 403 and 429 without any body. The body text comes from\n * public bug reports of the live API (continuedev/continue#10373, HTTP 429;\n * LCV-Ideas-Software/cross-review#270, HTTP 403): `Your team <team-id> has\n * either used all available credits or reached its monthly spending limit. To\n * continue making API requests, please purchase more credits or raise your\n * spending limit.` One report also names the code\n * `personal-team-blocked:spending-limit`, which this adapter does not rely on.\n *\n * Only the structured body text is matched (same anti-echo rule as the other\n * overlays), by the stable middle of the sentence, on a 429 or a 403. Replace\n * this with a pinned capture when one exists.\n */\nconst XAI_CREDITS_EXHAUSTED_BODY =\n /^Your team \\S+ has either used all available credits or reached its monthly spending limit/\n\n/** True iff the structured body matches the doc-derived credits-exhausted signature. */\nfunction isXaiCreditsExhaustedBody(rawErr: unknown): boolean {\n const text = extractXaiErrorBodyText(rawErr)\n return text !== undefined && XAI_CREDITS_EXHAUSTED_BODY.test(text)\n}\n\n/**\n * True iff `rawErr` is the `openai` SDK's own connection error. The SDK's\n * `APIConnectionError` carries a caller-chosen message in some paths, so it is\n * also matched by class. Matched by constructor name rather than `instanceof`\n * so this file does not need a runtime import of `openai` (per `client.ts`,\n * that package is imported ONLY in `buildXaiClient`, keeping unit tests\n * independent of the real SDK). Every other transport failure (an errno or\n * undici code on the cause chain, `fetch failed`, `Connection error.`) is\n * recognised by core's `classifyError` through `isTransportError`.\n */\nfunction isOpenAiSdkConnectionError(rawErr: unknown): boolean {\n return (\n rawErr instanceof Error &&\n (rawErr.constructor.name === 'APIConnectionError' ||\n rawErr.constructor.name === 'APIConnectionTimeoutError')\n )\n}\n\n/** undici error codes for Node's own header and body timers. */\nconst UNDICI_HEADERS_TIMEOUT_CODE = 'UND_ERR_HEADERS_TIMEOUT'\nconst UNDICI_BODY_TIMEOUT_CODE = 'UND_ERR_BODY_TIMEOUT'\n\n/**\n * What the adapter knows about the SDK deadline of the call that failed: the\n * `timeout` it handed the SDK and how long the call ran. Without it an\n * `APIConnectionTimeoutError` is never taken for the SDK's own deadline.\n */\nexport interface XaiSdkDeadline {\n /** The per-request `timeout` the adapter passed to the SDK, in ms. */\n timeoutMs: number\n /** Wall-clock ms between the SDK call starting and the error. */\n elapsedMs: number\n}\n\n/** Timers may fire a hair early relative to a monotonic clock. */\nconst SDK_DEADLINE_SLACK_MS = 5\n\n/**\n * True only for the SDK's own deadline. The `openai` SDK wraps EVERY fetch\n * failure whose text mentions \"timed out\" (an OS `ETIMEDOUT`, a TLS handshake\n * timeout, a host fetch's own abort) as an `APIConnectionTimeoutError`, so the\n * class alone proves nothing. The SDK's own timer produces that class with no\n * cause (body phase) or with the `AbortError` of its own controller (headers\n * phase), and it cannot fire before the `timeout` the adapter set; both are\n * required. Anything else falls through to the ordinary classification.\n */\nfunction isSdkDeadline(rawErr: unknown, deadline: XaiSdkDeadline | undefined): boolean {\n if (deadline === undefined) return false\n if (\n !(rawErr instanceof Error) ||\n rawErr.constructor.name !== 'APIConnectionTimeoutError'\n ) {\n return false\n }\n const causes = causeChain(rawErr).slice(1)\n if (!causes.every((e) => (e as { name?: unknown }).name === 'AbortError')) return false\n return deadline.elapsedMs >= deadline.timeoutMs - SDK_DEADLINE_SLACK_MS\n}\n\n/**\n * Which transport deadline killed the request, or `undefined` when none did.\n *\n * - `'headers'` / `'body'`: Node's undici header or body timer fired (the 300 s\n * default). Matched by undici error `code` (or class name) anywhere in the\n * cause chain; the `openai` SDK wraps the undici error as the cause of its\n * own `APIConnectionTimeoutError`, or lets it escape raw while the body is\n * read.\n * - `'sdk'`: the SDK's own deadline fired (see {@link isSdkDeadline}).\n *\n * A retry reaches the same limit and repeats the spend, so all three are\n * non-retryable. A connect timeout, an OS `ETIMEDOUT` and a TLS handshake\n * timeout are not matched: nothing reached xAI, so a retry is safe.\n */\nfunction xaiTransportTimeoutKind(\n rawErr: unknown,\n deadline: XaiSdkDeadline | undefined,\n): 'headers' | 'body' | 'sdk' | undefined {\n const chain = causeChain(rawErr)\n const has = (code: string, name: string): boolean =>\n chain.some((e) => {\n const o = e as { code?: unknown; name?: unknown }\n return o.code === code || o.name === name\n })\n if (has(UNDICI_HEADERS_TIMEOUT_CODE, 'HeadersTimeoutError')) return 'headers'\n if (has(UNDICI_BODY_TIMEOUT_CODE, 'BodyTimeoutError')) return 'body'\n if (isSdkDeadline(rawErr, deadline)) return 'sdk'\n return undefined\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 * 3b. HTTP 429 or 403 whose structured body is the credits-exhausted /\n * spending-limit sentence (doc-derived, see `XAI_CREDITS_EXHAUSTED_BODY`) →\n * `rate_limited`, `retryable: false`, `reason: 'credits_exhausted'`.\n * 4. A transport deadline (undici header or body timer, or the SDK's own\n * deadline, which needs the `deadline` argument to be recognised; see\n * {@link xaiTransportTimeoutKind}) → `timeout`,\n * `retryable: false`, `reason: 'transport_timeout'`.\n * 5. A transport failure (core's `classifyError` already makes it a retryable\n * `server` error; an `openai` SDK connection error that core left `unknown`\n * is made one here). A connection that never reached xAI is not the\n * caller's fault.\n * 6. Else rebuild the core classification tagged `provider: 'xai'`.\n *\n * A streamed call that failed mid-stream arrives as an `XaiStreamError`; see\n * {@link classifyStreamError} (`estimatedInputTokens` is the request's input\n * estimate, used only for a failure after output began; `requestTimeoutMs` is\n * the timeout the caller configured, quoted by the client-deadline message).\n */\nexport function classifyXaiError(\n rawErr: unknown,\n deadline?: XaiSdkDeadline,\n estimatedInputTokens = 0,\n requestTimeoutMs?: number,\n): LlmError {\n if (rawErr instanceof LlmError) {\n return rawErr\n }\n if (rawErr instanceof XaiStreamError) {\n return classifyStreamError(rawErr, estimatedInputTokens, requestTimeoutMs)\n }\n\n const base = classifyError(rawErr)\n\n const transportTimeout = xaiTransportTimeoutKind(rawErr, deadline)\n if (transportTimeout !== undefined) {\n const which =\n transportTimeout === 'sdk' ? 'SDK deadline' : `transport ${transportTimeout} timer`\n return new LlmError(`xAI request hit the ${which}: ${base.message}`, {\n kind: 'timeout',\n retryable: false,\n reason: 'transport_timeout',\n provider: 'xai',\n cause: base.cause ?? rawErr,\n })\n }\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 (\n (base.httpStatus === 429 || base.httpStatus === 403) &&\n isXaiCreditsExhaustedBody(rawErr)\n ) {\n // Out of credits or at the spending limit: neither a retry nor a key\n // rotation helps, the team has to add credit or raise the limit. xAI sends\n // it as a 429 in some reports and a 403 in others.\n // The team id in the sentence is an account identifier: it would land in\n // logs and ledger rows, so the message omits it (it stays on `cause`).\n return new LlmError(\n (extractXaiErrorBodyText(rawErr) ?? base.message).replace(\n /^Your team \\S+ /,\n 'Your team ',\n ),\n {\n kind: 'rate_limited',\n retryable: false,\n reason: 'credits_exhausted',\n httpStatus: base.httpStatus,\n provider: 'xai',\n cause: base.cause ?? rawErr,\n },\n )\n }\n\n if (base.kind === 'unknown' && isOpenAiSdkConnectionError(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 * How a failed response's `error.code` is classified. A retry is allowed only\n * for a code that names a transient condition (`server_error`,\n * `rate_limit_exceeded`): a deterministic failure is refused again and billed\n * again, and an unrecognised code is not assumed to be transient.\n */\nfunction classifyFailedResponseCode(\n code: string | undefined,\n): Pick<LlmError, 'kind' | 'retryable'> {\n switch (code) {\n case 'server_error':\n return { kind: 'server', retryable: true }\n case 'rate_limit_exceeded':\n return { kind: 'rate_limited', retryable: true }\n case 'bio_policy':\n case 'misalignment_policy_violation':\n case 'image_content_policy_violation':\n return { kind: 'content_filter', retryable: false }\n case 'invalid_prompt':\n case 'data_residency_mismatch':\n case 'invalid_image':\n case 'invalid_image_format':\n case 'invalid_base64_image':\n case 'invalid_image_url':\n case 'image_too_large':\n case 'image_too_small':\n case 'image_parse_error':\n case 'invalid_image_mode':\n case 'image_file_too_large':\n case 'unsupported_image_media_type':\n case 'empty_image_file':\n case 'failed_to_download_image':\n case 'image_file_not_found':\n return { kind: 'bad_request', retryable: false }\n default:\n return { kind: 'unknown', retryable: false }\n }\n}\n\n/**\n * The usage of a stream that failed after output began, as an ESTIMATE (ADR-040\n * Amendment A): input is the length of the wire input over 4\n * ({@link estimateWireInputTokens}), output is the characters received over 4.\n * Its limits: hidden reasoning tokens, tool fees and the provider's own prompt\n * overhead are not counted, so the real spend is usually higher; cached input is\n * not known, so cached tokens are priced as uncached, which is higher than the\n * bill; image and file inputs carry no text and count nothing; characters per\n * token is a rule of thumb that varies with language and with the JSON syntax of\n * replayed state. Treat it as the order of magnitude of what was spent, never as\n * a bill. The `usage_estimated` detail makes the pricing source report the cost\n * as `'estimated'`; no `cost_in_usd_ticks` is ever attached.\n */\nfunction estimatedStreamUsage(outputChars: number, inputTokens: number): Usage {\n const outputTokens = Math.ceil(outputChars / 4)\n return {\n inputTokens,\n outputTokens,\n details: { input: inputTokens, output: outputTokens, [XAI_ESTIMATED_USAGE_KEY]: 1 },\n raw: {\n estimated: true,\n basis:\n 'estimate: wire input characters / 4 for input (replayed state included, media not counted), received output characters / 4 for output; hidden reasoning is not counted',\n outputChars,\n },\n }\n}\n\n/**\n * The error for a call that failed while streaming (ADR-040, Amendment A).\n *\n * A failure BEFORE any output event stays what a refused or dropped connection\n * is: retryable, no usage, an unpriced attempt. A failure AFTER output began\n * (or after the terminal event) is never retryable: the model was generating,\n * a reasoning call burns tokens before its first visible event, a retry repeats\n * that spend and cannot resume it (the reasoning of ADR-032's timeouts). It\n * carries the terminal usage when one arrived (exact, ticks included), else a\n * lower-bound ESTIMATE from what was received ({@link estimatedStreamUsage}).\n * Snapshot usage from `response.created` / `response.in_progress` is never used.\n * An `error` event is booked as possibly billed (`mayHaveBilled`): the stream had\n * started, so even `rate_limited` and `bad_request` are not known-free.\n */\nfunction classifyStreamError(\n err: XaiStreamError,\n estimatedInputTokens: number,\n requestTimeoutMs: number | undefined,\n): LlmError {\n const failure = err.failure\n const { progressed, outputChars } = err.progress\n const usage =\n err.terminalUsage !== undefined\n ? mapUsage(err.terminalUsage)\n : progressed\n ? estimatedStreamUsage(outputChars, estimatedInputTokens)\n : undefined\n const common = {\n provider: 'xai',\n ...(usage !== undefined ? { usage } : {}),\n ...(err.servedServiceTier !== undefined\n ? { servedServiceTier: err.servedServiceTier }\n : {}),\n cause: err,\n } as const\n switch (failure.kind) {\n case 'ended_early':\n case 'malformed':\n // A connection that closed early or a body that is not valid is a\n // transient provider fault, and a retry may complete, but only while\n // nothing was generated.\n return new LlmError(err.message, {\n kind: 'server',\n retryable: !progressed,\n ...common,\n })\n case 'cut': {\n // A transport failure after output began. Node's own timers keep their\n // kind; every other failure is a `server` error that is not retried.\n const base = classifyXaiError(err.cause)\n return base.kind === 'timeout'\n ? new LlmError(base.message, {\n kind: 'timeout',\n retryable: false,\n ...(base.reason !== undefined ? { reason: base.reason } : {}),\n ...common,\n })\n : new LlmError(err.message, { kind: 'server', retryable: false, ...common })\n }\n case 'deadline':\n // The same limit again, the same spend again. The client's own timer, set\n // a buffer past the configured timeout so the engine's deadline fires\n // first; the message quotes the configured value.\n return new LlmError(\n `xAI request hit the client deadline: the stream was still open after the ${\n requestTimeoutMs ?? failure.timeoutMs\n } ms request timeout`,\n {\n kind: 'timeout',\n retryable: false,\n reason: 'transport_timeout',\n ...common,\n },\n )\n case 'aborted': {\n // The engine's deadline or the caller stopped a call that was generating:\n // the abort reason keeps its kind, the estimate rides along.\n const reason: unknown = err.cause\n return reason instanceof LlmError\n ? new LlmError(reason.message, {\n kind: reason.kind,\n retryable: reason.retryable,\n ...(reason.reason !== undefined ? { reason: reason.reason } : {}),\n ...common,\n cause: reason,\n })\n : new LlmError('Request aborted by caller', {\n kind: 'aborted',\n retryable: false,\n ...common,\n cause: reason ?? err,\n })\n }\n case 'idle':\n return new LlmError(`xAI request hit the idle timeout: ${err.message}`, {\n kind: 'timeout',\n retryable: false,\n reason: 'transport_timeout',\n ...common,\n })\n case 'error_event': {\n const mapped = classifyFailedResponseCode(failure.code)\n // Inside an open stream a retry repeats whatever the call already did:\n // `rate_limit_exceeded` is not retried, and `server_error` only before\n // any output.\n return new LlmError(err.message, {\n kind: mapped.kind,\n retryable: mapped.kind === 'server' && !progressed,\n mayHaveBilled: true,\n ...common,\n })\n }\n case 'not_event_stream':\n // Misconfiguration of the host's `fetch`, not a bad request, but a retry\n // repeats it, and the upstream call may have run and billed.\n return new LlmError(err.message, {\n kind: 'bad_request',\n retryable: false,\n mayHaveBilled: true,\n ...common,\n })\n }\n}\n\n/**\n * The error for a response with `status` `failed` or `cancelled` (see step 6b).\n *\n * `streamProgressed` is true when output events arrived before the failure: the\n * run already spent tokens, so a retry would repeat that spend and it is not\n * retried, whatever the code (the policy of an `error` event). A failed response\n * is always `mayHaveBilled`: the provider had accepted the request and started\n * work, so a `rate_limited` or `bad_request` code without usage is not known-free.\n */\nfunction failedResponseError(\n response: XaiResponseShape,\n streamProgressed: boolean,\n): LlmError {\n const reported = isPlainRecord(response.error) ? response.error : undefined\n const code = typeof reported?.['code'] === 'string' ? reported['code'] : undefined\n const detail =\n typeof reported?.['message'] === 'string' ? `: ${reported['message']}` : ''\n const { kind, retryable } =\n response.status === 'cancelled'\n ? ({ kind: 'unknown', retryable: false } as const)\n : classifyFailedResponseCode(code)\n return new LlmError(\n response.status === 'cancelled'\n ? `xAI response reported status \"cancelled\"${detail}`\n : `xAI response failed${code !== undefined ? ` (error.code \"${code}\")` : ''}${detail}`,\n {\n kind,\n retryable: retryable && !streamProgressed,\n mayHaveBilled: true,\n provider: 'xai',\n // Usage is attached only when the failed response billed tokens.\n ...(isPlainRecord(response.usage) &&\n typeof response.usage.input_tokens === 'number' &&\n typeof response.usage.output_tokens === 'number'\n ? { usage: mapUsage(response.usage) }\n : {}),\n ...(typeof response.service_tier === 'string' && response.service_tier.length > 0\n ? { servedServiceTier: response.service_tier }\n : {}),\n cause: response.error ?? { status: response.status },\n },\n )\n}\n\n/**\n * Input tokens of the request body as the failure estimate counts them: the\n * JSON length of everything the provider reads as text (`input` with any replayed\n * `'state'` history, `instructions`, `tools`, `text.format`) over 4, rounded up.\n * The request's own new messages are not enough: on `continuation: 'state'` the\n * whole history, every encrypted reasoning blob and search item, is sent again\n * and billed as input. Inline image data URLs are not counted (they are not text).\n * See {@link estimatedStreamUsage} for the estimate's limits.\n */\nfunction estimateWireInputTokens(params: XaiResponseCreateParams): number {\n const withoutImageBytes = (key: string, value: unknown): unknown =>\n key === 'image_url' && typeof value === 'string' && value.startsWith('data:')\n ? ''\n : value\n try {\n const wire = JSON.stringify(\n {\n input: params.input,\n instructions: params.instructions,\n tools: params.tools,\n text: params.text,\n },\n withoutImageBytes,\n )\n return Math.ceil(wire.length / 4)\n } catch {\n return 0\n }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter options\n// ---------------------------------------------------------------------------\n\n/**\n * Default deadline of one `countTokens` call (`POST /v1/tokenize-text`), in\n * milliseconds: 60 s. The call is a small text-only request; the engine's\n * `countTokens` `timeoutMs` and the call's own signal still apply first.\n */\nexport const XAI_COUNT_TOKENS_TIMEOUT_MS = 60_000\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 * HTTP transport (`fetch`, `fetchOptions`, `idleTimeoutMs`) for the SDK client\n * the adapter builds: a proxy, mTLS or egress policy, or an undici `fetch` with\n * an `Agent({ headersTimeout, bodyTimeout })` dispatcher. Calls stream\n * internally (ADR-040), so a reasoning call no longer needs it to run past\n * 300 s; a tool-using call expected to run past 300 s without any streamed\n * event still does (untested, see the package README). `idleTimeoutMs` ends a\n * stream that sends no bytes for that long (off by default). `fetch` must return\n * the request's `text/event-stream` response unchanged. `fetch` and\n * `fetchOptions` also carry `countTokens` (`POST /v1/tokenize-text`). Validated\n * and copied when the adapter is created. Cannot be combined with `client` (an injected client owns its own\n * transport).\n */\n transport?: XaiTransport\n /**\n * Deadline of one `countTokens` call in milliseconds (an integer from 1 to\n * {@link XAI_MAX_TIMEOUT_MS}); default {@link XAI_COUNT_TOKENS_TIMEOUT_MS}. A\n * call still open then fails with a retryable `timeout` error.\n */\n countTokensTimeoutMs?: number\n}\n\n// ---------------------------------------------------------------------------\n// xaiAdapter factory\n// ---------------------------------------------------------------------------\n\n/**\n * Validates a host transport and returns a private copy of it.\n *\n * @throws LlmError `bad_request` for a transport that is not an object, whose\n * `fetch` is not a function, whose `fetchOptions` is not a plain\n * object, whose `fetchOptions` carries a key the request owns, or whose\n * `idleTimeoutMs` is not an integer from 1 to {@link XAI_MAX_TIMEOUT_MS}.\n */\nfunction snapshotXaiTransport(\n transport: XaiTransport | undefined,\n): XaiTransport | undefined {\n if (transport === undefined) return undefined\n const reject = (message: string): LlmError =>\n new LlmError(`xaiAdapter: ${message}`, {\n kind: 'bad_request',\n retryable: false,\n provider: 'xai',\n })\n const candidate = transport as unknown\n if (candidate === null || typeof candidate !== 'object') {\n throw reject('transport must be an object { fetch, fetchOptions?, idleTimeoutMs? }.')\n }\n if (typeof transport.fetch !== 'function') {\n throw reject('transport.fetch must be a function.')\n }\n const idle = transport.idleTimeoutMs as unknown\n if (\n idle !== undefined &&\n (typeof idle !== 'number' ||\n !Number.isInteger(idle) ||\n idle < 1 ||\n idle > XAI_MAX_TIMEOUT_MS)\n ) {\n throw reject(\n `transport.idleTimeoutMs must be an integer from 1 to ${XAI_MAX_TIMEOUT_MS}.`,\n )\n }\n const fetchOptions = transport.fetchOptions as unknown\n if (\n fetchOptions !== undefined &&\n (fetchOptions === null ||\n typeof fetchOptions !== 'object' ||\n Array.isArray(fetchOptions))\n ) {\n throw reject('transport.fetchOptions must be an object.')\n }\n if (fetchOptions !== undefined) {\n for (const key of XAI_RESERVED_FETCH_OPTION_KEYS) {\n if (key in fetchOptions) {\n throw reject(\n `transport.fetchOptions.${key} is not supported; the request owns it.`,\n )\n }\n }\n }\n return {\n fetch: transport.fetch,\n ...(fetchOptions !== undefined\n ? {\n fetchOptions: {\n ...(fetchOptions as NonNullable<XaiTransport['fetchOptions']>),\n },\n }\n : {}),\n ...(transport.idleTimeoutMs !== undefined\n ? { idleTimeoutMs: transport.idleTimeoutMs }\n : {}),\n }\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 * @param opts.transport - Optional `fetch` + `fetchOptions` for the built client.\n */\nexport function xaiAdapter(opts?: XaiAdapterOptions): ProviderAdapter {\n return xaiAdapterWithSeams(opts, {})\n}\n\n/**\n * The test seams of {@link xaiAdapter}: a replacement for the client factory\n * (to make client construction fail without the real SDK) and for the `fetch`\n * `countTokens` uses. Passed to {@link xaiAdapterWithSeams}.\n *\n * @internal\n */\ninterface XaiAdapterSeams {\n clientFactory?: (\n auth: AuthMaterial,\n transport?: XaiTransport,\n ) => XaiClientLike | Promise<XaiClientLike>\n fetch?: typeof fetch\n}\n\n/**\n * {@link xaiAdapter} with its seams replaced. Not exported from the package\n * index, so no test seam is in a shipped type (the same pattern as the Gemini\n * adapter's `geminiAdapterWithClientFactory`).\n *\n * @internal\n */\nexport function xaiAdapterWithSeams(\n opts: XaiAdapterOptions | undefined,\n seams: XaiAdapterSeams,\n): ProviderAdapter {\n if (opts?.client !== undefined && opts.transport !== undefined) {\n throw new LlmError(\n 'xaiAdapter: `transport` has no effect on an injected `client`; configure the transport on the client itself.',\n { kind: 'bad_request', retryable: false, provider: 'xai' },\n )\n }\n // Validated and copied once: the host mutating its own transport object\n // afterwards cannot reach the SDK or `countTokens`.\n const transport = snapshotXaiTransport(opts?.transport)\n const countTokensTimeoutMs = opts?.countTokensTimeoutMs ?? XAI_COUNT_TOKENS_TIMEOUT_MS\n if (\n !Number.isInteger(countTokensTimeoutMs) ||\n countTokensTimeoutMs < 1 ||\n countTokensTimeoutMs > XAI_MAX_TIMEOUT_MS\n ) {\n throw new LlmError(\n `xaiAdapter: countTokensTimeoutMs must be an integer from 1 to ${XAI_MAX_TIMEOUT_MS}.`,\n { kind: 'bad_request', retryable: false, provider: 'xai' },\n )\n }\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 (req.modelDescriptor !== undefined) {\n assertModelMatchesDescriptor(req, req.modelDescriptor, 'xai')\n }\n // A direct adapter call without a descriptor is checked against the\n // built-in one, so media types are never silently unchecked.\n const mediaDescriptor = req.modelDescriptor ?? xaiRegistry.resolve('xai', model)\n if (mediaDescriptor !== undefined) {\n assertInputMimeTypesAdmitted(req.messages, mediaDescriptor, 'xai')\n }\n if (\n xaiRegistry.resolve('xai', model)?.capabilities?.continuation === 'state' &&\n req.modelDescriptor?.capabilities?.continuation !== 'state'\n ) {\n throw badXaiRequest(\n `A matching xAI model descriptor with continuation \"state\" 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 = req.modelDescriptor?.capabilities?.continuation === 'state'\n const replayState = parseXaiReplayState(req.transientProviderState, model)\n if (replayState !== undefined && !replayRequired) {\n throw badXaiRequest(\n `transientProviderState requires a model descriptor with continuation \"state\" 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?.xai.input ?? [])]\n const replayCallIds = new Set(\n replayState?.xai.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?.xai.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 — forwarded as given. xAI documents no output limit,\n // so the schema applies no cap (`limits.maxOutputTokens` is null) and the\n // provider decides; truncation surfaces as finishReason:'length', not an\n // 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 and grok-4.7: `'low' | 'medium' | 'high' |\n // 'xhigh'` (grok-4.6 live-verified 2026-08-12; grok-4.7 shares its\n // Responses-API surface). `'none'` is rejected by all three. 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 assertJsonSchemaProfile(\n schema as JsonValue,\n 'output.jsonSchema',\n XAI_JSON_SCHEMA_PROFILE,\n )\n const title = isPlainRecord(schema) ? schema['title'] : undefined\n // `text.format.name` is the schema's `title`. xAI documents no rule for\n // it (read 2026-10-03); the Responses API it mirrors takes\n // `^[a-zA-Z0-9_-]{1,64}$`, so that is enforced: a title outside it is\n // rejected, never rewritten, and a schema with no title is sent as\n // `structured_output`.\n if (typeof title === 'string' && !XAI_SCHEMA_NAME.test(title)) {\n throw badXaiRequest(\n `output.jsonSchema.title \"${boundedNote(title)}\" cannot be the xAI structured-output name for model \"${model}\": it must match ${XAI_SCHEMA_NAME.source} (letters, digits, \"_\" and \"-\", 1 to 64 characters). Rename the title or remove it to use \"${XAI_DEFAULT_SCHEMA_NAME}\".`,\n )\n }\n const name = typeof title === 'string' ? title : XAI_DEFAULT_SCHEMA_NAME\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 // Responses carries one request-wide `tool_choice`, and `required`\n // means \"at least one tool\" — a function call would satisfy it. The\n // option is therefore server-tool-only: it cannot promise a search\n // once function tools are declared.\n if (xaiProviderConfig.toolChoice !== undefined) {\n if (req.toolChoice !== undefined) {\n throw badXaiRequest(\n `providerOptions.xai.toolChoice and toolChoice cannot both be set for model \"${model}\"; xAI accepts one tool_choice per request.`,\n )\n }\n if (req.tools !== undefined && req.tools.length > 0) {\n throw badXaiRequest(\n `providerOptions.xai.toolChoice applies to the server-side search tools only and cannot be combined with function tools for model \"${model}\".`,\n )\n }\n // A file attachment implicitly enables xAI's `attachment_search`,\n // which is a tool too: it could satisfy `required` without a web\n // or X search. Not live-probed (the ZDR key blocks attachments).\n if (hasFileRef) {\n throw badXaiRequest(\n `providerOptions.xai.toolChoice cannot be combined with file attachments for model \"${model}\"; xAI's implicit attachment_search would count as the tool call.`,\n )\n }\n params.tool_choice = xaiProviderConfig.toolChoice\n }\n // Forwarded verbatim per the Responses contract. It caps agentic\n // turns, not individual searches, and the 2026-10-02 probes\n // (fixture 33) showed the server not enforcing it yet.\n if (xaiProviderConfig.maxTurns !== undefined) {\n params.max_turns = xaiProviderConfig.maxTurns\n }\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 req.tools.forEach((tool, index) => {\n assertJsonSchemaProfile(\n tool.inputJsonSchema,\n `tools[${index}].inputJsonSchema`,\n XAI_JSON_SCHEMA_PROFILE,\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 // It only governs how a response orders its tool calls, so with no tool\n // (function or server) on the request it has nothing to act on.\n if (params.tools === undefined || params.tools.length === 0) {\n throw badXaiRequest(\n `providerOptions.xai.parallelToolCalls requires at least one tool (function tools or providerOptions.xai.tools) for model \"${model}\".`,\n )\n }\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 let responseMeta: XaiResponseMeta | undefined\n let sdkCallStart: { startedAt: number; timeoutMs: number } | undefined\n try {\n const buildClient = seams.clientFactory ?? buildXaiClient\n const client: XaiClientLike =\n opts?.client !== undefined\n ? opts.client\n : await buildClient(ctx.auth, transport)\n ctx.logger.debug(\n { model, configKeys: Object.keys(params) },\n 'llm.adapter.dispatch',\n )\n // Request deadline: timeoutMs + buffer so the engine's own deadline\n // (armed at exactly timeoutMs) fires first; one hour when no timeoutMs\n // is set. The client sends the call as a stream (ADR-040) and applies it\n // as the SDK `timeout` (the wait for headers only, for a stream) and as\n // its own timer over the rest of the stream, so it bounds the whole\n // call. It does not move Node's 300 s header timer (that needs\n // `transport`); the stream keeps the body timer from ever going quiet,\n // and `transport.idleTimeoutMs` bounds a connection that goes quiet anyway.\n const sdkTimeoutMs =\n genConfig.timeoutMs !== undefined\n ? genConfig.timeoutMs + XAI_TIMEOUT_BUFFER_MS\n : XAI_DEFAULT_TIMEOUT_MS\n const requestOptions: XaiRequestOptions = {\n ...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),\n timeout: sdkTimeoutMs,\n onResponse: (meta) => {\n responseMeta = meta\n },\n }\n sdkCallStart = { startedAt: performance.now(), timeoutMs: sdkTimeoutMs }\n response = await client.responses.create(params, requestOptions)\n } catch (rawErr) {\n throw classifyXaiError(\n rawErr,\n sdkCallStart !== undefined\n ? {\n timeoutMs: sdkCallStart.timeoutMs,\n elapsedMs: performance.now() - sdkCallStart.startedAt,\n }\n : undefined,\n estimateWireInputTokens(params),\n genConfig.timeoutMs ?? XAI_DEFAULT_TIMEOUT_MS,\n )\n }\n\n // ------------------------------------------------------------------\n // 6b. A 200 that reports failure. DOC-DERIVED, NOT A CAPTURE: xAI's\n // reference lists `status` completed|in_progress|incomplete and names\n // an `error` object without its shape. `failed` and `cancelled`, and\n // the `error.code` values, come from OpenAI's Responses object (the\n // API xAI is compatible with), where `error` is set only when the\n // response failed. Only those two statuses are failures: an `error`\n // object beside a completed response is not a documented shape, and\n // a billed, usable answer is never thrown away for it.\n // ------------------------------------------------------------------\n if (response.status === 'failed' || response.status === 'cancelled') {\n throw failedResponseError(response, responseMeta?.streamProgressed === true)\n }\n // A terminal response that carries no token counts cannot be priced or\n // mapped. It is billed, so the attempt is unpriced and a retry would\n // repeat the spend: a typed non-retryable error, not a TypeError.\n if (\n !isPlainRecord(response.usage) ||\n typeof response.usage.input_tokens !== 'number' ||\n typeof response.usage.output_tokens !== 'number'\n ) {\n throw new LlmError(\n `xAI response ${String(response.id)} (status \"${String(response.status)}\") carries no numeric usage; it cannot be priced.`,\n {\n kind: 'server',\n retryable: false,\n provider: 'xai',\n cause: { id: response.id },\n },\n )\n }\n // What reconciling the stream with its final object had to do (ADR-040).\n for (const message of responseMeta?.streamNotes ?? []) {\n warnings.push({ type: 'other', message })\n }\n\n // ------------------------------------------------------------------\n // 7. Map response. The response is billed and complete by now, so a\n // failure to map it (a shape this version did not expect) is a typed\n // error that carries the exact usage, never a bare TypeError that\n // would lose it, and a retry would repeat the spend.\n // ------------------------------------------------------------------\n try {\n let text = ''\n const reasoningChunks: string[] = []\n const messageItems: XaiMessageOutputItem[] = []\n const toolCalls: NonNullable<AdapterResult['toolCalls']> = []\n // Function calls that did not complete: never a tool call to run.\n const droppedCalls: string[] = []\n const droppedItems = new Set<unknown>()\n // Output order of the representable items (message and function_call);\n // the assistant message is built from it once the last message item is known.\n const outputOrder: Array<\n XaiMessageOutputItem | NonNullable<AdapterResult['toolCalls']>[number]\n > = []\n\n for (const item of response.output) {\n if (isXaiMessageItem(item)) {\n messageItems.push(item)\n outputOrder.push(item)\n } else if (isXaiReasoningItem(item)) {\n for (const part of item.summary as unknown[]) {\n const summary = partText(part)\n if (summary !== undefined && summary.length > 0) {\n reasoningChunks.push(summary)\n }\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 // A response that did not complete (cut by the output cap, or ended\n // abnormally) holds no call to run: its arguments may stop mid-string,\n // and a call beside an abnormal stop is not one the model finished.\n if (\n response.status !== 'completed' ||\n (typeof item['status'] === 'string' && item['status'] !== 'completed')\n ) {\n droppedCalls.push(name.length > 0 ? name : callId)\n droppedItems.add(item)\n continue\n }\n let args: JsonValue = {}\n if (typeof item['arguments'] === 'string') {\n try {\n args = JSON.parse(item['arguments']) as JsonValue\n } catch (cause) {\n // A completed call whose arguments are not JSON cannot be run, and\n // the response is billed: a typed error that carries the usage.\n throw new LlmError(\n `xAI response ${String(response.id)} holds a completed function call \"${name}\" whose arguments are not valid JSON.`,\n {\n kind: 'server',\n retryable: false,\n provider: 'xai',\n usage: mapUsage(response.usage),\n ...(typeof response.service_tier === 'string' &&\n response.service_tier.length > 0\n ? { servedServiceTier: response.service_tier }\n : {}),\n cause,\n },\n )\n }\n }\n if (callId.length > 0 && name.length > 0) {\n const call = { toolCallId: callId, toolName: name, args }\n toolCalls.push(call)\n outputOrder.push(call)\n }\n }\n }\n const reasoningText =\n reasoningChunks.length > 0 ? reasoningChunks.join('\\n\\n') : undefined\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 let refusal: string | undefined\n if (messageItems.length > 0) {\n const lastMessage = messageItems[\n messageItems.length - 1\n ] as XaiMessageOutputItem\n const ignoredTypes = new Map<string, number>()\n for (const part of lastMessage.content as unknown[]) {\n const own = partText(part)\n if (own !== undefined) {\n text += own\n } else if (isPlainRecord(part) && part['type'] === 'refusal') {\n const said = typeof part['refusal'] === 'string' ? part['refusal'] : ''\n refusal = `${refusal === undefined ? '' : `${refusal} `}${said}`\n } else {\n const type =\n isPlainRecord(part) && typeof part['type'] === 'string'\n ? part['type']\n : 'unknown'\n ignoredTypes.set(type, (ignoredTypes.get(type) ?? 0) + 1)\n }\n }\n for (const [type, count] of ignoredTypes) {\n warnings.push({\n type: 'other',\n message: `xai: ignored ${count} message content part(s) of type \"${type}\" that carry no text; the answer text is built from the output_text parts.`,\n })\n }\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 // Ordered assistant message: provider order, the last message item as the\n // single text part (earlier ones are superseded, as for `text`), reasoning\n // and server-tool items omitted (they live in the replay state).\n const lastMessageItem = messageItems[messageItems.length - 1]\n const messageParts: Part[] = []\n for (const entry of outputOrder) {\n if ('toolCallId' in entry) {\n messageParts.push({ kind: 'tool-call', ...entry })\n } else if (entry === lastMessageItem && text.length > 0) {\n messageParts.push({ kind: 'text', text })\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 let finishReason = mapFinishReason(response)\n if (refusal !== undefined) {\n // The model declined: not a cut answer, so the cap keeps its own reason.\n if (finishReason !== 'length') finishReason = 'content_filter'\n warnings.push({\n type: 'other',\n message: `xai: the model refused to answer${\n refusal.length > 0 ? `: \"${boundedNote(refusal)}\"` : ''\n }; the result carries no text for it and finishReason is \"${finishReason}\".`,\n })\n }\n if (droppedCalls.length > 0) {\n const named = droppedCalls.map((name) => `\"${name}\"`).join(', ')\n const reason = response.incomplete_details?.reason\n warnings.push({\n type: 'other',\n message: `xai: dropped ${droppedCalls.length} function call(s) (${named}) because the response ended with status \"${String(response.status)}\"${\n typeof reason === 'string' ? ` (${reason})` : ''\n }, not \"completed\": ${\n reason === 'max_output_tokens'\n ? 'the call was cut by the output cap and its arguments are incomplete'\n : 'a call beside an abnormal end is not a call to run'\n }. The result carries no tool call; finishReason is \"${finishReason}\".`,\n })\n }\n\n const expectedToolCounters = expectedServerToolCounters(xaiProviderConfig.tools)\n // A response where no server tool ran reports\n // `num_server_side_tools_used: 0` and omits the per-tool counters\n // (live 2026-10-02, fixture 32: `tool_choice: 'none'`; the same shape\n // comes back when the model skips the search under `auto`). That is an\n // explicit zero, not a missing counter, so the call prices exactly\n // with no tool cost. A zero that arrives WITH a counters object is\n // contradictory and keeps the missing-counter checks.\n const noServerToolRan =\n response.usage['num_server_side_tools_used'] === 0 &&\n response.usage['server_side_tool_usage_details'] === undefined\n // Normalised search facts (ADR-035), the same names on every provider:\n // `web_search_requested` is 1 when the request enabled web search, and\n // `web_search_calls` is the observed count. The count comes from the\n // provider's counters; an explicit \"no server tool ran\" is a known zero.\n if (\n xaiProviderConfig.tools?.some((tool) => tool['type'] === 'web_search') === true\n ) {\n usage.details['web_search_requested'] = 1\n if (noServerToolRan) usage.details[WEB_SEARCH_COUNTER] = 0\n }\n // The call is already billed when the counters arrive, so an exceeded\n // budget is reported, never thrown: the result is still returned.\n if (xaiProviderConfig.searchBudget !== undefined) {\n const over = exceededSearchBudget(xaiProviderConfig.searchBudget, usage.details)\n if (over.length > 0) {\n usage.details['search_budget_exceeded'] = 1\n warnings.push({\n type: 'other',\n message: `xai: search budget exceeded (${over.join('; ')}); the call is already billed and its result is returned.`,\n })\n }\n }\n // A non-zero counter for a server tool that xAI bills per use and the\n // pricing snapshot has no rate for (code interpreter, file or document\n // search, image generation) is not priced here: the call is priced\n // 'estimated' and understates. A counter the snapshot does not know is\n // priced 'estimated' too, but nothing says it is billed: when the request\n // enabled image or video understanding, which xAI lists as token-priced\n // with no invocation fee (pricing page, re-read 2026-10-03; it names no\n // counter for them), the unknown counter is most likely that tool's and the\n // token cost already priced may be the whole cost. Token-only tools (MCP)\n // do not warn. With a file attachment, the attachment warning below states\n // the same fact as `document_search_calls`.\n const { feeUnpriced, unknown } = classifyUnpricedXaiToolCounters(usage)\n const shown = (keys: string[]): string =>\n keys.map((key) => `${key}=${String(usage.details[key])}`).join(', ')\n const feeCounters = hasFileRef\n ? feeUnpriced.filter((key) => key !== 'document_search_calls')\n : feeUnpriced\n if (feeCounters.length > 0) {\n warnings.push({\n type: 'other',\n message: `xai: server tool counter(s) [${shown(feeCounters)}] are non-zero but have no rate in the pricing snapshot (xAI bills the tool per use); the call's cost is estimated and understates.`,\n })\n }\n if (unknown.length > 0) {\n const understanding =\n xaiProviderConfig.tools?.some(\n (tool) =>\n tool['enable_image_understanding'] === true ||\n tool['enable_video_understanding'] === true,\n ) === true\n warnings.push({\n type: 'other',\n message: understanding\n ? `xai: server tool counter(s) [${shown(unknown)}] are not in the pricing snapshot. The request enabled image or video understanding, which xAI prices by tokens with no invocation fee, so the counter is probably that tool's and the priced token cost may be complete; the counter's name was never captured, so the call stays estimated.`\n : `xai: server tool counter(s) [${shown(unknown)}] are not in the pricing snapshot; xAI may bill the tool per use, so the call's cost is estimated and may understate.`,\n })\n }\n if ((expectedToolCounters.length > 0 || hasFileRef) && !noServerToolRan) {\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, (message) =>\n warnings.push({ type: 'other', message }),\n )\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 // The HTTP response's request id and remaining-quota headers, when the\n // client exposes them (the real client does).\n if (responseMeta !== undefined) {\n const xaiMeta: { [k: string]: JsonValue } = {}\n if (responseMeta.requestId !== undefined)\n xaiMeta['requestId'] = responseMeta.requestId\n if (responseMeta.rateLimitRemaining !== undefined) {\n xaiMeta['rateLimitRemaining'] = { ...responseMeta.rateLimitRemaining }\n }\n if (Object.keys(xaiMeta).length > 0) providerMeta['xai'] = xaiMeta\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 xai: {\n model,\n input: [\n ...params.input,\n ...response.output.filter((item) => !droppedItems.has(item)),\n ],\n },\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 message: { role: 'assistant', parts: messageParts },\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 } catch (mapErr) {\n if (mapErr instanceof LlmError) throw mapErr\n throw new LlmError(\n `xAI response ${String(response.id)} could not be mapped: ${\n mapErr instanceof Error ? mapErr.message : String(mapErr)\n }`,\n {\n kind: 'server',\n retryable: false,\n provider: 'xai',\n usage: mapUsage(response.usage),\n ...(typeof response.service_tier === 'string' &&\n response.service_tier.length > 0\n ? { servedServiceTier: response.service_tier }\n : {}),\n cause: mapErr,\n },\n )\n }\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 = seams.fetch ?? transport?.fetch ?? fetch\n\n // The call's own deadline, beside the caller's signal: a hung connection\n // must not wait forever.\n const controller = new AbortController()\n const forwardAbort = (): void => {\n controller.abort(ctx.signal?.reason)\n }\n if (ctx.signal?.aborted === true) forwardAbort()\n else ctx.signal?.addEventListener('abort', forwardAbort, { once: true })\n const timeout = new LlmError(\n `xAI tokenize-text timed out after ${countTokensTimeoutMs}ms`,\n { kind: 'timeout', retryable: true, provider: 'xai' },\n )\n const timer = setTimeout(() => {\n controller.abort(timeout)\n }, countTokensTimeoutMs)\n\n try {\n const res = await fetchImpl('https://api.x.ai/v1/tokenize-text', {\n // The host transport's init (a dispatcher, say) first; the request\n // owns the keys below, which `snapshotXaiTransport` keeps out of it.\n ...(seams.fetch === undefined ? transport?.fetchOptions : undefined),\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ model: req.model, text }),\n signal: controller.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 const requestId = res.headers.get('x-request-id')\n // `headers` lets `classifyError` read `Retry-After`; the request id is\n // what a support ticket needs.\n throw Object.assign(\n new Error(\n `xAI tokenize-text HTTP ${res.status}${\n requestId !== null && requestId !== '' ? ` (request id ${requestId})` : ''\n }`,\n ),\n { status: res.status, error: parsed, headers: res.headers },\n )\n }\n\n let raw: unknown\n try {\n raw = await res.json()\n } catch (cause) {\n if (controller.signal.aborted) throw cause\n throw new LlmError('xAI tokenize-text response is not JSON', {\n kind: 'server',\n retryable: true,\n provider: 'xai',\n cause,\n })\n }\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 (controller.signal.aborted && controller.signal.reason === timeout) {\n throw timeout\n }\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 } finally {\n clearTimeout(timer)\n ctx.signal?.removeEventListener('abort', forwardAbort)\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): 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\n/**\n * Citations from the response: the top-level source list first, then the last\n * message's `url_citation` annotations, deduplicated by URL.\n *\n * An annotation with a non-empty `start_index`/`end_index` range marks an\n * inline citation. xAI writes the marker into the answer as `[[N]](url)` and\n * the range covers exactly that marker, indexed from the start of the\n * `output_text` part that carries it (fixtures 17, 26, 30 and 32; every\n * captured message has one part). The adapter treats the indices as UTF-16\n * code units and adds the part's offset in the joined answer text, and it\n * checks the result: the slice must be `[[label]](<the annotation's url>)`.\n * When it is, the source is `cited: true` with that `textRange`, and a title\n * equal to `label` (xAI numbers its markers: `title: \"1\"`) is dropped, so a\n * real title that happens to be numeric survives. When it is not (a base\n * other than UTF-16 or part-relative, an answer with emoji or several parts\n * that xAI indexes differently), the range is dropped, the source stays\n * `cited: true` because xAI did report an inline range, and `onDropped` says\n * why: never a range that points at the wrong span.\n *\n * `cited` is never `false`. A zero-width (`0`/`0`) or missing range means xAI\n * reported no inline marker range for the source; it does not mean the answer\n * does not cite it (fixture 19: the answer text carries inline\n * `render_inline_citation` markup while its three annotations are `0`/`0`;\n * structured answers, fixtures 18 and 32, have only `0`/`0` annotations), so\n * `cited` stays absent. A source from the top-level list alone says nothing\n * about citing either.\n */\n/** `label` when `marker` is exactly `[[label]](url)`, else `undefined`. */\nfunction inlineMarkerLabel(marker: string, url: string): string | undefined {\n const tail = `]](${url})`\n return marker.startsWith('[[') &&\n marker.endsWith(tail) &&\n marker.length >= 2 + tail.length\n ? marker.slice(2, marker.length - tail.length)\n : undefined\n}\n\nfunction collectXaiCitations(\n response: XaiResponseShape,\n messageItems: XaiMessageOutputItem[],\n onDropped: (message: string) => void,\n): Citation[] {\n const byUrl = new Map<string, Citation>()\n\n const upsert = (\n url: unknown,\n title: unknown,\n markerLabel?: string,\n ): Citation | undefined => {\n if (typeof url !== 'string' || url.length === 0) return undefined\n let citation = byUrl.get(url)\n if (citation === undefined) {\n citation = { url }\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 byUrl.set(url, citation)\n }\n if (\n citation.title === undefined &&\n typeof title === 'string' &&\n title.length > 0 &&\n title !== url &&\n title !== markerLabel\n ) {\n citation.title = title\n }\n return citation\n }\n\n if (Array.isArray(response.citations)) {\n for (const item of response.citations) {\n if (typeof item === 'string') {\n upsert(item, undefined)\n } else if (isPlainRecord(item)) {\n upsert(item['url'] ?? item['uri'], item['title'])\n }\n }\n }\n\n const lastMessage = messageItems.at(-1)\n if (lastMessage !== undefined) {\n const joined = (lastMessage.content as unknown[])\n .map((part) => partText(part) ?? '')\n .join('')\n let partOffset = 0\n for (const part of lastMessage.content as unknown[]) {\n const annotations = isPlainRecord(part) ? part['annotations'] : undefined\n if (Array.isArray(annotations)) {\n for (const ann of annotations) {\n if (!isPlainRecord(ann)) continue\n if (ann['type'] !== undefined && ann['type'] !== 'url_citation') continue\n const start = ann['start_index']\n const end = ann['end_index']\n const hasRange =\n typeof start === 'number' &&\n typeof end === 'number' &&\n Number.isInteger(start) &&\n Number.isInteger(end) &&\n start >= 0 &&\n end > start\n const url = ann['url']\n const label =\n hasRange && typeof url === 'string'\n ? inlineMarkerLabel(joined.slice(partOffset + start, partOffset + end), url)\n : undefined\n const citation = upsert(url, ann['title'], label)\n if (citation === undefined || !hasRange) continue\n citation.cited = true\n if (label === undefined) {\n onDropped(\n `xai: dropped a textRange for a citation of ${citation.url}: the answer at start_index ${start}, end_index ${end} is not the inline [[N]](url) marker. The source stays cited without a range.`,\n )\n } else {\n citation.textRange ??= { start: partOffset + start, end: partOffset + end }\n }\n }\n }\n partOffset += (partText(part) ?? '').length\n }\n }\n\n return [...byUrl.values()]\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 { XAI_MAX_TIMEOUT_MS, 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 * Default deadline of one Files API call (headers and body), in milliseconds:\n * 60 s. A store with an `AbortSignal` of its own still honours it; a very large\n * upload on a slow link needs a larger `timeoutMs` in {@link XaiFileStoreOptions}.\n */\nexport const XAI_FILES_DEFAULT_TIMEOUT_MS = 60_000\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 * Deadline of each call (response headers and body) in milliseconds. A call\n * that is still open then fails with a retryable `timeout` error. An integer\n * from 1 to {@link XAI_MAX_TIMEOUT_MS}; default {@link XAI_FILES_DEFAULT_TIMEOUT_MS}.\n */\n timeoutMs?: number\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 /** The response headers: `classifyError` reads `Retry-After` from them. */\n readonly headers: Headers\n\n constructor(status: number, message: string, errorBody: unknown, headers: Headers) {\n super(message)\n this.name = 'XaiFilesHttpError'\n this.status = status\n this.error = errorBody\n this.headers = headers\n }\n}\n\nasync function throwHttpFailure(\n res: Response,\n signal: AbortSignal,\n operation: string,\n): Promise<never> {\n const status = res.status\n let bodyText = ''\n try {\n bodyText = await res.text()\n } catch (e) {\n // The call's own deadline (or the caller's abort) ended the body read: that\n // is the answer, not the status line of a response that was never read.\n if (signal.aborted) throw abortedError(signal, `xAI file ${operation} aborted`, e)\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 const requestId = res.headers.get('x-request-id')\n if (requestId !== null && requestId !== '') message += ` (request id ${requestId})`\n\n throw new XaiFilesHttpError(status, message, parsed, res.headers)\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// Per-call deadline\n// ---------------------------------------------------------------------------\n\n/** The `LlmError`s a store's own deadline timer created, to tell them from a caller's abort. */\nconst DEADLINE_ERRORS = new WeakSet()\n\n/**\n * The error a call whose `signal` aborted ends in: the store's own timeout when\n * its deadline fired, else an `aborted` error carrying the caller's reason.\n */\nfunction abortedError(signal: AbortSignal, message: string, cause?: unknown): LlmError {\n const reason: unknown = signal.reason\n if (reason instanceof LlmError && DEADLINE_ERRORS.has(reason)) return reason\n return new LlmError(message, {\n kind: 'aborted',\n retryable: false,\n provider: 'xai',\n ...(cause !== undefined ? { cause } : {}),\n })\n}\n\n/**\n * `id` as one URL path segment. `encodeURIComponent` keeps `/`, `?` and `#` in an\n * id from addressing another path; `.` and `..` survive it and are refused.\n */\nfunction pathSegment(id: string): string {\n if (id === '.' || id === '..') {\n throw badRequest(`fileId \"${id}\" is not a valid file id.`)\n }\n return encodeURIComponent(id)\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 timeoutMs: number\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 const timeoutMs = opts.timeoutMs ?? XAI_FILES_DEFAULT_TIMEOUT_MS\n if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > XAI_MAX_TIMEOUT_MS) {\n throw badRequest(\n `XaiFileStoreOptions.timeoutMs must be an integer from 1 to ${XAI_MAX_TIMEOUT_MS}.`,\n )\n }\n this.timeoutMs = timeoutMs\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 * Runs one call under the store's deadline: `run` gets a signal that aborts\n * when the caller's does or when `timeoutMs` passes (headers and body read\n * both count), and the timer is cleared however the call ends.\n */\n private async bounded<T>(\n caller: AbortSignal | undefined,\n run: (signal: AbortSignal) => Promise<T>,\n ): Promise<T> {\n const controller = new AbortController()\n const forward = (): void => {\n controller.abort(caller?.reason)\n }\n if (caller?.aborted === true) forward()\n else caller?.addEventListener('abort', forward, { once: true })\n const timer = setTimeout(() => {\n const error = new LlmError(\n `xAI Files API call timed out after ${this.timeoutMs}ms`,\n {\n kind: 'timeout',\n retryable: true,\n provider: 'xai',\n },\n )\n DEADLINE_ERRORS.add(error)\n controller.abort(error)\n }, this.timeoutMs)\n try {\n return await run(controller.signal)\n } finally {\n clearTimeout(timer)\n caller?.removeEventListener('abort', forward)\n }\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 return this.bounded(signal, async (bound) => {\n let res: Response\n try {\n res = await this.fetchImpl(\n this.filesUrl(),\n this.requestInit('POST', { body: form, signal: bound }),\n )\n } catch (e) {\n if (bound.aborted) throw abortedError(bound, 'xAI file upload aborted')\n throw classifyStoreError(e)\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res, bound, 'upload')\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 if (bound.aborted) throw abortedError(bound, 'xAI file upload aborted', 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\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 const url = this.filesUrl(pathSegment(fileId))\n\n return this.bounded(signal, async (bound) => {\n let res: Response\n try {\n res = await this.fetchImpl(url, this.requestInit('GET', { signal: bound }))\n } catch (e) {\n if (bound.aborted) throw abortedError(bound, 'xAI file get aborted')\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, bound, 'get')\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n return makeHandle((await readJsonBody(res, bound, 'get')) as VendorFileObject)\n })\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 return this.bounded(signal, async (bound) => {\n let res: Response\n try {\n res = await this.fetchImpl(url, this.requestInit('GET', { signal: bound }))\n } catch (e) {\n if (bound.aborted) throw abortedError(bound, 'xAI file list aborted')\n throw classifyStoreError(e)\n }\n\n if (!res.ok) {\n try {\n await throwHttpFailure(res, bound, 'list')\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n const json = (await readJsonBody(res, bound, 'list')) 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 /**\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 const url = this.filesUrl(pathSegment(fileId))\n\n const failClosed = opts?.failClosed === true\n\n await this.bounded(opts?.signal, async (bound) => {\n try {\n const res = await this.fetchImpl(\n url,\n this.requestInit('DELETE', { signal: bound }),\n )\n\n if (res.status === 404) {\n return\n }\n\n if (!res.ok) {\n await throwHttpFailure(res, bound, 'delete')\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 bound.aborted && !(err instanceof LlmError)\n ? abortedError(bound, 'xAI file delete aborted', err)\n : classifyStoreError(err)\n\n if (failClosed) {\n throw classified\n }\n this.onDeleteError(fileId, classified)\n }\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 const url = this.filesUrl(`${pathSegment(fileId)}/content`)\n\n return this.bounded(signal, async (bound) => {\n let res: Response\n try {\n res = await this.fetchImpl(url, this.requestInit('GET', { signal: bound }))\n } catch (e) {\n if (bound.aborted) throw abortedError(bound, 'xAI file content download aborted')\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, bound, 'getContent')\n } catch (e) {\n throw classifyStoreError(e)\n }\n }\n\n try {\n return new Uint8Array(await res.arrayBuffer())\n } catch (e) {\n if (bound.aborted)\n throw abortedError(bound, 'xAI file content download aborted', e)\n throw classifyStoreError(e)\n }\n })\n }\n}\n\n/**\n * The JSON body of a 2xx response. A body that is not JSON (a gateway page behind\n * a 200) is a typed `server` error, an abort during the read is the abort.\n */\nasync function readJsonBody(\n res: Response,\n signal: AbortSignal,\n operation: string,\n): Promise<unknown> {\n try {\n return await res.json()\n } catch (e) {\n if (signal.aborted) throw abortedError(signal, `xAI file ${operation} aborted`, e)\n throw new LlmError(`xAI file ${operation} returned a non-JSON body`, {\n kind: 'server',\n retryable: false,\n provider: 'xai',\n cause: e,\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` / `grok-4.7`\n * model 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 * `grok-4.7` 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"]}