import type * as plugins from './plugins.js'; import { classifyAnthropicLimit } from './smartai.limits.anthropic.js'; import { registerAnthropicCacheTransparentTransport } from './smartai.cache.anthropic.js'; /** The Anthropic API every OAuth and API-key request goes to; the AI SDK's versioned base URL. */ export const ANTHROPIC_API_BASE_URL = 'https://api.anthropic.com/v1'; /** * The beta a Claude subscription OAuth access token is accepted under. Claude Code 2.1.282 adds it to its own * requests exactly when it holds such a token (its `oauth_auth` beta, `oauth-2025-04-20`). */ export const ANTHROPIC_OAUTH_BETA = 'oauth-2025-04-20'; /** The Messages API version Claude Code and the AI SDK send. */ export const ANTHROPIC_API_VERSION = '2023-06-01'; /** Whether a failed request reached the provider: `notSent` never did, `outcomeUnknown` may have. */ export type TAnthropicOAuthRequestOutcome = 'notSent' | 'outcomeUnknown'; export class AnthropicOAuthAuthError extends Error { public status?: number; public requestOutcome?: TAnthropicOAuthRequestOutcome; constructor(message: string, options: { status?: number; requestOutcome?: TAnthropicOAuthRequestOutcome } = {}) { super(message); this.name = 'AnthropicOAuthAuthError'; this.status = options.status; this.requestOutcome = options.requestOutcome; } } /** The Claude account and organization a connection is pinned to for its lifetime, as the authority states them. */ export interface IAnthropicOAuthIdentity { readonly accountUuid: string; readonly organizationUuid: string; } /** A Claude subscription OAuth access token, read for itself alone. */ export interface IAnthropicOAuthReadAccess { readonly accessToken: string; } /** Access to one Claude account, as an account authority resolves it. */ export interface IAnthropicOAuthAccessGrant extends IAnthropicOAuthReadAccess, IAnthropicOAuthIdentity { /** * The authority's generation of this access token. When it is set and the provider rejects the token, the * connection resolves once more naming this generation, so the authority can renew exactly that token. */ readonly generation?: number; } export interface IAnthropicOAuthAccessResolveRequest { /** The provider request signal. A resolver should pass it through to its authority. */ readonly signal: AbortSignal; /** The generation of the access token the provider has just rejected with 401. */ readonly rejectedGeneration?: number; } export interface IAnthropicOAuthResolvingConnectionOptions { /** Every resolved access must state exactly this account and organization. */ readonly expectedIdentity: IAnthropicOAuthIdentity; /** Resolves current access immediately before every provider request. */ readonly resolveAccess: (request: IAnthropicOAuthAccessResolveRequest) => Promise; /** Optional underlying transport. Defaults to the current global fetch. */ readonly fetch?: typeof fetch; } /** The provider owns inference; an authentication component supplies this connection. */ export interface IAnthropicModelConnection { settings: plugins.AnthropicProviderSettings; middleware?: plugins.LanguageModelV4Middleware; /** Reads this connection's own limit dialect first; the Anthropic API dialect handles the rest. */ classifyLimit?: plugins.TModelLimitClassifier; } const apiBaseUrl = new URL(ANTHROPIC_API_BASE_URL); const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.length > 0; const isGeneration = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 1; /** Whether a request URL is under `ANTHROPIC_API_BASE_URL` and carries no credentials. Shared by both kinds of login. */ export function isAnthropicApiRequestUrl(urlArg: string): boolean { const url = new URL(urlArg); return url.origin === apiBaseUrl.origin && url.username === '' && url.password === '' && (url.pathname === apiBaseUrl.pathname || url.pathname.startsWith(`${apiBaseUrl.pathname}/`)); } function assertApiRequestUrl(urlArg: string): void { if (!isAnthropicApiRequestUrl(urlArg)) { throw new AnthropicOAuthAuthError('Anthropic OAuth request URL is outside the Anthropic API.', { requestOutcome: 'notSent' }); } } function requireIdentity(identityArg: IAnthropicOAuthIdentity | undefined): IAnthropicOAuthIdentity { if (!identityArg || !isNonEmptyString(identityArg.accountUuid) || !isNonEmptyString(identityArg.organizationUuid)) { throw new AnthropicOAuthAuthError('Anthropic OAuth account identity is invalid.'); } return Object.freeze({ accountUuid: identityArg.accountUuid, organizationUuid: identityArg.organizationUuid }); } function assertGrant(grantArg: IAnthropicOAuthAccessGrant, expectedIdentityArg: IAnthropicOAuthIdentity): void { if (!grantArg || !isNonEmptyString(grantArg.accessToken) || (grantArg.generation !== undefined && !isGeneration(grantArg.generation))) { throw new AnthropicOAuthAuthError('Anthropic OAuth resolved access is invalid.', { requestOutcome: 'notSent' }); } if (grantArg.accountUuid !== expectedIdentityArg.accountUuid || grantArg.organizationUuid !== expectedIdentityArg.organizationUuid) { throw new AnthropicOAuthAuthError('Anthropic OAuth resolved access identity does not match the connection.', { requestOutcome: 'notSent' }); } } /** A comma-separated `anthropic-beta` value with the OAuth beta added once, keeping the caller's order. */ export function mergeAnthropicOAuthBeta(valueArg: string | null): string { const betas = (valueArg ?? '').split(',').map((entry) => entry.trim()).filter((entry) => entry.length > 0); const unique = [...new Set(betas)]; if (!unique.includes(ANTHROPIC_OAUTH_BETA)) unique.push(ANTHROPIC_OAUTH_BETA); return unique.join(','); } /** * The headers an OAuth request authenticates with, over the request's own: the bearer token replaces any * credential the request carried (an `x-api-key` included), the OAuth beta joins 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 createAnthropicOAuthHeaders(accessArg: IAnthropicOAuthReadAccess, headersArg?: HeadersInit): Headers { const headers = new Headers(headersArg); headers.delete('x-api-key'); headers.set('authorization', `Bearer ${accessArg.accessToken}`); headers.set('anthropic-beta', mergeAnthropicOAuthBeta(headers.get('anthropic-beta'))); if (!headers.has('anthropic-version')) headers.set('anthropic-version', ANTHROPIC_API_VERSION); return headers; } const accessRejected = (): AnthropicOAuthAuthError => new AnthropicOAuthAuthError( 'Anthropic rejected the OAuth access token.', { status: 401, requestOutcome: 'outcomeUnknown' }, ); /** * An Anthropic API connection on a Claude subscription OAuth login that resolves its access before every request. * * Requests go only to `https://api.anthropic.com/v1`. The account and organization are pinned at construction; * an access that states another stops the request before the transport is called. A provider 401 is answered * once: when the rejected access carried a `generation`, the connection resolves again with `rejectedGeneration` * and sends the request a second time with the new access. A 401 that cannot be retried, and a second 401, fail * with an `AnthropicOAuthAuthError` whose `status` is 401. Every other status is the caller's. */ export const createAnthropicOAuthResolvingConnection = ( optionsArg: IAnthropicOAuthResolvingConnectionOptions, ): IAnthropicModelConnection => { if (!optionsArg || typeof optionsArg.resolveAccess !== 'function') { throw new AnthropicOAuthAuthError('Anthropic OAuth access resolver is required.'); } const expectedIdentity = requireIdentity(optionsArg.expectedIdentity); const resolveAccess = optionsArg.resolveAccess; const transport = optionsArg.fetch ?? globalThis.fetch; if (typeof transport !== 'function') throw new AnthropicOAuthAuthError('fetch is not available for Anthropic inference.'); const resolveGrant = async (requestArg: IAnthropicOAuthAccessResolveRequest): Promise => { const grant = await resolveAccess(requestArg); requestArg.signal.throwIfAborted(); assertGrant(grant, expectedIdentity); return grant; }; const send = (requestArg: Request, grantArg: IAnthropicOAuthAccessGrant): Promise => { const authenticated = new Request(requestArg, { headers: createAnthropicOAuthHeaders(grantArg, requestArg.headers) }); authenticated.signal.throwIfAborted(); return transport(authenticated); }; const fetchWithCurrentAccess: typeof fetch = async (inputArg, initArg) => { const request = new Request(inputArg, { ...initArg, redirect: 'error' }); assertApiRequestUrl(request.url); request.signal.throwIfAborted(); const grant = await resolveGrant({ signal: request.signal }); // A replay needs the body the first attempt consumes, so it is kept only when a replay can happen. const replay = grant.generation === undefined ? undefined : request.clone(); const response = await send(request, grant); if (response.status !== 401) return response; await response.body?.cancel().catch(() => undefined); if (!replay) throw accessRejected(); const renewed = await resolveGrant({ signal: replay.signal, rejectedGeneration: grant.generation }); const replayed = await send(replay, renewed); if (replayed.status !== 401) return replayed; await replayed.body?.cancel().catch(() => undefined); throw accessRejected(); }; if (optionsArg.fetch === undefined) registerAnthropicCacheTransparentTransport(fetchWithCurrentAccess); 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: fetchWithCurrentAccess }, classifyLimit: classifyAnthropicLimit, }; }; /** An effort level a request can ask a model for: the Messages API's `output_config.effort`, as the AI SDK sends it. */ export type TAnthropicEffort = NonNullable; /** The rank of every effort level a request can name; keyed by level, so a level the AI SDK adds cannot be left out. */ const effortRanks: Readonly> = { low: 1, medium: 2, high: 3, xhigh: 4, max: 5 }; /** Every effort level a request can name, lowest first. */ export const ANTHROPIC_EFFORTS: readonly TAnthropicEffort[] = Object.freeze((Object.keys(effortRanks) as TAnthropicEffort[]) .sort((leftArg, rightArg) => effortRanks[leftArg] - effortRanks[rightArg])); /** A model an account may use, as the Anthropic API lists it. */ export interface IAnthropicOAuthModel { providerId: 'anthropic'; modelId: string; displayName: string; /** RFC 3339 release time, when the API states one. */ createdAt?: string; /** The context window in tokens, when the API states it. */ maxInputTokens?: number; /** The output limit in tokens, when the API states it. */ maxOutputTokens?: number; /** * The effort levels the model accepts, lowest first, when the API states its effort capability; empty when it * states the model takes none. Only levels a request can name (`ANTHROPIC_EFFORTS`) are listed. */ efforts?: TAnthropicEffort[]; /** Whether the model accepts adaptive thinking (`thinking: { type: 'adaptive' }`), when the API states it. */ adaptiveThinking?: boolean; } /** * Why a model list read failed, other than a rejected access token or an abort. * * - `NETWORK_FAILED`: the request did not complete. * - `HTTP_ERROR`: the API answered with an error status other than 401; `status` names it. * - `PROTOCOL_ERROR`: the answer was oversized or not a model list this package can read. */ export type TAnthropicOAuthModelListErrorCode = 'NETWORK_FAILED' | 'HTTP_ERROR' | 'PROTOCOL_ERROR'; export class AnthropicOAuthModelListError extends Error { public readonly code: TAnthropicOAuthModelListErrorCode; public readonly status?: number; constructor(codeArg: TAnthropicOAuthModelListErrorCode, statusArg?: number) { super(`Anthropic model list request failed (${codeArg}${statusArg === undefined ? '' : ` ${statusArg}`}).`); this.name = 'AnthropicOAuthModelListError'; this.code = codeArg; if (statusArg !== undefined) this.status = statusArg; } } export interface IAnthropicOAuthModelListOptions { signal?: AbortSignal; /** Optional underlying transport. Defaults to the current global fetch. */ fetch?: typeof fetch; } const maximumPageBytes = 1024 * 1024; const maximumModels = 1000; const maximumPages = 10; const textEncoder = new TextEncoder(); const protocolError = (): AnthropicOAuthModelListError => new AnthropicOAuthModelListError('PROTOCOL_ERROR'); const isRecord = (valueArg: unknown): valueArg is Record => typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg); const boundedString = (valueArg: unknown, maximumBytesArg: number): string => { if (typeof valueArg !== 'string' || valueArg.length === 0 || textEncoder.encode(valueArg).byteLength > maximumBytesArg) { throw protocolError(); } return valueArg; }; const optionalTokens = (valueArg: unknown): number | undefined => { if (valueArg === undefined || valueArg === null) return undefined; if (!Number.isSafeInteger(valueArg) || (valueArg as number) < 1) throw protocolError(); return valueArg as number; }; /** A capability node of `/v1/models`: absent, or an object whose `supported` is a boolean. */ const capability = (valueArg: unknown): (Record & { supported: boolean }) | undefined => { if (valueArg === undefined || valueArg === null) return undefined; if (!isRecord(valueArg) || typeof valueArg.supported !== 'boolean') throw protocolError(); return valueArg as Record & { supported: boolean }; }; /** * What a model's capability tree states about effort and adaptive thinking. The tree states every capability with * `supported` at each node; a node this package does not read is left alone, so a capability the API adds later * does not fail the list. */ const readCapabilities = (valueArg: unknown): Pick => { if (valueArg === undefined || valueArg === null) return {}; if (!isRecord(valueArg)) throw protocolError(); const effort = capability(valueArg.effort); const thinking = capability(valueArg.thinking); let adaptiveThinking: boolean | undefined; if (thinking) { if (thinking.types !== undefined && thinking.types !== null && !isRecord(thinking.types)) throw protocolError(); const adaptive = capability(isRecord(thinking.types) ? thinking.types.adaptive : undefined); adaptiveThinking = thinking.supported === false ? false : adaptive?.supported; } return { ...(effort === undefined ? {} : { efforts: ANTHROPIC_EFFORTS.filter((levelArg) => effort.supported === true && capability(effort[levelArg])?.supported === true), }), ...(adaptiveThinking === undefined ? {} : { adaptiveThinking }), }; }; const readPage = async (responseArg: Response, signalArg: AbortSignal | undefined): Promise => { const declared = responseArg.headers.get('content-length'); if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > maximumPageBytes)) { await responseArg.body?.cancel().catch(() => undefined); throw protocolError(); } if (!responseArg.body) throw protocolError(); const reader = responseArg.body.getReader(); const chunks: Uint8Array[] = []; let size = 0; let completed = false; const onAbort = (): void => { void reader.cancel().catch(() => undefined); }; signalArg?.addEventListener('abort', onAbort, { once: true }); if (signalArg?.aborted) onAbort(); try { while (true) { signalArg?.throwIfAborted(); const { done, value } = await reader.read(); signalArg?.throwIfAborted(); if (done) break; size += value.byteLength; if (size > maximumPageBytes) { await reader.cancel().catch(() => undefined); throw protocolError(); } chunks.push(value); } completed = true; } finally { signalArg?.removeEventListener('abort', onAbort); if (!completed) void reader.cancel().catch(() => undefined); reader.releaseLock(); } try { return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks))) as unknown; } catch { throw protocolError(); } }; /** * Reads the models a Claude subscription OAuth login may use: `GET /v1/models` with the bearer token and the * OAuth beta, as Claude Code's model-capability read does (`models.list({ betas: [oauth-2025-04-20], limit: 1000 })`), * following `has_more` with `after_id` across at most ten pages. A rejected access token fails with an * `AnthropicOAuthAuthError` whose `status` is 401, so a caller that holds a renewable access resolves it again * and repeats the read. An abort rejects with the signal's reason; every other failure is an * `AnthropicOAuthModelListError`. */ export async function listAnthropicOAuthModels( accessArg: IAnthropicOAuthReadAccess, optionsArg: IAnthropicOAuthModelListOptions = {}, ): Promise { if (!accessArg || !isNonEmptyString(accessArg.accessToken)) { throw new AnthropicOAuthAuthError('Anthropic OAuth access is invalid.'); } const transport = optionsArg.fetch ?? globalThis.fetch; if (typeof transport !== 'function') throw new AnthropicOAuthAuthError('fetch is not available for the Anthropic model list.'); return readAnthropicModelList(createAnthropicOAuthHeaders(accessArg, { accept: 'application/json' }), transport, optionsArg.signal, () => new AnthropicOAuthAuthError('Anthropic rejected the OAuth access token.', { status: 401 })); } /** * Reads `GET /v1/models` with the headers a login authenticates with, following `has_more` with `after_id` across at * most ten pages. A 401 fails with the login's own error; an abort rejects with the signal's reason; every other * failure is an `AnthropicOAuthModelListError`. Shared by both kinds of login. */ export async function readAnthropicModelList( headersArg: Headers, transportArg: typeof fetch, signalArg: AbortSignal | undefined, rejectedArg: () => Error, ): Promise { signalArg?.throwIfAborted(); const models: IAnthropicOAuthModel[] = []; const modelIds = new Set(); let afterId: string | undefined; for (let page = 0; page < maximumPages; page++) { const url = new URL(`${ANTHROPIC_API_BASE_URL}/models`); url.searchParams.set('limit', String(maximumModels)); if (afterId !== undefined) url.searchParams.set('after_id', afterId); let response: Response; try { response = await transportArg(url.toString(), { method: 'GET', redirect: 'error', signal: signalArg, headers: new Headers(headersArg) }); } catch { if (signalArg?.aborted) throw signalArg.reason; throw new AnthropicOAuthModelListError('NETWORK_FAILED'); } if (!response.ok) { await response.body?.cancel().catch(() => undefined); if (response.status === 401) throw rejectedArg(); throw new AnthropicOAuthModelListError('HTTP_ERROR', response.status); } const body = await readPage(response, signalArg); if (!isRecord(body) || !Array.isArray(body.data) || typeof body.has_more !== 'boolean') throw protocolError(); for (const raw of body.data) { if (!isRecord(raw) || (raw.type !== undefined && raw.type !== 'model')) throw protocolError(); const modelId = boundedString(raw.id, 256); if (modelIds.has(modelId)) throw protocolError(); modelIds.add(modelId); if (models.length >= maximumModels) throw protocolError(); const createdAt = raw.created_at === undefined || raw.created_at === null ? undefined : boundedString(raw.created_at, 64); const maxInputTokens = optionalTokens(raw.max_input_tokens); const maxOutputTokens = optionalTokens(raw.max_tokens); models.push({ providerId: 'anthropic', modelId, displayName: raw.display_name === undefined || raw.display_name === null ? modelId : boundedString(raw.display_name, 512), ...(createdAt === undefined ? {} : { createdAt }), ...(maxInputTokens === undefined ? {} : { maxInputTokens }), ...(maxOutputTokens === undefined ? {} : { maxOutputTokens }), ...readCapabilities(raw.capabilities), }); } if (!body.has_more) return models; afterId = boundedString(body.last_id, 256); } throw protocolError(); }