@12-apps/llm 0.0.0-stage → 1.0.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/adapter.ts","../src/adapters/load.ts","../src/adapters/sealed-fetch.ts","../src/adapters/util.ts","../src/adapters/anthropic.ts","../src/adapters/gemini.ts","../src/adapters/openai.ts","../src/adapters/xai.ts","../src/adapters/index.ts","../src/credentials.ts","../src/schema.ts","../src/client.ts","../src/loop.ts"],"sourcesContent":["/**\n * Typed errors. Every adapter maps its SDK's failures onto these, so a host\n * decides retry, hand-off and alerting once, whatever the provider.\n *\n * No error carries a credential: messages are built here, from the provider's\n * status and its own message with any secret the call used scrubbed out.\n */\nimport type { Refusal } from \"./types\";\n\nexport type LlmErrorKind =\n | \"auth\"\n | \"rate_limit\"\n | \"refusal\"\n | \"invalid_request\"\n | \"unavailable\"\n | \"invalid_response\"\n | \"unsupported\";\n\nexport class LlmError extends Error {\n readonly kind: LlmErrorKind;\n readonly provider: string;\n /** The provider's HTTP status, when there was one. */\n readonly status: number | undefined;\n\n constructor(kind: LlmErrorKind, provider: string, message: string, status?: number) {\n super(message);\n this.name = \"LlmError\";\n this.kind = kind;\n this.provider = provider;\n this.status = status;\n }\n}\n\n/** The credential was refused (401) or lacks permission (403). */\nexport class AuthError extends LlmError {\n constructor(provider: string, message: string, status?: number) {\n super(\"auth\", provider, message, status);\n this.name = \"AuthError\";\n }\n}\n\n/** The host revoked the credential (the account was disconnected): nothing is sent or refreshed with it. */\nexport class CredentialRevokedError extends AuthError {\n constructor(provider = \"credential\") {\n super(provider, \"The credential was revoked by the host.\");\n this.name = \"CredentialRevokedError\";\n }\n}\n\n/** Too many requests. `retryAfterMs` is the provider's own hint, when given. */\nexport class RateLimitError extends LlmError {\n readonly retryAfterMs: number | undefined;\n\n constructor(provider: string, message: string, retryAfterMs?: number) {\n super(\"rate_limit\", provider, message, 429);\n this.name = \"RateLimitError\";\n this.retryAfterMs = retryAfterMs;\n }\n}\n\n/** The model declined. Thrown by `ensureNotRefused`; `chat` returns it as data. */\nexport class RefusalError extends LlmError {\n readonly refusal: Refusal;\n\n constructor(provider: string, refusal: Refusal) {\n super(\"refusal\", provider, `The model declined the request (${refusal.category ?? \"uncategorized\"}).`);\n this.name = \"RefusalError\";\n this.refusal = refusal;\n }\n}\n\n/** The request itself is wrong (400, 404, 413, 422) and will fail again as is. */\nexport class InvalidRequestError extends LlmError {\n constructor(provider: string, message: string, status?: number) {\n super(\"invalid_request\", provider, message, status);\n this.name = \"InvalidRequestError\";\n }\n}\n\n/** The provider is down, overloaded or unreachable (5xx, 529, network). */\nexport class ProviderUnavailableError extends LlmError {\n constructor(provider: string, message: string, status?: number) {\n super(\"unavailable\", provider, message, status);\n this.name = \"ProviderUnavailableError\";\n }\n}\n\n/** The provider answered with something this package cannot read. */\nexport class InvalidResponseError extends LlmError {\n constructor(provider: string, message: string) {\n super(\"invalid_response\", provider, message);\n this.name = \"InvalidResponseError\";\n }\n}\n\n/** A provider, credential kind or capability nobody registered or declared. */\nexport class UnsupportedError extends LlmError {\n constructor(provider: string, message: string) {\n super(\"unsupported\", provider, message);\n this.name = \"UnsupportedError\";\n }\n}\n\ninterface ErrorShape {\n status?: unknown;\n headers?: unknown;\n message?: unknown;\n name?: unknown;\n}\n\nfunction headerValue(headers: unknown, name: string): string | undefined {\n if (!headers || typeof headers !== \"object\") return undefined;\n const getter = (headers as { get?: unknown }).get;\n if (typeof getter === \"function\") {\n const value: unknown = getter.call(headers, name);\n return typeof value === \"string\" ? value : undefined;\n }\n const value = (headers as Record<string, unknown>)[name];\n return typeof value === \"string\" ? value : undefined;\n}\n\n/** `retry-after-ms`, else `retry-after` in seconds or as an HTTP date. */\nexport function retryAfterFrom(headers: unknown, now: () => number = Date.now): number | undefined {\n const ms = Number(headerValue(headers, \"retry-after-ms\"));\n if (Number.isFinite(ms) && ms >= 0 && headerValue(headers, \"retry-after-ms\") !== undefined) return ms;\n const raw = headerValue(headers, \"retry-after\");\n if (raw === undefined) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n const date = Date.parse(raw);\n return Number.isNaN(date) ? undefined : Math.max(0, date - now());\n}\n\n/** Replace every occurrence of each secret with a marker. */\nfunction redact(text: string, secrets: readonly string[]): string {\n return secrets.reduce(\n (out, secret) => (secret.length >= 4 ? out.split(secret).join(\"[redacted]\") : out),\n text,\n );\n}\n\nconst CONNECTION_ERROR = /connection|timeout|fetch failed|network|ECONN|ETIMEDOUT|ENOTFOUND|socket/i;\n\nfunction shapeOf(error: unknown): ErrorShape {\n return error && typeof error === \"object\" ? (error as ErrorShape) : {};\n}\n\nfunction messageOf(shape: ErrorShape, error: unknown): string {\n return typeof shape.message === \"string\" ? shape.message : String(error);\n}\n\n/** The typed error for an HTTP status, or null when the status says nothing. */\nfunction errorForStatus(provider: string, status: number, message: string, headers: unknown): LlmError | null {\n if (status === 401 || status === 403) return new AuthError(provider, message, status);\n if (status === 429) return new RateLimitError(provider, message, retryAfterFrom(headers));\n if (status >= 500 || status === 408) return new ProviderUnavailableError(provider, message, status);\n if (status >= 400) return new InvalidRequestError(provider, message, status);\n return null;\n}\n\n/**\n * Map any SDK error onto the taxonomy by its HTTP status (every official SDK\n * exposes `status`), so an adapter needs no SDK class import. An `LlmError`\n * passes through untouched, and so does anything that is not a provider\n * failure (an abort, a bug, a host exception).\n */\nexport function mapProviderError(provider: string, error: unknown, secrets: readonly string[] = []): unknown {\n if (error instanceof LlmError) return error;\n const shape = shapeOf(error);\n if (shape.name === \"AbortError\" || shape.name === \"APIUserAbortError\") return error;\n const text = redact(messageOf(shape, error), secrets);\n const message = `${provider}: ${text}`;\n if (typeof shape.status === \"number\") {\n return errorForStatus(provider, shape.status, message, shape.headers) ?? error;\n }\n return CONNECTION_ERROR.test(`${String(shape.name)} ${text}`) ? new ProviderUnavailableError(provider, message) : error;\n}\n","/**\n * The adapter port and the registry the factory picks adapters from.\n *\n * An adapter is the ONLY place a provider's API shape lives. It declares what\n * it can do (`capabilities`) and which credential strategies its provider\n * accepts (`credentialKinds`), and turns one `ChatRequest` into one\n * `ChatResult` with the credential it is handed. Retry, OAuth refresh and the\n * strict-schema check are the client's, so an adapter never repeats them.\n */\nimport type { CredentialKind, ResolvedCredential } from \"./credentials\";\nimport { UnsupportedError } from \"./errors\";\nimport type { Capability, ChatRequest, ChatResult } from \"./types\";\n\n/** What the client hands an adapter for one call. */\nexport interface ChatCall {\n model: string;\n request: ChatRequest;\n credential: ResolvedCredential;\n}\n\nexport interface ProviderAdapter {\n /** The provider id a host names in `createModelClient({ provider })`. */\n readonly id: string;\n /** Used when the host names no model; an adapter may ship none. */\n readonly defaultModel?: string;\n readonly capabilities: readonly Capability[];\n readonly credentialKinds: readonly CredentialKind[];\n /**\n * Run one chat turn. Throws the package's typed errors (map an SDK failure\n * with `mapProviderError`); a refusal is a RESULT, not an error.\n */\n chat(call: ChatCall): Promise<ChatResult>;\n}\n\nexport interface RegisterOptions {\n /** Replace an adapter already registered under the same id. */\n replace?: boolean;\n}\n\nexport interface AdapterRegistry {\n register(adapter: ProviderAdapter, options?: RegisterOptions): AdapterRegistry;\n get(id: string): ProviderAdapter;\n has(id: string): boolean;\n ids(): string[];\n}\n\n/**\n * A registry of adapters, keyed by provider id. A host adds its own adapter\n * (or replaces a built-in one, say with a different base URL) with\n * `register`, without touching this package.\n */\nexport function createAdapterRegistry(adapters: readonly ProviderAdapter[] = []): AdapterRegistry {\n const byId = new Map<string, ProviderAdapter>();\n const registry: AdapterRegistry = {\n register(adapter, options = {}) {\n if (byId.has(adapter.id) && !options.replace) {\n throw new TypeError(\n `@12-apps/llm: an adapter for \"${adapter.id}\" is already registered; pass { replace: true } to replace it.`,\n );\n }\n byId.set(adapter.id, adapter);\n return registry;\n },\n get(id) {\n const adapter = byId.get(id);\n if (!adapter) {\n throw new UnsupportedError(id, `No adapter is registered for provider \"${id}\" (registered: ${[...byId.keys()].join(\", \") || \"none\"}).`);\n }\n return adapter;\n },\n has: (id) => byId.has(id),\n ids: () => [...byId.keys()],\n };\n for (const adapter of adapters) registry.register(adapter);\n return registry;\n}\n","/**\n * Load a provider SDK on first use. The SDKs are OPTIONAL peers: a host that\n * only talks to one provider installs one SDK, and an adapter whose SDK is\n * missing fails with a typed error naming the package to install.\n */\nimport { UnsupportedError } from \"../errors\";\n\nexport async function loadSdk<T>(provider: string, packageName: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (error) {\n const code = (error as { code?: unknown }).code;\n if (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") {\n throw new UnsupportedError(provider, `The \"${provider}\" adapter needs the optional peer \"${packageName}\"; install it, or pass a client.`);\n }\n throw error;\n }\n}\n","/**\n * The edge every built-in adapter sends through (FUT-3738, review item B3).\n *\n * A store's own key must reach its provider ALONE. The SDKs read the process\n * environment for anything left unset — a base URL, an organisation or\n * project, custom headers, a second token — so a platform's `OPENAI_*`,\n * `ANTHROPIC_*` or `GOOGLE_*` variables would ride along on a store's call:\n * billed to the platform's project, routed to the platform's proxy, or\n * authenticated twice. The adapters pass every such option explicitly, and\n * this `fetch` is the second layer, the shape of a credential gateway: it\n * pins the request to the adapter's own base URL, drops every auth and\n * tenant-routing header the SDK set, and sets only the call's credential.\n */\nimport { InvalidRequestError } from \"../errors\";\n\n/** Headers that authenticate a request or bill it to an account. */\nconst ACCOUNT_HEADERS = [\n \"authorization\",\n \"api-key\",\n \"x-api-key\",\n \"x-goog-api-key\",\n \"x-goog-user-project\",\n \"openai-organization\",\n \"openai-project\",\n] as const;\n\n/** The SDKs' \"extra headers\" variables, as `Name: value` lines. */\nconst CUSTOM_HEADER_VARIABLES = [\"OPENAI_CUSTOM_HEADERS\", \"ANTHROPIC_CUSTOM_HEADERS\"] as const;\n\n/** The header a custom-headers line names, with its value; null for a line the SDKs skip or `Headers` rejects. */\nfunction parseLine(line: string): [string, string] | null {\n const colon = line.indexOf(\":\");\n if (colon < 0) return null;\n const name = line.slice(0, colon).trim().toLowerCase();\n const value = line.slice(colon + 1).trim();\n try {\n new Headers().set(name, value);\n } catch {\n return null; // a name or value `Headers` rejects was never sent either\n }\n return [name, value];\n}\n\nfunction parseCustomHeaders(): Array<[string, string]> {\n const lines = CUSTOM_HEADER_VARIABLES.flatMap((variable) =>\n (typeof process === \"undefined\" ? \"\" : (process.env[variable] ?? \"\")).split(/\\r?\\n/),\n );\n return lines.map(parseLine).filter((pair): pair is [string, string] => pair !== null);\n}\n\n/** Drop the platform's custom headers, but never one the adapter set itself with another value. */\nfunction dropPlatformHeaders(headers: Headers): void {\n for (const [name, value] of parseCustomHeaders()) {\n if (headers.get(name) === value) headers.delete(name);\n }\n}\n\n/** One request an adapter makes: its method and its path under the base URL (exact string or pattern). */\nexport interface SealRoute {\n method: \"GET\" | \"POST\";\n /** Relative to the base URL's path, e.g. `/v1/messages`. */\n path: string | RegExp;\n}\n\ninterface SealOptions {\n provider: string;\n /** The only origin and path prefix a request may go to. */\n baseURL: string;\n /** The only requests the adapter makes; any other path or method under the base URL is refused. */\n routes: readonly SealRoute[];\n /** The call's own credential headers, set last. */\n auth: Readonly<Record<string, string>>;\n /** The host's `fetch` (a proxy, a test double); the global one otherwise. */\n fetch?: typeof globalThis.fetch;\n}\n\nfunction within(url: URL, base: URL): boolean {\n const prefix = base.pathname.endsWith(\"/\") ? base.pathname : `${base.pathname}/`;\n return url.origin === base.origin && (url.pathname === base.pathname || url.pathname.startsWith(prefix));\n}\n\n/** The URL's path relative to the base URL's path (`within` already holds). */\nfunction relativePath(url: URL, base: URL): string {\n const root = base.pathname.replace(/\\/$/, \"\");\n return url.pathname.slice(root.length) || \"/\";\n}\n\nfunction allowed(routes: readonly SealRoute[], method: string, path: string): boolean {\n return routes.some((route) => route.method === method && (typeof route.path === \"string\" ? route.path === path : route.path.test(path)));\n}\n\nexport function sealedFetch(options: SealOptions): typeof globalThis.fetch {\n const base = new URL(options.baseURL);\n const send = options.fetch ?? globalThis.fetch;\n const sealed = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {\n const outgoing = new Request(input, init);\n if (!within(new URL(outgoing.url), base)) {\n throw new InvalidRequestError(options.provider, `Refused a request outside the adapter's base URL (${base.origin}${base.pathname}).`);\n }\n if (!allowed(options.routes, outgoing.method, relativePath(new URL(outgoing.url), base))) {\n throw new InvalidRequestError(options.provider, `Refused a ${outgoing.method} request to a path the adapter does not use.`);\n }\n const headers = new Headers(outgoing.headers);\n for (const name of ACCOUNT_HEADERS) headers.delete(name);\n dropPlatformHeaders(headers);\n for (const [name, value] of Object.entries(options.auth)) headers.set(name, value);\n const body = outgoing.method === \"GET\" || outgoing.method === \"HEAD\" ? undefined : await outgoing.arrayBuffer();\n // Never followed: a redirect would carry the call's credential headers to another origin.\n const response = await send(outgoing.url, { method: outgoing.method, headers, body, signal: outgoing.signal, redirect: \"manual\" });\n if (response.type === \"opaqueredirect\" || (response.status >= 300 && response.status < 400)) {\n throw new InvalidRequestError(options.provider, \"The provider answered with a redirect, which is never followed.\", response.status);\n }\n return response;\n };\n return sealed as typeof globalThis.fetch;\n}\n","/** Pieces every built-in adapter's response mapping shares. */\nimport type { Refusal, StopReason } from \"../types\";\n\n/** A token count the provider may have left out or nulled. */\nexport function count(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\n/** The refusal of a result, or null when the turn was not refused. */\nexport function refusalOf(stopReason: StopReason, category: string | null, explanation: string | null): Refusal | null {\n return stopReason === \"refusal\" ? { category, explanation } : null;\n}\n","/**\n * The Anthropic adapter, over the official `@anthropic-ai/sdk` (an optional\n * peer, imported only when this adapter builds its own client).\n *\n * Mapping notes:\n * - System blocks keep their order; a block marked `cache` carries a\n * `cache_control` breakpoint. Tools render before the system prompt, so the\n * first breakpoint also caches the tool list. At most four breakpoints in\n * all, `cacheConversation` included (the API's limit).\n * - Tools are sent with `strict: true`. `toolChoice: \"required\"` becomes\n * `{ type: \"any\" }`, which some models refuse: steer with the prompt there.\n * - `effort` becomes `output_config.effort`. `temperature` is dropped: the\n * current Messages API refuses sampling parameters.\n * - An assistant turn this adapter produced is replayed from `raw`, so\n * thinking blocks go back unchanged inside a tool loop.\n */\nimport type Anthropic from \"@anthropic-ai/sdk\";\n\nimport type { ChatCall, ProviderAdapter } from \"../adapter\";\nimport type { ResolvedCredential } from \"../credentials\";\nimport { InvalidRequestError, InvalidResponseError, mapProviderError } from \"../errors\";\nimport type { ChatResult, Message, StopReason, SystemBlock, ToolCall, Usage } from \"../types\";\nimport { loadSdk } from \"./load\";\nimport { sealedFetch, type SealRoute } from \"./sealed-fetch\";\nimport { count, refusalOf } from \"./util\";\n\nexport const ANTHROPIC_PROVIDER = \"anthropic\";\nexport const ANTHROPIC_DEFAULT_MODEL = \"claude-haiku-5-5\";\nconst OAUTH_BETA = \"oauth-2025-04-20\";\nconst MAX_BREAKPOINTS = 4;\n\n/**\n * The slice of the SDK client this adapter calls. `params` is the SDK's\n * `MessageCreateParamsNonStreaming`; it is typed `never` here so this\n * package's public types do not require the optional SDK to be installed.\n */\nexport interface AnthropicClientLike {\n messages: {\n create(params: never, options?: { signal?: AbortSignal }): Promise<unknown>;\n };\n}\n\nexport interface AnthropicAdapterOptions {\n /** Build the SDK client for one call (tests inject a recording fake). */\n client?: (credential: ResolvedCredential) => AnthropicClientLike | Promise<AnthropicClientLike>;\n baseURL?: string;\n /** The `fetch` the SDK sends with (a proxy, a test double). */\n fetch?: typeof globalThis.fetch;\n defaultModel?: string;\n}\n\n/** Where Anthropic's API lives; never read from the environment (B3). */\nexport const ANTHROPIC_BASE_URL = \"https://api.anthropic.com\";\n\n/** The one endpoint the adapter calls. */\nexport const ANTHROPIC_ROUTES: readonly SealRoute[] = [{ method: \"POST\", path: \"/v1/messages\" }];\n\n/**\n * Both credential options are passed, the unused one as `null`: an option left\n * unset is read from `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN`, and a\n * store's key would go out beside the platform's token (B3). The base URL is\n * explicit for the same reason (`ANTHROPIC_BASE_URL`), and the sealed fetch\n * sends only this credential.\n */\nasync function defaultClient(credential: ResolvedCredential, options: AnthropicAdapterOptions): Promise<AnthropicClientLike> {\n const sdk = await loadSdk(ANTHROPIC_PROVIDER, \"@anthropic-ai/sdk\", () => import(\"@anthropic-ai/sdk\"));\n const Client = sdk.default;\n const baseURL = options.baseURL ?? ANTHROPIC_BASE_URL;\n const apiKey = credential.kind === \"apiKey\";\n const auth: Record<string, string> = apiKey ? { \"x-api-key\": credential.secret } : { authorization: `Bearer ${credential.secret}` };\n const common = { baseURL, fetch: sealedFetch({ provider: ANTHROPIC_PROVIDER, baseURL, routes: ANTHROPIC_ROUTES, auth, fetch: options.fetch }), maxRetries: 0 };\n return apiKey\n ? new Client({ ...common, apiKey: credential.secret, authToken: null })\n : new Client({ ...common, apiKey: null, authToken: credential.secret, defaultHeaders: { \"anthropic-beta\": OAUTH_BETA } });\n}\n\nfunction cacheControl(cache: SystemBlock[\"cache\"]): Anthropic.CacheControlEphemeral | undefined {\n if (!cache) return undefined;\n return cache === true ? { type: \"ephemeral\" } : { type: \"ephemeral\", ttl: cache.ttl };\n}\n\nfunction toSystem(blocks: readonly SystemBlock[]): Anthropic.TextBlockParam[] {\n return blocks.map((block) => {\n const control = cacheControl(block.cache);\n return control ? { type: \"text\", text: block.text, cache_control: control } : { type: \"text\", text: block.text };\n });\n}\n\nfunction assistantContent(message: Extract<Message, { role: \"assistant\" }>): Anthropic.ContentBlockParam[] {\n if (message.raw?.provider === ANTHROPIC_PROVIDER && Array.isArray(message.raw.content)) {\n return message.raw.content as Anthropic.ContentBlockParam[];\n }\n const blocks: Anthropic.ContentBlockParam[] = message.text ? [{ type: \"text\", text: message.text }] : [];\n for (const call of message.toolCalls) {\n blocks.push({ type: \"tool_use\", id: call.id, name: call.name, input: call.input });\n }\n return blocks;\n}\n\nfunction toMessages(messages: readonly Message[]): Anthropic.MessageParam[] {\n return messages.map((message): Anthropic.MessageParam => {\n if (message.role === \"user\") return { role: \"user\", content: message.text };\n if (message.role === \"assistant\") return { role: \"assistant\", content: assistantContent(message) };\n return {\n role: \"user\",\n content: message.results.map((result) => ({\n type: \"tool_result\" as const,\n tool_use_id: result.callId,\n content: result.output,\n ...(result.isError ? { is_error: true } : {}),\n })),\n };\n });\n}\n\nfunction toToolChoice(choice: ChatCall[\"request\"][\"toolChoice\"]): Anthropic.ToolChoice | undefined {\n if (choice === \"none\") return { type: \"none\" };\n if (choice === \"required\") return { type: \"any\" };\n return choice === \"auto\" ? { type: \"auto\" } : undefined;\n}\n\nexport function toAnthropicParams(call: ChatCall): Anthropic.MessageCreateParamsNonStreaming {\n const { request, model } = call;\n const system = request.system ?? [];\n const breakpoints = system.filter((block) => block.cache).length + (request.cacheConversation ? 1 : 0);\n if (breakpoints > MAX_BREAKPOINTS) {\n throw new InvalidRequestError(ANTHROPIC_PROVIDER, `At most ${MAX_BREAKPOINTS} cache breakpoints per request; this one has ${breakpoints}.`);\n }\n const params: Anthropic.MessageCreateParamsNonStreaming = {\n model,\n max_tokens: request.maxOutputTokens,\n messages: toMessages(request.messages),\n };\n if (system.length > 0) params.system = toSystem(system);\n if (request.tools && request.tools.length > 0) {\n params.tools = request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema as Anthropic.Tool.InputSchema,\n strict: true,\n }));\n }\n const toolChoice = toToolChoice(request.toolChoice);\n if (toolChoice) params.tool_choice = toolChoice;\n if (request.effort) params.output_config = { effort: request.effort };\n if (request.cacheConversation) params.cache_control = { type: \"ephemeral\" };\n return params;\n}\n\nconst STOP_REASONS: Record<string, StopReason> = {\n end_turn: \"end\",\n stop_sequence: \"end\",\n tool_use: \"tool_use\",\n max_tokens: \"max_tokens\",\n model_context_window_exceeded: \"max_tokens\",\n refusal: \"refusal\",\n};\n\nfunction toUsage(usage: Anthropic.Usage | undefined): Usage {\n return {\n inputTokens: count(usage?.input_tokens),\n cacheCreationTokens: count(usage?.cache_creation_input_tokens),\n cacheReadTokens: count(usage?.cache_read_input_tokens),\n outputTokens: count(usage?.output_tokens),\n raw: usage ?? null,\n };\n}\n\nfunction textOf(content: readonly Anthropic.ContentBlock[]): string {\n return content\n .filter((block): block is Anthropic.TextBlock => block.type === \"text\")\n .map((block) => block.text)\n .join(\"\");\n}\n\nfunction toolCallsOf(content: readonly Anthropic.ContentBlock[]): ToolCall[] {\n return content\n .filter((block): block is Anthropic.ToolUseBlock => block.type === \"tool_use\")\n .map((block) => ({ id: block.id, name: block.name, input: block.input }));\n}\n\nfunction stopReasonOf(reason: string | null): StopReason {\n return (reason && STOP_REASONS[reason]) || \"other\";\n}\n\nfunction refusalDetails(details: Anthropic.RefusalStopDetails | null | undefined): [string | null, string | null] {\n return [details?.category ?? null, details?.explanation ?? null];\n}\n\nfunction fromAnthropicMessage(response: Anthropic.Message, model: string): ChatResult {\n if (!response || !Array.isArray(response.content)) {\n throw new InvalidResponseError(ANTHROPIC_PROVIDER, \"The response carries no content array.\");\n }\n const text = textOf(response.content);\n const toolCalls = toolCallsOf(response.content);\n const providerStopReason = response.stop_reason ?? null;\n const stopReason = stopReasonOf(providerStopReason);\n return {\n provider: ANTHROPIC_PROVIDER,\n model: response.model || model,\n text,\n toolCalls,\n stopReason,\n providerStopReason,\n refusal: refusalOf(stopReason, ...refusalDetails(response.stop_details)),\n usage: toUsage(response.usage),\n message: { role: \"assistant\", text, toolCalls, raw: { provider: ANTHROPIC_PROVIDER, content: response.content } },\n };\n}\n\nexport function anthropicAdapter(options: AnthropicAdapterOptions = {}): ProviderAdapter {\n const build = options.client ?? ((credential: ResolvedCredential) => defaultClient(credential, options));\n return {\n id: ANTHROPIC_PROVIDER,\n defaultModel: options.defaultModel ?? ANTHROPIC_DEFAULT_MODEL,\n capabilities: [\"chat\"],\n credentialKinds: [\"apiKey\", \"oauth\"],\n async chat(call) {\n const params = toAnthropicParams(call);\n const client = await build(call.credential);\n let response: unknown;\n try {\n response = await client.messages.create(params as never, call.request.signal ? { signal: call.request.signal } : undefined);\n } catch (error) {\n throw mapProviderError(ANTHROPIC_PROVIDER, error, [call.credential.secret]);\n }\n return fromAnthropicMessage(response as Anthropic.Message, call.model);\n },\n };\n}\n","/**\n * The Gemini adapter, over the official Google GenAI SDK (`@google/genai`, an\n * optional peer, imported only when this adapter builds its own client).\n *\n * Mapping notes:\n * - System blocks become `systemInstruction` parts, in order. The Gemini API\n * caches repeated prefixes implicitly; explicit cached contents are a\n * separate resource this adapter does not manage, so `cache` breakpoints,\n * `cacheConversation` and `cacheKey` have nothing to map to.\n * - Tools become function declarations with `parametersJsonSchema` (JSON\n * Schema, `additionalProperties` included). `toolChoice` becomes the\n * function-calling mode (`required` is `ANY`).\n * - `effort` becomes `thinkingConfig.thinkingLevel`; `temperature` is passed.\n * - Usage: `promptTokenCount` includes the cached tokens; output counts the\n * candidates plus the thinking tokens, which Gemini bills as output.\n * - A model turn this adapter produced is replayed from `raw`, so thought\n * signatures go back unchanged inside a tool loop.\n * - Credentials: an API key, or a Google OAuth access token for the Gemini\n * API (Google's own OAuth, which its terms allow for this API).\n */\nimport type { Content, GenerateContentParameters, GenerateContentResponse, Part } from \"@google/genai\";\n\nimport type { ChatCall, ProviderAdapter } from \"../adapter\";\nimport type { ResolvedCredential } from \"../credentials\";\nimport { InvalidRequestError, InvalidResponseError, mapProviderError } from \"../errors\";\nimport type { ChatResult, Effort, Message, StopReason, ToolCall, ToolChoice, Usage } from \"../types\";\nimport { loadSdk } from \"./load\";\nimport { sealedFetch, type SealRoute } from \"./sealed-fetch\";\nimport { count, refusalOf } from \"./util\";\n\nexport const GEMINI_PROVIDER = \"gemini\";\n\n/**\n * The slice of the SDK client this adapter calls. `params` is the SDK's\n * `GenerateContentParameters`, typed `never` here so this package's public\n * types do not require the optional SDK to be installed.\n */\nexport interface GeminiClientLike {\n models: {\n generateContent(params: never): Promise<unknown>;\n };\n}\n\nexport interface GeminiAdapterOptions {\n /** Build the SDK client for one call (tests inject a recording fake). */\n client?: (credential: ResolvedCredential) => GeminiClientLike | Promise<GeminiClientLike>;\n baseURL?: string;\n /** The `fetch` the SDK sends with (a proxy, a test double). */\n fetch?: typeof globalThis.fetch;\n defaultModel?: string;\n}\n\n/** A google-auth `AuthClient` stand-in that only ever sends the host's token. */\nfunction bearerAuthClient(token: string) {\n return { getRequestHeaders: async () => new Headers({ Authorization: `Bearer ${token}` }) };\n}\n\n/** Where the Gemini API lives; never read from the environment (B3). */\nexport const GEMINI_BASE_URL = \"https://generativelanguage.googleapis.com/\";\n\n/** The one endpoint the adapter calls: `models.generateContent`. */\nexport const GEMINI_ROUTES: readonly SealRoute[] = [{ method: \"POST\", path: /^\\/v1(?:beta)?\\/models\\/[^/:]+:generateContent$/ }];\n\n/**\n * `vertexai: false` and the base URL are explicit: unset, the SDK reads\n * `GOOGLE_GENAI_USE_VERTEXAI`, `GOOGLE_CLOUD_PROJECT` and\n * `GOOGLE_GEMINI_BASE_URL`, and a store's key would be sent to the platform's\n * Vertex project or proxy (B3). The sealed fetch sends only this credential.\n */\nasync function defaultClient(credential: ResolvedCredential, options: GeminiAdapterOptions): Promise<GeminiClientLike> {\n const sdk = await loadSdk(GEMINI_PROVIDER, \"@google/genai\", () => import(\"@google/genai\"));\n const baseUrl = options.baseURL ?? GEMINI_BASE_URL;\n const auth: Record<string, string> =\n credential.kind === \"apiKey\" ? { \"x-goog-api-key\": credential.secret } : { authorization: `Bearer ${credential.secret}` };\n const httpOptions = { baseUrl, fetch: sealedFetch({ provider: GEMINI_PROVIDER, baseURL: baseUrl, routes: GEMINI_ROUTES, auth, fetch: options.fetch }) };\n if (credential.kind === \"apiKey\") return new sdk.GoogleGenAI({ vertexai: false, apiKey: credential.secret, httpOptions });\n const client = new sdk.GoogleGenAI({\n vertexai: false,\n httpOptions,\n googleAuthOptions: { authClient: bearerAuthClient(credential.secret) as never },\n });\n // The SDK falls back to GOOGLE_API_KEY / GEMINI_API_KEY when no key is\n // passed, and a key would be sent instead of the token: refuse that.\n if ((client as unknown as { apiKey?: string }).apiKey !== undefined) {\n throw new InvalidRequestError(GEMINI_PROVIDER, \"An API key in the environment would replace the OAuth token; unset it or use apiKey credentials.\");\n }\n return client;\n}\n\nfunction assistantContent(message: Extract<Message, { role: \"assistant\" }>): Content {\n if (message.raw?.provider === GEMINI_PROVIDER && message.raw.content && typeof message.raw.content === \"object\") {\n return message.raw.content as Content;\n }\n const parts: Part[] = message.text ? [{ text: message.text }] : [];\n for (const call of message.toolCalls) {\n parts.push({ functionCall: { id: call.id, name: call.name, args: (call.input ?? {}) as Record<string, unknown> } });\n }\n return { role: \"model\", parts };\n}\n\nfunction toContents(messages: readonly Message[]): Content[] {\n return messages.map((message): Content => {\n if (message.role === \"user\") return { role: \"user\", parts: [{ text: message.text }] };\n if (message.role === \"assistant\") return assistantContent(message);\n return {\n role: \"user\",\n parts: message.results.map((result) => ({\n functionResponse: {\n id: result.callId,\n name: result.name,\n response: result.isError ? { error: result.output } : { output: result.output },\n },\n })),\n };\n });\n}\n\nconst MODES: Record<ToolChoice, string> = { auto: \"AUTO\", none: \"NONE\", required: \"ANY\" };\nconst LEVELS: Record<Effort, string> = { low: \"LOW\", medium: \"MEDIUM\", high: \"HIGH\" };\n\ntype GeminiConfig = NonNullable<GenerateContentParameters[\"config\"]>;\n\nexport function toGeminiParams(call: ChatCall): GenerateContentParameters {\n const { request, model } = call;\n const config: GeminiConfig = { maxOutputTokens: request.maxOutputTokens };\n if (request.system && request.system.length > 0) {\n config.systemInstruction = { parts: request.system.map((block) => ({ text: block.text })) };\n }\n if (request.tools && request.tools.length > 0) {\n config.tools = [\n {\n functionDeclarations: request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parametersJsonSchema: tool.inputSchema,\n })),\n },\n ];\n }\n if (request.toolChoice) {\n config.toolConfig = { functionCallingConfig: { mode: MODES[request.toolChoice] as never } };\n }\n if (request.effort) config.thinkingConfig = { thinkingLevel: LEVELS[request.effort] as never };\n if (request.temperature !== undefined) config.temperature = request.temperature;\n if (request.signal) config.abortSignal = request.signal;\n return { model, contents: toContents(request.messages), config };\n}\n\nconst REFUSALS = new Set([\"SAFETY\", \"RECITATION\", \"BLOCKLIST\", \"PROHIBITED_CONTENT\", \"SPII\", \"IMAGE_SAFETY\"]);\n\nfunction stopReasonOf(finish: string | undefined, hasCalls: boolean): StopReason {\n if (finish && REFUSALS.has(finish)) return \"refusal\";\n if (finish === \"MAX_TOKENS\") return \"max_tokens\";\n if (hasCalls) return \"tool_use\";\n return finish === \"STOP\" ? \"end\" : \"other\";\n}\n\nfunction toUsage(usage: GenerateContentResponse[\"usageMetadata\"]): Usage {\n const cacheRead = count(usage?.cachedContentTokenCount);\n const prompt = count(usage?.promptTokenCount) + count(usage?.toolUsePromptTokenCount);\n return {\n inputTokens: Math.max(0, prompt - cacheRead),\n cacheCreationTokens: 0,\n cacheReadTokens: cacheRead,\n outputTokens: count(usage?.candidatesTokenCount) + count(usage?.thoughtsTokenCount),\n raw: usage ?? null,\n };\n}\n\nfunction textOf(parts: readonly Part[]): string {\n return parts\n .filter((part) => typeof part.text === \"string\" && !part.thought)\n .map((part) => part.text)\n .join(\"\");\n}\n\nfunction toolCallsOf(parts: readonly Part[]): ToolCall[] {\n return parts.flatMap((part, index): ToolCall[] => {\n const call = part.functionCall;\n if (!call) return [];\n return [{ id: call.id ?? `gemini_call_${index}`, name: call.name ?? \"\", input: call.args ?? {} }];\n });\n}\n\n/** Why the turn stopped: a blocked prompt first, then the candidate's finish reason. */\nfunction stopOf(response: GenerateContentResponse, hasCalls: boolean): { stopReason: StopReason; provider: string | null } {\n const blocked = response.promptFeedback?.blockReason as string | undefined;\n if (blocked) return { stopReason: \"refusal\", provider: blocked };\n const finish = (response.candidates?.[0]?.finishReason as string | undefined) ?? null;\n return { stopReason: stopReasonOf(finish ?? undefined, hasCalls), provider: finish };\n}\n\nfunction fromGeminiResponse(response: GenerateContentResponse, model: string): ChatResult {\n if (!response || typeof response !== \"object\") {\n throw new InvalidResponseError(GEMINI_PROVIDER, \"The response is empty.\");\n }\n const parts = response.candidates?.[0]?.content?.parts ?? [];\n const text = textOf(parts);\n const toolCalls = toolCallsOf(parts);\n const { stopReason, provider } = stopOf(response, toolCalls.length > 0);\n const content: Content = { role: \"model\", parts };\n return {\n provider: GEMINI_PROVIDER,\n model: response.modelVersion || model,\n text,\n toolCalls,\n stopReason,\n providerStopReason: provider,\n refusal: refusalOf(stopReason, provider, response.promptFeedback?.blockReasonMessage ?? null),\n usage: toUsage(response.usageMetadata),\n message: { role: \"assistant\", text, toolCalls, raw: { provider: GEMINI_PROVIDER, content } },\n };\n}\n\nexport function geminiAdapter(options: GeminiAdapterOptions = {}): ProviderAdapter {\n const build = options.client ?? ((credential: ResolvedCredential) => defaultClient(credential, options));\n return {\n id: GEMINI_PROVIDER,\n defaultModel: options.defaultModel,\n capabilities: [\"chat\"],\n credentialKinds: [\"apiKey\", \"oauth\"],\n async chat(call) {\n const params = toGeminiParams(call);\n const client = await build(call.credential);\n let response: unknown;\n try {\n response = await client.models.generateContent(params as never);\n } catch (error) {\n throw mapProviderError(GEMINI_PROVIDER, error, [call.credential.secret]);\n }\n return fromGeminiResponse(response as GenerateContentResponse, call.model);\n },\n };\n}\n","/**\n * The OpenAI adapter, over the official `openai` SDK's Chat Completions API\n * with function tools (an optional peer, imported only when this adapter\n * builds its own client).\n *\n * Mapping notes:\n * - System blocks become one system message, its text parts in order.\n * OpenAI caches prompt prefixes by itself, so `cache` breakpoints and\n * `cacheConversation` have nothing to map to; `cacheKey` becomes\n * `prompt_cache_key`, which routes requests sharing a prefix together.\n * - Tools are sent with `strict: true`; arguments come back as JSON text and\n * are parsed here.\n * - `effort` becomes `reasoning_effort`; `temperature` is passed when given.\n * - Usage: `prompt_tokens` includes the cached tokens, so `inputTokens` is\n * the prompt minus the cache reads and writes.\n * - Credentials: API keys only. OpenAI's API authenticates with keys, and a\n * ChatGPT or Codex sign-in is not a credential a third-party product may\n * use (see the README's terms note).\n */\nimport type OpenAI from \"openai\";\n\nimport type { ChatCall, ProviderAdapter } from \"../adapter\";\nimport type { ResolvedCredential } from \"../credentials\";\nimport { InvalidResponseError, mapProviderError } from \"../errors\";\nimport type { ChatResult, Message, StopReason, ToolCall, Usage } from \"../types\";\nimport { loadSdk } from \"./load\";\nimport { sealedFetch, type SealRoute } from \"./sealed-fetch\";\nimport { count, refusalOf } from \"./util\";\n\ntype ChatParams = OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming;\ntype ChatMessageParam = OpenAI.Chat.Completions.ChatCompletionMessageParam;\ntype Completion = OpenAI.Chat.Completions.ChatCompletion;\ntype CompletionMessage = OpenAI.Chat.Completions.ChatCompletionMessage;\ntype FunctionToolCall = OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;\n\nexport const OPENAI_PROVIDER = \"openai\";\n\n/** Where OpenAI's API lives; never read from the environment (B3). */\nexport const OPENAI_BASE_URL = \"https://api.openai.com/v1\";\n\n/** The one endpoint the adapter calls (relative to the base URL), for OpenAI and xAI alike. */\nexport const OPENAI_ROUTES: readonly SealRoute[] = [{ method: \"POST\", path: \"/chat/completions\" }];\n\n/**\n * The slice of the SDK client this adapter calls. `params` is the SDK's\n * `ChatCompletionCreateParamsNonStreaming`, typed `never` here so this\n * package's public types do not require the optional SDK to be installed.\n */\nexport interface OpenAIClientLike {\n chat: {\n completions: {\n create(params: never, options?: { signal?: AbortSignal }): Promise<unknown>;\n };\n };\n}\n\nexport interface OpenAIAdapterOptions {\n /** Build the SDK client for one call (tests inject a recording fake). */\n client?: (credential: ResolvedCredential) => OpenAIClientLike | Promise<OpenAIClientLike>;\n baseURL?: string;\n /** The `fetch` the SDK sends with (a proxy, a test double). */\n fetch?: typeof globalThis.fetch;\n defaultModel?: string;\n}\n\n/** An OpenAI-compatible API: OpenAI itself, or a provider that speaks its Chat Completions (xAI). */\ninterface OpenAICompatibleOptions extends OpenAIAdapterOptions {\n id: string;\n /** The provider's own API root, used when the host passes no `baseURL`. */\n defaultBaseURL: string;\n /** Whether the provider takes `prompt_cache_key`. */\n promptCacheKey: boolean;\n}\n\n/**\n * Every account option is passed explicitly: with `organization`, `project`\n * or `baseURL` left unset the SDK reads `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`\n * and `OPENAI_BASE_URL`, so a store's own key would be billed to, or routed\n * through, the platform's account (B3). The sealed fetch is the second layer.\n */\nasync function defaultClient(credential: ResolvedCredential, options: OpenAICompatibleOptions): Promise<OpenAIClientLike> {\n const sdk = await loadSdk(options.id, \"openai\", () => import(\"openai\"));\n const baseURL = options.baseURL ?? options.defaultBaseURL;\n return new sdk.default({\n apiKey: credential.secret,\n organization: null,\n project: null,\n adminAPIKey: null,\n baseURL,\n fetch: sealedFetch({ provider: options.id, baseURL, routes: OPENAI_ROUTES, auth: { authorization: `Bearer ${credential.secret}` }, fetch: options.fetch }),\n maxRetries: 0,\n });\n}\n\nconst ERROR_PREFIX = \"[tool error] \";\n\nfunction toMessages(messages: readonly Message[]): ChatMessageParam[] {\n return messages.flatMap((message): ChatMessageParam[] => {\n if (message.role === \"user\") return [{ role: \"user\", content: message.text }];\n if (message.role === \"assistant\") {\n const toolCalls = message.toolCalls.map((call) => ({\n id: call.id,\n type: \"function\" as const,\n function: { name: call.name, arguments: JSON.stringify(call.input ?? {}) },\n }));\n return [{ role: \"assistant\", content: message.text || null, ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}) }];\n }\n return message.results.map((result) => ({\n role: \"tool\" as const,\n tool_call_id: result.callId,\n content: result.isError ? `${ERROR_PREFIX}${result.output}` : result.output,\n }));\n });\n}\n\nexport function toOpenAIParams(call: ChatCall, promptCacheKey = true): ChatParams {\n const { request, model } = call;\n const messages: ChatMessageParam[] = [];\n if (request.system && request.system.length > 0) {\n messages.push({ role: \"system\", content: request.system.map((block) => ({ type: \"text\" as const, text: block.text })) });\n }\n messages.push(...toMessages(request.messages));\n const params: ChatParams = { model, messages, max_completion_tokens: request.maxOutputTokens };\n if (request.tools && request.tools.length > 0) {\n params.tools = request.tools.map((tool) => ({\n type: \"function\" as const,\n function: { name: tool.name, description: tool.description, parameters: tool.inputSchema, strict: true },\n }));\n }\n return withHints(params, request, promptCacheKey);\n}\n\n/** The request's optional hints, each only when set. */\nfunction withHints(params: ChatParams, request: ChatCall[\"request\"], promptCacheKey: boolean): ChatParams {\n if (request.toolChoice) params.tool_choice = request.toolChoice;\n if (request.effort) params.reasoning_effort = request.effort;\n if (request.temperature !== undefined) params.temperature = request.temperature;\n if (request.cacheKey && promptCacheKey) params.prompt_cache_key = request.cacheKey;\n return params;\n}\n\nconst STOP_REASONS: Record<string, StopReason> = {\n stop: \"end\",\n tool_calls: \"tool_use\",\n function_call: \"tool_use\",\n length: \"max_tokens\",\n content_filter: \"refusal\",\n};\n\nfunction toUsage(usage: Completion[\"usage\"]): Usage {\n const details = usage?.prompt_tokens_details;\n const cacheRead = count(details?.cached_tokens);\n const cacheWrite = count(details?.cache_write_tokens);\n return {\n inputTokens: Math.max(0, count(usage?.prompt_tokens) - cacheRead - cacheWrite),\n cacheCreationTokens: cacheWrite,\n cacheReadTokens: cacheRead,\n outputTokens: count(usage?.completion_tokens),\n raw: usage ?? null,\n };\n}\n\nfunction parseArguments(provider: string, call: FunctionToolCall): unknown {\n try {\n return JSON.parse(call.function.arguments || \"{}\");\n } catch {\n throw new InvalidResponseError(provider, `Tool call ${call.id} (${call.function.name}) carries arguments that are not JSON.`);\n }\n}\n\nfunction toolCallsOf(provider: string, message: CompletionMessage): ToolCall[] {\n return (message.tool_calls ?? [])\n .filter((call): call is FunctionToolCall => call.type === \"function\")\n .map((call) => ({ id: call.id, name: call.function.name, input: parseArguments(provider, call) }));\n}\n\n/** A refusal is the message's own `refusal` text, or a content-filter stop. */\nfunction refusalText(message: CompletionMessage): string | null {\n return typeof message.refusal === \"string\" && message.refusal.length > 0 ? message.refusal : null;\n}\n\nfunction fromOpenAICompletion(provider: string, response: Completion, model: string): ChatResult {\n const choice = response?.choices?.[0];\n if (!choice) throw new InvalidResponseError(provider, \"The response carries no choice.\");\n const { message } = choice;\n const toolCalls = toolCallsOf(provider, message);\n const refused = refusalText(message);\n const stopReason: StopReason = refused ? \"refusal\" : (STOP_REASONS[choice.finish_reason] ?? \"other\");\n const text = message.content ?? \"\";\n return {\n provider,\n model: response.model || model,\n text,\n toolCalls,\n stopReason,\n providerStopReason: choice.finish_reason ?? null,\n refusal: refused ? refusalOf(stopReason, null, refused) : refusalOf(stopReason, choice.finish_reason, null),\n usage: toUsage(response.usage),\n message: { role: \"assistant\", text, toolCalls, raw: { provider, content: message } },\n };\n}\n\n/** An adapter for any API that speaks OpenAI's Chat Completions. */\nexport function openAICompatibleAdapter(options: OpenAICompatibleOptions): ProviderAdapter {\n const build = options.client ?? ((credential: ResolvedCredential) => defaultClient(credential, options));\n const provider = options.id;\n return {\n id: provider,\n defaultModel: options.defaultModel,\n capabilities: [\"chat\"],\n credentialKinds: [\"apiKey\"],\n async chat(call) {\n const params = toOpenAIParams(call, options.promptCacheKey);\n const client = await build(call.credential);\n let response: unknown;\n try {\n response = await client.chat.completions.create(params as never, call.request.signal ? { signal: call.request.signal } : undefined);\n } catch (error) {\n throw mapProviderError(provider, error, [call.credential.secret]);\n }\n return fromOpenAICompletion(provider, response as Completion, call.model);\n },\n };\n}\n\nexport function openaiAdapter(options: OpenAIAdapterOptions = {}): ProviderAdapter {\n return openAICompatibleAdapter({ ...options, id: OPENAI_PROVIDER, defaultBaseURL: OPENAI_BASE_URL, promptCacheKey: true });\n}\n","/**\n * The xAI (Grok) adapter (FUT-3738). xAI's API speaks OpenAI's Chat\n * Completions, so this is the OpenAI-compatible adapter under its own id,\n * with xAI's own API root and the store's own xAI key. It reads NOTHING from\n * the platform's `OPENAI_*` variables: the base URL, organisation and project\n * are passed explicitly and the sealed fetch sends only this key (B3).\n *\n * - No default model: a host names the Grok model it pays for.\n * - `cacheKey` is not sent: `prompt_cache_key` is OpenAI's parameter.\n * - Credentials: API keys only, as for OpenAI.\n * - The `openai` SDK is the optional peer this adapter needs.\n */\nimport type { ProviderAdapter } from \"../adapter\";\nimport { openAICompatibleAdapter, type OpenAIAdapterOptions } from \"./openai\";\n\nexport const XAI_PROVIDER = \"xai\";\n\n/** Where xAI's API lives; never read from the environment. */\nexport const XAI_BASE_URL = \"https://api.x.ai/v1\";\n\nexport type XaiAdapterOptions = OpenAIAdapterOptions;\n\nexport function xaiAdapter(options: XaiAdapterOptions = {}): ProviderAdapter {\n return openAICompatibleAdapter({ ...options, id: XAI_PROVIDER, defaultBaseURL: XAI_BASE_URL, promptCacheKey: false });\n}\n","import type { ProviderAdapter } from \"../adapter\";\nimport { anthropicAdapter } from \"./anthropic\";\nimport { geminiAdapter } from \"./gemini\";\nimport { openaiAdapter } from \"./openai\";\nimport { xaiAdapter } from \"./xai\";\n\n/** Fresh instances of the built-in adapters, with their defaults. */\nexport function builtInAdapters(): ProviderAdapter[] {\n return [anthropicAdapter(), openaiAdapter(), geminiAdapter(), xaiAdapter()];\n}\n\nexport * from \"./anthropic\";\nexport * from \"./gemini\";\nexport * from \"./openai\";\nexport * from \"./xai\";\n","/**\n * Credential strategies, interchangeable behind one interface.\n *\n * - `apiKey`: a static secret the HOST supplies, read at call time through a\n * resolver (or given directly). The package never persists it, logs it or\n * puts it in an error message.\n * - `oauth`: an access token the host provides, with its expiry, plus a\n * refresh hook. Before a call the package refreshes a token that is within\n * `refreshSkewMs` of expiring; after a 401 it refreshes once and retries\n * once. A refresh is SINGLE-FLIGHT per session (B1): concurrent calls that\n * find the token expiring, or get a 401, share one `refresh()` — providers\n * rotate the refresh token on use, and two refreshes racing can revoke the\n * login. A 401 on a token older than the last refresh adopts that refresh\n * instead of starting another. It never runs a login flow: obtaining the first token, storing the\n * refreshed one and choosing which provider's login is allowed at all are\n * the host's (see the README's terms note).\n *\n * Which strategies a provider accepts is the ADAPTER's declaration\n * (`ProviderAdapter.credentialKinds`), checked when the client is created.\n */\n\nimport { CredentialRevokedError } from \"./errors\";\n\nexport type CredentialKind = \"apiKey\" | \"oauth\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport interface ApiKeyCredentials {\n kind: \"apiKey\";\n /** The key, or a resolver the package calls before every request. */\n apiKey: string | (() => MaybePromise<string>);\n}\n\nexport interface OAuthToken {\n accessToken: string;\n /** Epoch milliseconds; omitted when the token does not say. */\n expiresAt?: number;\n}\n\nexport type RefreshReason = \"expiring\" | \"unauthorized\";\n\nexport interface OAuthCredentials {\n kind: \"oauth\";\n /** The host's current token. Called before every request. */\n token: () => MaybePromise<OAuthToken>;\n /**\n * Obtain a fresh token. The host stores it so `token()` returns it next\n * time; the package only uses it for the call in flight.\n */\n refresh: (reason: RefreshReason) => MaybePromise<OAuthToken>;\n /** How close to expiry a token is refreshed first. Default 60 s. */\n refreshSkewMs?: number;\n /**\n * The host's \"this account was disconnected\" check, called before a token is\n * handed out and again after a refresh lands. Once it returns true,\n * `current()` and `afterUnauthorized()` throw `CredentialRevokedError`, and a\n * refresh that was in flight is discarded: never returned, never cached.\n */\n isRevoked?: () => MaybePromise<boolean>;\n}\n\nexport type Credentials = ApiKeyCredentials | OAuthCredentials;\n\nconst INSPECT = Symbol.for(\"nodejs.util.inspect.custom\");\n\n/**\n * The secret an adapter sends on ONE request. Its value is non-enumerable and\n * it prints as `[credential apiKey]`, so a log line, a JSON dump or an error\n * context that captures it carries no secret.\n */\nexport class ResolvedCredential {\n readonly kind: CredentialKind;\n declare readonly secret: string;\n\n constructor(kind: CredentialKind, secret: string) {\n this.kind = kind;\n Object.defineProperty(this, \"secret\", { value: secret, enumerable: false });\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n toString(): string {\n return `[credential ${this.kind}]`;\n }\n\n [INSPECT](): string {\n return this.toString();\n }\n}\n\nexport interface CredentialSessionOptions {\n now?: () => number;\n}\n\n/**\n * Wraps one strategy for the client: `current()` before a request,\n * `afterUnauthorized()` once after a 401 (null when nothing can be renewed).\n */\nexport interface CredentialSession {\n readonly kind: CredentialKind;\n current(): Promise<ResolvedCredential>;\n /** `used` is the credential the 401 answered, so a refresh made since is adopted. */\n afterUnauthorized(used: ResolvedCredential): Promise<ResolvedCredential | null>;\n}\n\n/** Which refresh each OAuth credential came from (0: the host's token as read). */\nconst generations = new WeakMap<ResolvedCredential, number>();\n\nfunction nonEmpty(value: unknown, what: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`@12-apps/llm: the host's ${what} returned no value.`);\n }\n return value;\n}\n\nexport function createCredentialSession(\n credentials: Credentials,\n options: CredentialSessionOptions = {},\n): CredentialSession {\n const now = options.now ?? Date.now;\n if (credentials.kind === \"apiKey\") {\n const read = async () =>\n nonEmpty(\n typeof credentials.apiKey === \"function\" ? await credentials.apiKey() : credentials.apiKey,\n \"API key\",\n );\n return {\n kind: \"apiKey\",\n current: async () => new ResolvedCredential(\"apiKey\", await read()),\n afterUnauthorized: async () => null,\n };\n }\n const skew = credentials.refreshSkewMs ?? 60_000;\n const oauth = credentials;\n let generation = 0;\n let latest: ResolvedCredential | null = null;\n let inFlight: Promise<ResolvedCredential> | null = null;\n let revoked = false;\n const assertLive = async (): Promise<void> => {\n if (revoked || (await oauth.isRevoked?.())) {\n revoked = true;\n latest = null;\n throw new CredentialRevokedError();\n }\n };\n const stamped = (secret: string, of: number): ResolvedCredential => {\n const credential = new ResolvedCredential(\"oauth\", secret);\n generations.set(credential, of);\n return credential;\n };\n // One refresh at a time: every caller that needs one while it runs awaits the same promise.\n const refresh = (reason: RefreshReason): Promise<ResolvedCredential> => {\n inFlight ??= (async () => {\n await assertLive();\n const secret = nonEmpty((await oauth.refresh(reason)).accessToken, \"OAuth refresh\");\n await assertLive(); // disconnected while the refresh ran: its result is discarded\n generation += 1;\n latest = stamped(secret, generation);\n return latest;\n })().finally(() => {\n inFlight = null;\n });\n return inFlight;\n };\n return {\n kind: \"oauth\",\n async current() {\n await assertLive();\n if (inFlight) return inFlight;\n const of = generation; // before the await: a refresh that lands meanwhile makes this token older\n const token = await oauth.token();\n const expiring = token.expiresAt !== undefined && token.expiresAt - now() <= skew;\n if (expiring) return refresh(\"expiring\");\n return stamped(nonEmpty(token.accessToken, \"OAuth token provider\"), of);\n },\n async afterUnauthorized(used) {\n await assertLive();\n if (inFlight) return inFlight;\n // A refresh finished after this call's token was read: that token is the answer, not another rotation.\n if (latest && (generations.get(used) ?? 0) < generation) return latest;\n return refresh(\"unauthorized\");\n },\n };\n}\n","/**\n * The strict-schema rule every tool input schema meets, whatever the provider.\n *\n * Each provider's strict mode guarantees the model's arguments validate\n * against the schema, and each asks for a slightly different subset. The\n * common ground, which this check enforces, is: the root is an object; every\n * object sets `additionalProperties: false`; every object lists ALL its\n * properties in `required`. An optional field is spelled as a nullable type\n * (`type: [\"string\", \"null\"]`), which every provider accepts.\n */\nimport type { JsonSchema, ToolDefinition } from \"./types\";\n\nconst NESTED_SINGLE = [\"items\", \"not\", \"additionalItems\"] as const;\nconst NESTED_LIST = [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\"] as const;\nconst NESTED_MAP = [\"properties\", \"$defs\", \"definitions\"] as const;\n\nfunction isObjectSchema(schema: JsonSchema): boolean {\n const type = schema.type;\n return type === \"object\" || (Array.isArray(type) && type.includes(\"object\")) || \"properties\" in schema;\n}\n\nfunction asSchema(value: unknown): JsonSchema | null {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as JsonSchema) : null;\n}\n\nfunction objectProblems(schema: JsonSchema, path: string): string[] {\n const problems: string[] = [];\n if (schema.additionalProperties !== false) {\n problems.push(`${path}: an object must set additionalProperties: false`);\n }\n const properties = asSchema(schema.properties) ?? {};\n const required = Array.isArray(schema.required) ? schema.required : [];\n for (const key of Object.keys(properties)) {\n if (!required.includes(key)) {\n problems.push(`${path}: property \"${key}\" must be listed in required (use a nullable type for an optional field)`);\n }\n }\n return problems;\n}\n\nfunction nestedSchemas(schema: JsonSchema, path: string): Array<[JsonSchema, string]> {\n const single = NESTED_SINGLE.map((key): [unknown, string] => [schema[key], `${path}.${key}`]);\n const listed = NESTED_LIST.flatMap((key) => {\n const list = schema[key];\n return Array.isArray(list) ? list.map((item, index): [unknown, string] => [item, `${path}.${key}[${index}]`]) : [];\n });\n const mapped = NESTED_MAP.flatMap((key) =>\n Object.entries(asSchema(schema[key]) ?? {}).map(([name, value]): [unknown, string] => [value, `${path}.${key}.${name}`]),\n );\n return [...single, ...listed, ...mapped].flatMap(([value, at]): Array<[JsonSchema, string]> => {\n const child = asSchema(value);\n return child ? [[child, at]] : [];\n });\n}\n\n/** Every reason `schema` is not strict, with a path to each; empty when it is. */\nexport function strictSchemaProblems(schema: JsonSchema, path = \"$\"): string[] {\n const own = isObjectSchema(schema) ? objectProblems(schema, path) : [];\n return own.concat(...nestedSchemas(schema, path).map(([child, at]) => strictSchemaProblems(child, at)));\n}\n\n/** Every problem in a tool list: duplicate names and non-strict schemas. */\nexport function toolSchemaProblems(tools: readonly ToolDefinition[]): string[] {\n const seen = new Set<string>();\n const problems: string[] = [];\n for (const tool of tools) {\n if (seen.has(tool.name)) problems.push(`tool \"${tool.name}\" is defined twice`);\n seen.add(tool.name);\n if (tool.inputSchema.type !== \"object\") problems.push(`tool \"${tool.name}\": the input schema root must be type \"object\"`);\n problems.push(...strictSchemaProblems(tool.inputSchema).map((p) => `tool \"${tool.name}\" ${p}`));\n }\n return problems;\n}\n\n/** Throws a TypeError naming every problem in every tool's input schema. */\nexport function assertStrictTools(tools: readonly ToolDefinition[]): void {\n const problems = toolSchemaProblems(tools);\n if (problems.length > 0) {\n throw new TypeError(`@12-apps/llm: tool schemas are not strict:\\n- ${problems.join(\"\\n- \")}`);\n }\n}\n","/**\n * The abstract factory: `createModelClient` picks an adapter by provider id\n * and wraps it with what every provider shares: the credential strategy\n * (including the OAuth refresh on near-expiry and the single retry after a\n * 401), the strict tool-schema check, and the host's retry policy.\n */\nimport type { AdapterRegistry, ProviderAdapter } from \"./adapter\";\nimport { createAdapterRegistry } from \"./adapter\";\nimport { builtInAdapters } from \"./adapters\";\nimport type { CredentialSession, Credentials, ResolvedCredential } from \"./credentials\";\nimport { createCredentialSession } from \"./credentials\";\nimport { AuthError, InvalidRequestError, LlmError, UnsupportedError } from \"./errors\";\nimport { toolSchemaProblems } from \"./schema\";\nimport type { Capability, ChatRequest, ChatResult } from \"./types\";\n\n/**\n * The host's ONE retry policy. Called after each failed attempt with the\n * typed error and the attempt number (1 for the first failure). Return a\n * delay in milliseconds to try again, or `null` to give up and throw.\n * The package itself never retries (the SDKs' own retries are switched off),\n * so this hook is the whole policy. A 401 under OAuth is not seen here: the\n * client refreshes and retries it once by itself.\n */\nexport type RetryPolicy = (error: LlmError, attempt: number) => number | null;\n\nexport interface ModelClientOptions {\n provider: string;\n /** Defaults to the adapter's default model. */\n model?: string;\n credentials: Credentials;\n retry?: RetryPolicy;\n /** Where to find adapters. Defaults to a registry of the built-in four. */\n registry?: AdapterRegistry;\n /** Test seams. */\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n}\n\nexport interface ModelClient {\n readonly provider: string;\n readonly model: string;\n readonly capabilities: readonly Capability[];\n supports(capability: Capability): boolean;\n chat(request: ChatRequest): Promise<ChatResult>;\n}\n\n/** Retries rate limits and outages, honouring retry-after; gives up after `maxAttempts`. */\nexport function retryTransient(options: { maxAttempts?: number; baseDelayMs?: number } = {}): RetryPolicy {\n const maxAttempts = options.maxAttempts ?? 3;\n const base = options.baseDelayMs ?? 1000;\n return (error, attempt) => {\n if (attempt >= maxAttempts) return null;\n if (error.kind === \"rate_limit\") {\n const hinted = (error as { retryAfterMs?: number }).retryAfterMs;\n return hinted ?? base * 2 ** (attempt - 1);\n }\n return error.kind === \"unavailable\" ? base * 2 ** (attempt - 1) : null;\n };\n}\n\nconst neverRetry: RetryPolicy = () => null;\n\nconst defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nfunction checkRequest(adapter: ProviderAdapter, request: ChatRequest): void {\n const problems = toolSchemaProblems(request.tools ?? []);\n if (!Number.isInteger(request.maxOutputTokens) || request.maxOutputTokens <= 0) {\n problems.push(\"maxOutputTokens must be a positive integer\");\n }\n if (problems.length > 0) {\n throw new InvalidRequestError(adapter.id, `Invalid chat request:\\n- ${problems.join(\"\\n- \")}`);\n }\n}\n\nasync function callWithAuth(\n adapter: ProviderAdapter,\n session: CredentialSession,\n model: string,\n request: ChatRequest,\n): Promise<ChatResult> {\n const credential: ResolvedCredential = await session.current();\n try {\n return await adapter.chat({ model, request, credential });\n } catch (error) {\n if (!(error instanceof AuthError) || error.status !== 401) throw error;\n const renewed = await session.afterUnauthorized(credential);\n if (!renewed) throw error;\n return adapter.chat({ model, request, credential: renewed });\n }\n}\n\nexport function createModelClient(options: ModelClientOptions): ModelClient {\n const registry = options.registry ?? createAdapterRegistry(builtInAdapters());\n const adapter = registry.get(options.provider);\n if (!adapter.credentialKinds.includes(options.credentials.kind)) {\n throw new UnsupportedError(\n adapter.id,\n `The \"${adapter.id}\" adapter does not accept \"${options.credentials.kind}\" credentials (it accepts: ${adapter.credentialKinds.join(\", \")}).`,\n );\n }\n const session = createCredentialSession(options.credentials, { now: options.now });\n const model = options.model ?? adapter.defaultModel;\n if (!model) {\n throw new InvalidRequestError(adapter.id, `The \"${adapter.id}\" adapter has no default model; pass \\`model\\`.`);\n }\n const retry = options.retry ?? neverRetry;\n const sleep = options.sleep ?? defaultSleep;\n\n return {\n provider: adapter.id,\n model,\n capabilities: adapter.capabilities,\n supports: (capability) => adapter.capabilities.includes(capability),\n async chat(request) {\n checkRequest(adapter, request);\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await callWithAuth(adapter, session, request.model ?? model, request);\n } catch (error) {\n if (!(error instanceof LlmError)) throw error;\n const delay = retry(error, attempt);\n if (delay === null || request.signal?.aborted) throw error;\n await sleep(delay);\n }\n }\n },\n };\n}\n","/**\n * The tool-use loop: run turns until the model stops calling tools, refuses,\n * runs out of output budget, or the turn limit is reached.\n *\n * The host supplies an executor per tool name and a usage callback; every\n * turn's normalized usage is reported through it, before anything else\n * happens with that turn, so a host meters cost even for a turn that ends the\n * loop. A refusal is a typed RESULT (`status: \"refused\"`), never an error, so\n * the host can hand the conversation to a person.\n *\n * The returned `messages` are always a valid request for the NEXT turn (B2):\n * a turn the loop ends on keeps its text but never a tool call that was not\n * run (no tool_use without its tool_result), and a turn with neither text nor\n * a tool call — an empty refusal — is not appended at all. Either would make\n * the provider reject the host's next request with a 400.\n */\nimport type { ModelClient } from \"./client\";\nimport { RefusalError } from \"./errors\";\nimport type { AssistantMessage, ChatRequest, ChatResult, Message, Refusal, ToolCall, ToolResult, Usage } from \"./types\";\n\n/** What an executor returns: the output text, or the text marked as an error. */\nexport type ToolOutput = string | { output: string; isError?: boolean };\n\nexport type ToolExecutor = (input: unknown, context: { call: ToolCall; turn: number }) => Promise<ToolOutput> | ToolOutput;\n\nexport interface ToolLoopOptions {\n client: ModelClient;\n /** The first turn's request. `messages` is the conversation so far. */\n request: ChatRequest;\n executors: Readonly<Record<string, ToolExecutor>>;\n /** Turns at most, each turn being one model call. Default 8. */\n maxTurns?: number;\n /** Called once per turn with that turn's usage, turn numbers from 1. */\n onUsage?: (usage: Usage, turn: number, result: ChatResult) => void | Promise<void>;\n}\n\nexport type ToolLoopStatus = \"completed\" | \"refused\" | \"max_turns\" | \"max_tokens\" | \"stopped\";\n\nexport interface ToolLoopResult {\n status: ToolLoopStatus;\n /** The conversation, with every turn and tool result appended. */\n messages: Message[];\n /** The last model turn. */\n final: ChatResult;\n turns: number;\n /** The sum of every turn's usage (without the raw objects). */\n usage: Omit<Usage, \"raw\">;\n /** Set when `status` is \"refused\". */\n refusal: Refusal | null;\n}\n\nconst UNKNOWN_TOOL = \"This tool does not exist.\";\n\nfunction addUsage(total: Omit<Usage, \"raw\">, usage: Usage): Omit<Usage, \"raw\"> {\n return {\n inputTokens: total.inputTokens + usage.inputTokens,\n cacheCreationTokens: total.cacheCreationTokens + usage.cacheCreationTokens,\n cacheReadTokens: total.cacheReadTokens + usage.cacheReadTokens,\n outputTokens: total.outputTokens + usage.outputTokens,\n };\n}\n\nasync function runCall(call: ToolCall, turn: number, executors: ToolLoopOptions[\"executors\"]): Promise<ToolResult> {\n const executor = Object.hasOwn(executors, call.name) ? executors[call.name] : undefined;\n if (!executor) return { callId: call.id, name: call.name, output: UNKNOWN_TOOL, isError: true };\n try {\n const out = await executor(call.input, { call, turn });\n return typeof out === \"string\"\n ? { callId: call.id, name: call.name, output: out }\n : { callId: call.id, name: call.name, output: out.output, ...(out.isError ? { isError: true } : {}) };\n } catch (error) {\n // The model gets the failure as an error result and may recover from it.\n const message = error instanceof Error ? error.message : String(error);\n return { callId: call.id, name: call.name, output: message, isError: true };\n }\n}\n\n/**\n * The turn the loop ENDS on, as it goes into the transcript: its words only.\n * Tool calls nobody will answer are dropped, and with them `raw`, which\n * carries the same calls in the provider's own blocks; a turn with no words\n * is left out.\n */\nfunction settled(message: AssistantMessage): AssistantMessage | null {\n if (message.toolCalls.length === 0) return message.text.length > 0 ? message : null;\n return message.text.length > 0 ? { role: \"assistant\", text: message.text, toolCalls: [] } : null;\n}\n\n/** The loop's result, with the turn it ends on settled into the transcript. */\nfunction ended(status: ToolLoopStatus, messages: Message[], final: ChatResult, turns: number, usage: Omit<Usage, \"raw\">): ToolLoopResult {\n const last = settled(final.message);\n if (last) messages.push(last);\n return { status, messages, final, turns, usage, refusal: status === \"refused\" ? final.refusal : null };\n}\n\nfunction statusOf(result: ChatResult): ToolLoopStatus | null {\n if (result.stopReason === \"refusal\") return \"refused\";\n if (result.stopReason === \"max_tokens\") return \"max_tokens\";\n if (result.toolCalls.length === 0) return result.stopReason === \"end\" ? \"completed\" : \"stopped\";\n return null;\n}\n\nexport async function runToolLoop(options: ToolLoopOptions): Promise<ToolLoopResult> {\n const maxTurns = options.maxTurns ?? 8;\n if (!Number.isInteger(maxTurns) || maxTurns < 1) throw new TypeError(\"@12-apps/llm: maxTurns must be a positive integer.\");\n const messages: Message[] = [...options.request.messages];\n let usage: Omit<Usage, \"raw\"> = { inputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0, outputTokens: 0 };\n\n for (let turn = 1; ; turn += 1) {\n const final = await options.client.chat({ ...options.request, messages: [...messages] });\n usage = addUsage(usage, final.usage);\n await options.onUsage?.(final.usage, turn, final);\n const status = statusOf(final) ?? (turn >= maxTurns ? \"max_turns\" : null);\n if (status) return ended(status, messages, final, turn, usage);\n messages.push(final.message);\n\n const results = await Promise.all(final.toolCalls.map((call) => runCall(call, turn, options.executors)));\n messages.push({ role: \"tool\", results });\n }\n}\n\n/** Throw a `RefusalError` when a turn was refused; return it otherwise. */\nexport function ensureNotRefused(result: ChatResult): ChatResult {\n if (result.stopReason === \"refusal\") {\n throw new RefusalError(result.provider, result.refusal ?? { category: null, explanation: null });\n }\n return result;\n}\n"],"mappings":";;;;AAkBO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAlBpC,OAkBoC;AAAA;AAAA;AAAA,EACzB;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,MAAoB,UAAkB,SAAiB,QAAiB;AAClF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,SAAS;AAAA,EAChB;AACF;AAGO,IAAM,YAAN,cAAwB,SAAS;AAAA,EAlCxC,OAkCwC;AAAA;AAAA;AAAA,EACtC,YAAY,UAAkB,SAAiB,QAAiB;AAC9D,UAAM,QAAQ,UAAU,SAAS,MAAM;AACvC,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,yBAAN,cAAqC,UAAU;AAAA,EA1CtD,OA0CsD;AAAA;AAAA;AAAA,EACpD,YAAY,WAAW,cAAc;AACnC,UAAM,UAAU,yCAAyC;AACzD,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,iBAAN,cAA6B,SAAS;AAAA,EAlD7C,OAkD6C;AAAA;AAAA;AAAA,EAClC;AAAA,EAET,YAAY,UAAkB,SAAiB,cAAuB;AACpE,UAAM,cAAc,UAAU,SAAS,GAAG;AAC1C,SAAK,O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QAAQ,SAAS,UAAU,CAAC,GAAG,QAAQ,EAAE,CAAC;AACvF,YAAQ,SAAS,OAAO,MAAM,KAAK;AACnC,UAAM,QAAQ,UAAU,MAAM,OAAO,MAAM,KAAK;AAChD,UAAM,SAAS,SAAS,KAAK,MAAM,QAAQ,WAAW,cAAc;AACpE,QAAI,OAAQ,QAAO,MAAM,QAAQ,UAAU,OAAO,MAAM,KAAK;AAC7D,aAAS,KAAK,MAAM,OAAO;AAE3B,UAAM,UAAU,MAAM,QAAQ,IAAI,MAAM,UAAU,IAAI,CAAC,SAAS,QAAQ,MAAM,MAAM,QAAQ,SAAS,CAAC,CAAC;AACvG,aAAS,KAAK,EAAE,MAAM,QAAQ,QAAQ,CAAC;AAAA,EACzC;AACF;AAjBsB;AAoBf,SAAS,iBAAiB,QAAgC;AAC/D,MAAI,OAAO,eAAe,WAAW;AACnC,UAAM,IAAI,aAAa,OAAO,UAAU,OAAO,WAAW,EAAE,UAAU,MAAM,aAAa,KAAK,CAAC;AAAA,EACjG;AACA,SAAO;AACT;AALgB;","names":["value","defaultClient","assistantContent","stopReasonOf","toUsage","textOf","toolCallsOf","defaultClient","toMessages","STOP_REASONS","toUsage","toolCallsOf"]}
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@12-apps/llm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "sideEffects": false,
6
+ "description": "A provider-agnostic model connector. One interface for a chat turn with tools (system blocks with cache breakpoints, strict JSON-schema tools, tool choice, output budget, effort hint) and one normalized result (text, tool calls, stop reason, usage with cache tokens). An abstract factory picks an adapter by provider id from a registry the host can extend; Anthropic, OpenAI, Gemini and xAI adapters ship over each provider's official SDK, loaded only when used. Credentials are a strategy: an API key or an OAuth access token with a host-supplied refresh. A tool-use loop reports every turn's usage. Typed errors and one host retry hook.",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "scripts": {
15
+ "build": "rm -rf dist && tsup",
16
+ "clean": "rm -rf node_modules coverage dist",
17
+ "test": "node ../../scripts/vitest-with-teardown.mjs run",
18
+ "test:watch": "vitest watch",
19
+ "lint": "eslint src --max-warnings 0",
20
+ "check-types": "tsc --noEmit",
21
+ "typecheck": "tsc --noEmit"
22
+ },
23
+ "peerDependencies": {
24
+ "@anthropic-ai/sdk": ">=1.6.0",
25
+ "@google/genai": ">=3.1.0",
26
+ "openai": ">=7.55.0"
27
+ },
28
+ "peerDependenciesMeta": {
29
+ "@anthropic-ai/sdk": {
30
+ "optional": true
31
+ },
32
+ "@google/genai": {
33
+ "optional": true
34
+ },
35
+ "openai": {
36
+ "optional": true
37
+ }
38
+ },
39
+ "devDependencies": {
40
+ "@12-apps/eslint-config": "^1.22.0",
41
+ "@12-apps/typescript-config": "^1.21.0",
42
+ "@anthropic-ai/sdk": "^1.6.0",
43
+ "@google/genai": "^3.1.0",
44
+ "@types/node": "^22.10.6",
45
+ "eslint": "^9.39.1",
46
+ "eslint-plugin-test-flakiness": "^1.4.0",
47
+ "openai": "^7.55.0",
48
+ "tsup": "^8.0.0",
49
+ "typescript": "^5.9.2",
50
+ "vitest": "^3.2.4"
51
+ },
52
+ "engines": {
53
+ "node": ">=22.0.0"
54
+ },
55
+ "license": "MIT",
56
+ "publishConfig": {
57
+ "registry": "https://registry.npmjs.org",
58
+ "access": "public"
59
+ },
60
+ "repository": {
61
+ "type": "git",
62
+ "url": "git+https://github.com/12-apps/shared-packages.git",
63
+ "directory": "packages/llm"
64
+ },
65
+ "files": [
66
+ "dist",
67
+ "*.md",
68
+ "!eslint.config.js",
69
+ "!tsup.config.ts",
70
+ "!**/__tests__/**",
71
+ "!**/*.test.*"
72
+ ]
73
+ }