import { classifyAnthropicLimit } from './smartai.limits.anthropic.js'; import { registerAnthropicCacheTransparentTransport } from './smartai.cache.anthropic.js'; import { ANTHROPIC_API_BASE_URL, ANTHROPIC_API_VERSION, ANTHROPIC_OAUTH_BETA, isAnthropicApiRequestUrl, readAnthropicModelList, type IAnthropicModelConnection, type IAnthropicOAuthModel, type IAnthropicOAuthModelListOptions, type TAnthropicOAuthRequestOutcome, } from './smartai.oauth.anthropic.js'; export class AnthropicApiKeyAuthError extends Error { public status?: number; public requestOutcome?: TAnthropicOAuthRequestOutcome; constructor(message: string, options: { status?: number; requestOutcome?: TAnthropicOAuthRequestOutcome } = {}) { super(message); this.name = 'AnthropicApiKeyAuthError'; this.status = options.status; this.requestOutcome = options.requestOutcome; } } /** An Anthropic API key, as the Claude Console issues it. */ export interface IAnthropicApiKeyAccess { readonly apiKey: string; } export interface IAnthropicApiKeyConnectionOptions extends IAnthropicApiKeyAccess { /** Optional underlying transport. Defaults to the current global fetch. */ readonly fetch?: typeof fetch; } const requireAccess = (accessArg: IAnthropicApiKeyAccess | undefined): IAnthropicApiKeyAccess => { if (!accessArg || typeof accessArg.apiKey !== 'string' || accessArg.apiKey.length === 0) { throw new AnthropicApiKeyAuthError('Anthropic API key is invalid.', { requestOutcome: 'notSent' }); } return Object.freeze({ apiKey: accessArg.apiKey }); }; /** * The headers an API-key request authenticates with, over the request's own: the key replaces any credential the * request carried (an `authorization` bearer included), the OAuth beta leaves the request's betas, and the API * version is the request's or `2023-06-01`. Shared by inference and the model list. */ export function createAnthropicApiKeyHeaders(accessArg: IAnthropicApiKeyAccess, headersArg?: HeadersInit): Headers { const headers = new Headers(headersArg); headers.delete('authorization'); headers.set('x-api-key', accessArg.apiKey); const betas = [...new Set((headers.get('anthropic-beta') ?? '').split(',').map((entry) => entry.trim()) .filter((entry) => entry.length > 0 && entry !== ANTHROPIC_OAUTH_BETA))]; if (betas.length === 0) headers.delete('anthropic-beta'); else headers.set('anthropic-beta', betas.join(',')); if (!headers.has('anthropic-version')) headers.set('anthropic-version', ANTHROPIC_API_VERSION); return headers; } /** * An Anthropic API connection on an API key, for inference billed to the key's Claude Console organization. * * Requests go only to `https://api.anthropic.com/v1`, with `x-api-key` and without any bearer token or OAuth beta. * A provider 401 fails with an `AnthropicApiKeyAuthError` whose `status` is 401, since a rejected key does not renew; * every other status is the caller's. */ export const createAnthropicApiKeyConnection = (optionsArg: IAnthropicApiKeyConnectionOptions): IAnthropicModelConnection => { const access = requireAccess(optionsArg); const transport = optionsArg.fetch ?? globalThis.fetch; if (typeof transport !== 'function') throw new AnthropicApiKeyAuthError('fetch is not available for Anthropic inference.'); const fetchWithApiKey: typeof fetch = async (inputArg, initArg) => { const request = new Request(inputArg, { ...initArg, redirect: 'error' }); if (!isAnthropicApiRequestUrl(request.url)) { throw new AnthropicApiKeyAuthError('Anthropic API key request URL is outside the Anthropic API.', { requestOutcome: 'notSent' }); } const authenticated = new Request(request, { headers: createAnthropicApiKeyHeaders(access, request.headers) }); authenticated.signal.throwIfAborted(); const response = await transport(authenticated); if (response.status !== 401) return response; await response.body?.cancel().catch(() => undefined); throw new AnthropicApiKeyAuthError('Anthropic rejected the API key.', { status: 401, requestOutcome: 'outcomeUnknown' }); }; if (optionsArg.fetch === undefined) registerAnthropicCacheTransparentTransport(fetchWithApiKey); return { // The transport authenticates every request; the empty key keeps the AI SDK from reading its own. settings: { apiKey: '', baseURL: ANTHROPIC_API_BASE_URL, fetch: fetchWithApiKey }, classifyLimit: classifyAnthropicLimit, }; }; /** * Reads the models an API key may use from `GET /v1/models`, in the shape and with the paging and failures of * `listAnthropicOAuthModels`, authenticated with `x-api-key`. A rejected key fails with an `AnthropicApiKeyAuthError` * whose `status` is 401. */ export async function listAnthropicApiKeyModels( accessArg: IAnthropicApiKeyAccess, optionsArg: IAnthropicOAuthModelListOptions = {}, ): Promise { const access = requireAccess(accessArg); const transport = optionsArg.fetch ?? globalThis.fetch; if (typeof transport !== 'function') throw new AnthropicApiKeyAuthError('fetch is not available for the Anthropic model list.'); return readAnthropicModelList(createAnthropicApiKeyHeaders(access, { accept: 'application/json' }), transport, optionsArg.signal, () => new AnthropicApiKeyAuthError('Anthropic rejected the API key.', { status: 401 })); }