@alvin0/ai-agent-sdk-provider-http 0.1.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,"file":"index.js","names":["ENCODER","positiveFinite","positiveFinite"],"sources":["../src/common/config.ts","../src/stream/parser.ts","../src/stream/config.ts","../src/stream/idle-deadline.ts","../src/stream/terminal.ts","../src/common/failure.ts","../src/common/header-layers.ts","../src/base/http-errors.ts","../src/base/transport.ts","../src/base/http-adapter.ts","../src/common/data.ts","../src/common/json-snapshot.ts","../src/protocol/definition.ts","../src/protocol/protocol.ts","../src/observation/operations.ts","../src/configurable/http-provider.ts","../src/common/wire-body.ts","../src/configurable/runtime-provider.ts","../src/stream/sse.ts"],"sourcesContent":["/** Runtime wire-protocol contract version supported by this package. */\nexport const HTTP_PROTOCOL_API_VERSION = 1 as const\n\n/** Stable support-safe errors owned by the runtime HTTP extension path. */\nexport const HTTP_PROVIDER_ERROR_CODES = Object.freeze({\n PROTOCOL_API_UNSUPPORTED: 'HTTP_PROTOCOL_API_UNSUPPORTED',\n HEADER_INVALID: 'HTTP_HEADER_INVALID',\n HEADER_RESERVED: 'HTTP_HEADER_RESERVED',\n HEADER_COLLISION: 'HTTP_HEADER_COLLISION',\n WIRE_BODY_INVALID: 'HTTP_WIRE_BODY_INVALID',\n WIRE_BODY_TOO_LARGE: 'HTTP_WIRE_BODY_TOO_LARGE',\n STREAM_MEDIA_TYPE_INVALID: 'HTTP_STREAM_MEDIA_TYPE_INVALID',\n SSE_LIMIT_EXCEEDED: 'HTTP_SSE_LIMIT_EXCEEDED',\n REDIRECT_REJECTED: 'HTTP_REDIRECT_REJECTED',\n} as const)\n\nexport const HTTP_PROTOCOL_LIMITS = Object.freeze({\n idBytes: 128,\n dialectDepth: 16,\n dialectNodes: 4_096,\n dialectObjectFields: 1_024,\n dialectArrayItems: 4_096,\n dialectKeyBytes: 1_024,\n dialectBytes: 1024 * 1024,\n})\n\n/** Structural limits for detached runtime-provider configuration snapshots. */\nexport const HTTP_RUNTIME_OPTION_LIMITS = Object.freeze({\n maxDepth: 16,\n maxNodes: 16_384,\n maxObjectFields: 4_096,\n maxArrayItems: 4_096,\n maxKeyBytes: 1_024,\n maxBytes: 4 * 1024 * 1024,\n})\n\n/** Bounds for a failure envelope received across a package/runtime boundary. */\nexport const HTTP_FOREIGN_FAILURE_LIMITS = Object.freeze({\n messageBytes: 2_048,\n codeBytes: 128,\n requestIdBytes: 1_024,\n})\n","import { ModelError, waitForSettlement } from '@alvin0/ai-agent-sdk-core'\nimport { createParser } from 'eventsource-parser'\nimport { HTTP_PROVIDER_ERROR_CODES } from '../common/config.ts'\nimport type { SseEvent } from './sse.ts'\nimport type { SseParserLimits } from './config.ts'\n\n/** Internal bounded parser used by the HTTP transport. */\nexport async function* parseSseBounded(\n stream: ReadableStream<Uint8Array>,\n onActivity: (() => void) | undefined,\n teardownTimeoutMs: number,\n limits: SseParserLimits,\n): AsyncGenerator<SseEvent> {\n const pending: SseEvent[] = []\n let emitted = 0\n const parser = createParser({\n maxBufferSize: limits.maxEventChars,\n onError(error) {\n if (error.type === 'max-buffer-size-exceeded') throw limitError('character')\n },\n onEvent(event) {\n emitted++\n if (emitted > limits.maxEvents || event.data.length > limits.maxEventChars) {\n throw limitError(emitted > limits.maxEvents ? 'event-count' : 'character')\n }\n pending.push({ event: event.event, data: event.data })\n },\n onComment() { onActivity?.() },\n })\n\n const decoder = new TextDecoder()\n const reader = stream.getReader()\n let drained = false\n let primaryFailure: unknown\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n if (value !== undefined && value.byteLength > 0) onActivity?.()\n if (value !== undefined) parser.feed(decoder.decode(value, { stream: true }))\n yield* drainBatch(pending)\n }\n const tail = decoder.decode()\n if (tail.length > 0) {\n parser.feed(tail)\n yield* drainBatch(pending)\n }\n drained = true\n } catch (error: unknown) {\n primaryFailure = error\n throw error\n } finally {\n if (drained) reader.releaseLock()\n else {\n let cancellationFailure: unknown\n const cancellation = reader.cancel()\n .catch((error: unknown) => { cancellationFailure = error })\n const settled = await waitForSettlement(cancellation, teardownTimeoutMs)\n // Parser/protocol failure is the support-relevant cause. A broken body\n // cancellation path must not overwrite it with secondary teardown noise.\n if (primaryFailure === undefined) {\n if (!settled) {\n throw new Error(`SSE body ignored cancellation for more than ${teardownTimeoutMs}ms`)\n }\n if (cancellationFailure !== undefined) throw cancellationFailure\n }\n }\n }\n}\n\n/** Cursor iteration avoids repeated array compaction from Array.shift(). */\nfunction* drainBatch(pending: SseEvent[]): Generator<SseEvent> {\n for (let index = 0; index < pending.length; index++) {\n const event = pending[index]\n if (event !== undefined) yield event\n }\n pending.length = 0\n}\n\nfunction limitError(kind: 'event-count' | 'character'): ModelError {\n return new ModelError(\n `provider SSE event buffer ${kind} limit exceeded`,\n HTTP_PROVIDER_ERROR_CODES.SSE_LIMIT_EXCEEDED,\n )\n}\n","export const DEFAULT_MAX_SSE_EVENTS = 100_000\nexport const DEFAULT_MAX_SSE_EVENT_CHARS = 1_048_576\nexport const DEFAULT_SSE_TEARDOWN_TIMEOUT_MS = 30_000\n\nexport interface SseParserLimits {\n readonly maxEvents: number\n readonly maxEventChars: number\n}\n","import { MODEL_ERROR_CODES, ModelError, waitForSettlement } from '@alvin0/ai-agent-sdk-core'\n\n/** One resettable deadline shared by every body read in one physical attempt. */\nexport interface StreamIdleDeadline {\n /** Reset the deadline after a non-empty response-body read or SSE heartbeat. */\n readonly activity: () => void\n /** Race source progress against the deadline and bound source teardown. */\n readonly guard: <T>(source: AsyncIterable<T>) => AsyncGenerator<T>\n}\n\n/**\n * Create one idle timer for a physical provider attempt.\n *\n * The parser calls `activity` while one `iterator.next()` is pending. Resetting\n * the same timer lets comment-only heartbeats keep that read alive without\n * manufacturing protocol events. A primary timeout is never replaced by a\n * secondary iterator-cancellation failure.\n */\nexport function createStreamIdleDeadline(\n timeoutMs: number,\n displayName: string,\n teardownTimeoutMs: number,\n): StreamIdleDeadline {\n let timer: ReturnType<typeof setTimeout> | undefined\n let expired = false\n let rejectExpiry: ((error: Error) => void) | undefined\n const expiry = new Promise<never>((_resolve, reject) => { rejectExpiry = reject })\n // The deadline may expire while the consumer is between reads. Keep that\n // rejection observed; the next guarded read still receives the same error.\n void expiry.catch(() => undefined)\n\n const activity = () => {\n if (expired) return\n if (timer !== undefined) clearTimeout(timer)\n timer = setTimeout(() => {\n expired = true\n rejectExpiry?.(new ModelError(\n `${displayName} stream idle for more than ${timeoutMs}ms`,\n MODEL_ERROR_CODES.TIMEOUT,\n ))\n }, timeoutMs)\n }\n\n const dispose = () => {\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n }\n\n const guard = async function* <T>(source: AsyncIterable<T>): AsyncGenerator<T> {\n const iterator = source[Symbol.asyncIterator]()\n let exhausted = false\n let primaryFailure: unknown\n activity()\n try {\n while (true) {\n const result = await Promise.race([iterator.next(), expiry])\n if (result.done === true) {\n exhausted = true\n return\n }\n yield result.value\n }\n } catch (error: unknown) {\n primaryFailure = error\n throw error\n } finally {\n dispose()\n if (!exhausted) {\n const close = iterator.return?.bind(iterator)\n if (close !== undefined) {\n let closeFailure: unknown\n const closing = Promise.resolve().then(async () => { await close() })\n .catch((error: unknown) => { closeFailure = error })\n const settled = await waitForSettlement(closing, teardownTimeoutMs)\n if (primaryFailure === undefined) {\n if (!settled) {\n throw new ModelError(\n `${displayName} stream teardown exceeded ${teardownTimeoutMs}ms`,\n MODEL_ERROR_CODES.TEARDOWN_TIMEOUT,\n )\n }\n if (closeFailure !== undefined) throw closeFailure\n }\n }\n }\n }\n }\n\n return Object.freeze({ activity, guard })\n}\n","import { MODEL_ERROR_CODES, ModelError, type StreamChunk } from '@alvin0/ai-agent-sdk-core'\nimport type { ProviderProtocolChunk } from './types.ts'\n\n/**\n * Enforce the provider-neutral stream terminal contract.\n *\n * The finish chunk is held until the translator ends. That makes it impossible\n * for a custom protocol to expose a finish and then append more output. Earlier\n * output remains streaming; a truncated response after visible output is still\n * surfaced and therefore cannot be retried by the outer retry adapter.\n */\nexport async function* requireTerminalFinish(\n source: AsyncIterable<ProviderProtocolChunk>,\n displayName: string,\n): AsyncGenerator<ProviderProtocolChunk> {\n let finish: Extract<StreamChunk, { readonly type: 'finish' }> | undefined\n for await (const chunk of source) {\n if (finish !== undefined) {\n throw new ModelError(\n `${displayName} protocol emitted output after its terminal finish`,\n MODEL_ERROR_CODES.MALFORMED_RESPONSE,\n )\n }\n if (chunk.type === 'finish') {\n finish = chunk\n continue\n }\n yield chunk\n }\n if (finish === undefined) {\n throw new ModelError(\n `${displayName} response ended before a terminal finish`,\n MODEL_ERROR_CODES.STREAM_CLOSED,\n )\n }\n yield finish\n}\n","import {\n MODEL_ERROR_CODES,\n ModelError,\n type ModelFailure,\n type ProviderRequestId,\n} from '@alvin0/ai-agent-sdk-core'\nimport { HTTP_FOREIGN_FAILURE_LIMITS } from './config.ts'\n\nconst ENCODER = new TextEncoder()\nconst INVALID_FIELD = Symbol('invalid failure field')\n\ntype EnvelopeProbe =\n | { readonly kind: 'absent' }\n | { readonly kind: 'invalid' }\n | { readonly kind: 'valid'; readonly failure: ModelFailure }\n\n/** Read an own data property without invoking getters or inherited state. */\nfunction ownDataProbe(\n source: object,\n key: PropertyKey,\n): { readonly present: boolean; readonly data: boolean; readonly value?: unknown } {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)\n if (descriptor === undefined) return { present: false, data: true }\n if (!('value' in descriptor)) return { present: true, data: false }\n return { present: true, data: true, value: descriptor.value }\n } catch {\n return { present: true, data: false }\n }\n}\n\nfunction boundedString(value: unknown, maxBytes: number): value is string {\n return typeof value === 'string'\n && value.length > 0\n && ENCODER.encode(value).byteLength <= maxBytes\n}\n\nfunction optionalFailureField(source: object, key: PropertyKey): unknown {\n const field = ownDataProbe(source, key)\n return field.data ? field.value : INVALID_FIELD\n}\n\n/**\n * Validate the data twin carried by a ModelError from another core copy/realm.\n * A lone outer code is deliberately insufficient: retry policy may trust a code\n * only when the bounded inner envelope exists and agrees with it.\n */\nfunction probeFailureEnvelope(value: unknown): EnvelopeProbe {\n if ((typeof value !== 'object' && typeof value !== 'function') || value === null) {\n return { kind: 'absent' }\n }\n\n const outerCode = ownDataProbe(value, 'code')\n const carried = ownDataProbe(value, 'failure')\n if (!outerCode.present && !carried.present) return { kind: 'absent' }\n if (!outerCode.data || !carried.data\n || !boundedString(outerCode.value, HTTP_FOREIGN_FAILURE_LIMITS.codeBytes)\n || typeof carried.value !== 'object' || carried.value === null || Array.isArray(carried.value)) {\n return { kind: 'invalid' }\n }\n\n const message = optionalFailureField(carried.value, 'message')\n const code = optionalFailureField(carried.value, 'code')\n const status = optionalFailureField(carried.value, 'status')\n const providerRetryAfterMs = optionalFailureField(carried.value, 'providerRetryAfterMs')\n const requestId = optionalFailureField(carried.value, 'requestId')\n if (message === INVALID_FIELD || code === INVALID_FIELD || status === INVALID_FIELD\n || providerRetryAfterMs === INVALID_FIELD || requestId === INVALID_FIELD\n || !boundedString(message, HTTP_FOREIGN_FAILURE_LIMITS.messageBytes)\n || !boundedString(code, HTTP_FOREIGN_FAILURE_LIMITS.codeBytes)\n || code !== outerCode.value\n || (status !== undefined && (!Number.isSafeInteger(status) || (status as number) < 100 || (status as number) > 599))\n || (providerRetryAfterMs !== undefined\n && (!Number.isFinite(providerRetryAfterMs) || (providerRetryAfterMs as number) <= 0))\n || (requestId !== undefined\n && !boundedString(requestId, HTTP_FOREIGN_FAILURE_LIMITS.requestIdBytes))) {\n return { kind: 'invalid' }\n }\n\n return {\n kind: 'valid',\n failure: Object.freeze({\n message,\n code,\n ...status === undefined ? {} : { status: status as number },\n ...providerRetryAfterMs === undefined ? {} : { providerRetryAfterMs: providerRetryAfterMs as number },\n ...requestId === undefined ? {} : { requestId: requestId as ProviderRequestId },\n }),\n }\n}\n\n/** Normalize a foreign provider failure without relying on package class identity. */\nexport function normalizeHttpBoundaryError(value: unknown, fallbackMessage: string): ModelError {\n const envelope = probeFailureEnvelope(value)\n if (envelope.kind === 'absent') {\n return new ModelError(fallbackMessage, MODEL_ERROR_CODES.TRANSPORT, { cause: value })\n }\n if (envelope.kind === 'invalid') {\n return new ModelError(\n 'provider supplied an invalid failure envelope',\n MODEL_ERROR_CODES.UNKNOWN,\n { cause: value },\n )\n }\n const failure = envelope.failure\n return new ModelError(failure.message, failure.code, {\n cause: value,\n ...failure.status === undefined ? {} : { status: failure.status },\n ...failure.providerRetryAfterMs === undefined\n ? {}\n : { providerRetryAfterMs: failure.providerRetryAfterMs },\n ...failure.requestId === undefined ? {} : { requestId: failure.requestId },\n })\n}\n","import { AgentSdkError } from '@alvin0/ai-agent-sdk-core/provider'\nimport { HTTP_PROVIDER_ERROR_CODES } from './config.ts'\n\nexport type HeaderLayer = 'transport' | 'sdk-attribution' | 'wire-protocol' | 'endpoint' | 'auth'\n\nexport interface HeaderLayerInput {\n readonly layer: HeaderLayer\n readonly headers: Readonly<Record<string, string>>\n}\n\nexport interface HeaderMergeResult {\n readonly headers: Readonly<Record<string, string>>\n readonly sensitiveHeaderNames: readonly string[]\n}\n\nexport const DEFAULT_TRANSPORT_HEADERS = Object.freeze({\n 'content-type': 'application/json',\n accept: 'text/event-stream',\n})\n\nconst HEADER_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\nconst FORBIDDEN_TRANSPORT_NAMES = new Set([\n 'connection', 'content-length', 'host', 'proxy-authorization', 'proxy-authenticate',\n 'te', 'trailer', 'transfer-encoding', 'upgrade',\n])\nconst TRANSPORT_OWNED_NAMES = new Set(['accept', 'content-type'])\nconst SDK_OWNED_NAMES = new Set(['user-agent'])\nconst SDK_OWNED_PREFIXES = ['x-ai-agent-sdk-'] as const\nconst SENSITIVE_NAME = /authorization|api[-_]?key|token|secret|cookie|account[-_]?id|signature/i\n\n/** Conservative fallback used in addition to exact authentication provenance. */\nexport function isSensitiveHeaderName(name: string): boolean {\n return SENSITIVE_NAME.test(name)\n}\n\n/** Detach one layer without applying ownership rules that need all layers present. */\nexport function captureHeaderLayer(input: HeaderLayerInput): HeaderLayerInput {\n const output: Record<string, string> = Object.create(null) as Record<string, string>\n const source = headerRecord(input.headers)\n for (const key of Reflect.ownKeys(source)) {\n if (typeof key !== 'string') throw headerError('Header names must be strings', 'HEADER_INVALID')\n const descriptor = Object.getOwnPropertyDescriptor(source, key)\n if (descriptor === undefined || !('value' in descriptor)) {\n throw headerError('Header values must not use accessors', 'HEADER_INVALID')\n }\n const name = key.toLowerCase()\n validateHeaderShape(name, descriptor.value)\n if (Object.hasOwn(output, name)) {\n throw headerError('Header names must be unique case-insensitively', 'HEADER_COLLISION')\n }\n output[name] = descriptor.value\n }\n return Object.freeze({ layer: input.layer, headers: Object.freeze(output) })\n}\n\n/** Validate five case-insensitive ownership layers and return one detached snapshot. */\nexport function mergeHeaderLayers(layers: readonly HeaderLayerInput[]): HeaderMergeResult {\n const output: Record<string, string> = Object.create(null) as Record<string, string>\n const owners = new Map<string, HeaderLayer>()\n const sensitive = new Set<string>()\n\n for (const raw of layers) {\n const input = captureHeaderLayer(raw)\n for (const [name, value] of Object.entries(input.headers)) {\n const first = owners.get(name)\n if (first !== undefined) {\n throw headerError(\n `Header ownership collision between ${first} and ${input.layer}`,\n 'HEADER_COLLISION',\n )\n }\n validateHeaderOwnership(name, input.layer)\n owners.set(name, input.layer)\n output[name] = value\n if (input.layer === 'auth') sensitive.add(name)\n }\n }\n\n return Object.freeze({\n headers: Object.freeze(output),\n sensitiveHeaderNames: Object.freeze([...sensitive]),\n })\n}\n\nfunction headerRecord(value: unknown): object {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw headerError('Headers must be a record', 'HEADER_INVALID')\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw headerError('Headers must be a plain record', 'HEADER_INVALID')\n }\n return value\n}\n\nfunction validateHeaderShape(name: string, value: unknown): asserts value is string {\n if (!HEADER_NAME.test(name) || name.length > 256 || typeof value !== 'string'\n || value.length > 16_384 || /[\\r\\n\\0]/.test(value)) {\n throw headerError('Header name or value is invalid', 'HEADER_INVALID')\n }\n}\n\nfunction validateHeaderOwnership(name: string, layer: HeaderLayer): void {\n if (FORBIDDEN_TRANSPORT_NAMES.has(name) || name.startsWith('sec-') || name.startsWith('proxy-')) {\n throw headerError('Header name is reserved by the transport', 'HEADER_RESERVED')\n }\n if (TRANSPORT_OWNED_NAMES.has(name) && layer !== 'transport') {\n throw headerError('Header name is owned by the transport layer', 'HEADER_RESERVED')\n }\n if (SDK_OWNED_NAMES.has(name) && layer !== 'sdk-attribution') {\n throw headerError('Header name is owned by SDK attribution', 'HEADER_RESERVED')\n }\n if (SDK_OWNED_PREFIXES.some(prefix => name.startsWith(prefix)) && layer !== 'sdk-attribution') {\n throw headerError('Header prefix is owned by SDK attribution', 'HEADER_RESERVED')\n }\n if (isSensitiveHeaderName(name) && layer !== 'auth') {\n throw headerError('Credential headers must be supplied by auth', 'HEADER_RESERVED')\n }\n}\n\nfunction headerError(\n message: string,\n key: 'HEADER_INVALID' | 'HEADER_RESERVED' | 'HEADER_COLLISION',\n): AgentSdkError {\n return new AgentSdkError(message, HTTP_PROVIDER_ERROR_CODES[key])\n}\n","/**\n * The HTTP-to-taxonomy mapping every provider shares.\n *\n * Kept here rather than per provider because the interesting decisions are\n * genuinely vendor-independent: a 429 that means \"slow down\" versus one that\n * means \"your balance is gone\", and a 400 that means \"your prompt is too long\"\n * versus one that means \"your schema is wrong\". Both distinctions are invisible\n * in the status code and both change what the caller should do, so getting them\n * right once is worth more than getting them right three times.\n *\n * @module ai-agent-sdk/providers/base/http-errors\n */\n\nimport {\n CONTEXT_WINDOW_EXCEEDED_CODE,\n QUOTA_EXCEEDED_CODE,\n isContextWindowExceededError,\n isQuotaExceededError,\n} from '@alvin0/ai-agent-sdk-core'\nimport { MODEL_ERROR_CODES } from '@alvin0/ai-agent-sdk-core'\nimport { ProviderRequestId } from '@alvin0/ai-agent-sdk-core'\n\n/**\n * Map an HTTP status plus whatever the provider said into a stable code.\n *\n * `detail` should be the provider's error `code`, `type`, and `message` joined\n * into one string — the wording classifiers need all three because providers\n * disagree about which field carries the useful part.\n * @param status - status of a non-2xx response.\n * @param detail - provider error text, joined; empty string when the body was unparseable.\n * @returns the normalized code.\n */\nexport function httpErrorCode(status: number, detail = ''): string {\n if (status === 401 || status === 403) return MODEL_ERROR_CODES.AUTH\n if (status === 413) return MODEL_ERROR_CODES.INVALID_REQUEST\n // Checked BEFORE 429: an exhausted quota is often delivered as 429 but never\n // clears on its own, so retrying it burns latency and money for nothing.\n if (isQuotaExceededError(detail)) return QUOTA_EXCEEDED_CODE\n if (status === 429) return MODEL_ERROR_CODES.RATE_LIMIT\n if (status === 400 || status === 422) {\n return isContextWindowExceededError(detail)\n ? CONTEXT_WINDOW_EXCEEDED_CODE\n : MODEL_ERROR_CODES.INVALID_REQUEST\n }\n // A missing model or route is the caller's mistake, not a server fault, so it\n // must not land in the retryable SERVER bucket.\n if (status === 404) return MODEL_ERROR_CODES.INVALID_REQUEST\n if (status >= 500) return MODEL_ERROR_CODES.SERVER\n return `HTTP_${status}`\n}\n\n/**\n * Parse a `retry-after` header into milliseconds.\n *\n * The header comes in two forms — delta-seconds and an HTTP date — and both are\n * used in practice. A date already in the past yields `undefined` rather than a\n * negative delay.\n * @param value - the raw header value, or `null` when absent.\n * @returns a positive finite delay, or `undefined` when absent or unusable.\n */\nexport function retryAfterMs(value: string | null): number | undefined {\n if (value === null) return undefined\n const trimmed = value.trim()\n if (/^\\d+$/.test(trimmed)) {\n const delay = Number(trimmed) * 1_000\n return Number.isFinite(delay) && delay > 0 ? delay : undefined\n }\n const delay = Date.parse(trimmed) - Date.now()\n return Number.isFinite(delay) && delay > 0 ? delay : undefined\n}\n\n/** Header names providers use for their request correlation id, in priority order. */\nconst REQUEST_ID_HEADERS = [\n 'request-id',\n 'x-request-id',\n 'x-requestid',\n 'cf-ray',\n] as const\n\n/**\n * Extract a provider request id for diagnostics.\n *\n * Worth capturing even though nothing programmatic reads it: when a provider is\n * misbehaving, this id is what their support needs to find the request.\n * @param headers - the response headers.\n * @returns the first non-empty id found, or `undefined`.\n */\nexport function requestIdFrom(headers: Headers): ProviderRequestId | undefined {\n for (const name of REQUEST_ID_HEADERS) {\n const value = headers.get(name)\n if (value !== null && value.length > 0) return ProviderRequestId(value)\n }\n return undefined\n}\n\n/** A provider error body reduced to the two things this SDK needs. */\nexport interface ParsedErrorBody {\n /** Best human-readable message found, or `undefined` to fall back to the status. */\n message: string | undefined\n /** Provider `code`/`type`/`message` joined, for the wording classifiers. */\n detail: string\n}\n\n/** Read a string property from an unknown object without trusting its shape. */\nfunction stringField(source: unknown, key: string): string | undefined {\n if (typeof source !== 'object' || source === null) return undefined\n const value = (source as Record<string, unknown>)[key]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Reduce a provider error body to a message and a classifier detail string.\n *\n * Handles the two shapes both providers use — `{error: {...}}` and a bare\n * `{type, message}` — and tolerates a body that is not JSON at all, which is what\n * a gateway or load balancer in front of the provider will return.\n * @param raw - the response body as text.\n * @returns the message and joined detail.\n */\nexport function parseErrorBody(raw: string): ParsedErrorBody {\n let parsed: unknown\n try {\n parsed = JSON.parse(raw) as unknown\n } catch {\n // An HTML error page from an intermediary. The status stays authoritative,\n // and the raw text is still the best classifier input available.\n return { message: undefined, detail: raw.slice(0, 2_048) }\n }\n const error = typeof parsed === 'object' && parsed !== null\n && 'error' in (parsed as Record<string, unknown>)\n ? (parsed as Record<string, unknown>).error\n : parsed\n const code = stringField(error, 'code')\n const type = stringField(error, 'type')\n const message = stringField(error, 'message')\n // The ChatGPT-backed Codex endpoint reports some rejections as a bare\n // `{\"detail\": \"...\"}` — a FastAPI convention — with no `error` wrapper and no\n // `message`. Without this, a perfectly clear \"that model is not supported\"\n // would surface as an opaque \"HTTP 400\".\n const detailField = stringField(error, 'detail') ?? stringField(parsed, 'detail')\n const parts = [code, type, message ?? detailField]\n .filter((part): part is string => part !== undefined)\n return {\n message: message ?? detailField,\n detail: parts.join(' '),\n }\n}\n","import {\n MODEL_ERROR_CODES,\n ModelError,\n waitForSettlement,\n type ModelFailure,\n type ModelInfo,\n type ResolvedModelInfo,\n type SafeErrorRecord,\n} from '@alvin0/ai-agent-sdk-core'\nimport type { ProviderCatalogModel } from './http-adapter.ts'\nimport { HTTP_PROVIDER_ERROR_CODES } from '../common/config.ts'\nimport { isSensitiveHeaderName } from '../common/header-layers.ts'\n\nexport function boundedResponseBody(\n source: ReadableStream<Uint8Array>,\n maxBytes: number,\n maxChunks: number,\n displayName: string,\n signal?: AbortSignal,\n): ReadableStream<Uint8Array> {\n let bytes = 0\n let chunks = 0\n return source.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n chunks++\n bytes += chunk.byteLength\n if (chunks > maxChunks) {\n throw new ModelError(\n `${displayName} response exceeds the ${maxChunks}-chunk limit`,\n MODEL_ERROR_CODES.TRANSPORT,\n )\n }\n if (bytes > maxBytes) {\n throw new ModelError(\n `${displayName} response exceeds the ${maxBytes}-byte limit`,\n MODEL_ERROR_CODES.TRANSPORT,\n )\n }\n controller.enqueue(chunk)\n },\n }), signal === undefined ? undefined : { signal })\n}\n\nexport async function readBoundedText(\n response: Response,\n maxBytes: number,\n signal: AbortSignal,\n): Promise<string> {\n if (response.body === null) return ''\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let bytes = 0\n let text = ''\n try {\n while (true) {\n const { done, value } = await raceWithSignal(reader.read(), signal)\n if (done) break\n if (value === undefined) continue\n const remaining = maxBytes - bytes\n if (remaining <= 0) {\n await waitForSettlement(reader.cancel().catch(() => undefined), 30_000)\n return `${text}\\n[error body truncated at ${maxBytes} bytes]`\n }\n const kept = value.byteLength <= remaining ? value : value.subarray(0, remaining)\n bytes += kept.byteLength\n text += decoder.decode(kept, { stream: true })\n if (kept.byteLength !== value.byteLength) {\n await waitForSettlement(reader.cancel().catch(() => undefined), 30_000)\n return `${text}${decoder.decode()}\\n[error body truncated at ${maxBytes} bytes]`\n }\n }\n return text + decoder.decode()\n } finally {\n reader.releaseLock()\n }\n}\n\n/** Reject every redirect shape exposed by Web fetch without following a second hop. */\nexport async function rejectProviderRedirect(response: Response, requestedUrl: string): Promise<void> {\n const redirectedStatus = response.status >= 300 && response.status < 400\n const finalUrlChanged = response.url.length > 0 && response.url !== requestedUrl\n if (response.type !== 'opaqueredirect' && response.redirected !== true\n && !redirectedStatus && !finalUrlChanged) return\n if (response.body !== null) {\n await waitForSettlement(response.body.cancel().catch(() => undefined), 30_000)\n }\n throw new ModelError(\n 'provider transport rejected a redirect before following it',\n HTTP_PROVIDER_ERROR_CODES.REDIRECT_REJECTED,\n response.status === 0 ? undefined : { status: response.status },\n )\n}\n\nexport async function raceWithSignal<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n void pending.catch(() => undefined)\n throw signal.reason ?? new Error('operation aborted')\n }\n return await new Promise<T>((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener('abort', onAbort)\n reject(signal.reason ?? new Error('operation aborted'))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n void pending.then(\n value => {\n signal.removeEventListener('abort', onAbort)\n resolve(value)\n },\n error => {\n signal.removeEventListener('abort', onAbort)\n reject(error)\n },\n )\n })\n}\n\n/** HTTP-specific ownership cleanup; generic Promise races must not dispose values. */\nexport async function cancelResponseBody(response: Response): Promise<void> {\n try {\n if (response.body === null || response.body.locked) return\n await waitForSettlement(Promise.resolve().then(() => response.body!.cancel()), 30_000)\n } catch {\n // Cleanup rejection must not replace the original transport failure.\n }\n}\n\nexport async function* withAbortSignal<T>(\n iterable: AsyncIterable<T>,\n signal: AbortSignal,\n): AsyncGenerator<T> {\n const iterator = iterable[Symbol.asyncIterator]()\n let exhausted = false\n try {\n while (true) {\n const next = await raceWithSignal(iterator.next(), signal)\n if (next.done === true) {\n exhausted = true\n return\n }\n yield next.value\n }\n } finally {\n if (!exhausted) {\n const close = iterator.return?.bind(iterator)\n if (close !== undefined) {\n const closing = Promise.resolve().then(async () => { await close() })\n await waitForSettlement(closing, 30_000)\n }\n }\n }\n}\n\nexport function positiveInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`${name} must be a positive safe integer`)\n }\n return value\n}\n\nexport function positiveFinite(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0) {\n throw new RangeError(`${name} must be a positive finite number`)\n }\n return value\n}\n\nexport function endpointUrl(baseUrl: string, path: string, allowInsecureHttp: boolean): URL {\n let base: URL\n try {\n base = new URL(baseUrl)\n } catch (error) {\n throw new ModelError(\n 'provider baseUrl is not a valid absolute URL',\n MODEL_ERROR_CODES.INVALID_REQUEST,\n { cause: error },\n )\n }\n if (base.username.length > 0 || base.password.length > 0) {\n throw new ModelError('provider baseUrl must not contain credentials', MODEL_ERROR_CODES.INVALID_REQUEST)\n }\n if (base.search.length > 0 || base.hash.length > 0) {\n throw new ModelError('provider baseUrl must not contain a query or fragment', MODEL_ERROR_CODES.INVALID_REQUEST)\n }\n if (base.protocol !== 'https:' && !(allowInsecureHttp && base.protocol === 'http:')) {\n throw new ModelError(\n 'provider baseUrl must use HTTPS unless allowInsecureHttp is explicitly enabled',\n MODEL_ERROR_CODES.INVALID_REQUEST,\n )\n }\n const normalizedBase = base.href.replace(/\\/+$/, '')\n let endpoint: URL\n try {\n endpoint = new URL(`${normalizedBase}${path}`)\n } catch (error) {\n throw new ModelError(\n 'provider endpoint path produced an invalid URL',\n MODEL_ERROR_CODES.INVALID_REQUEST,\n { cause: error },\n )\n }\n if (endpoint.origin !== base.origin) {\n throw new ModelError(\n 'provider endpoint path must remain on the configured origin',\n MODEL_ERROR_CODES.INVALID_REQUEST,\n )\n }\n return endpoint\n}\n\nexport function safeProviderFailure(failure: ModelFailure): SafeErrorRecord {\n return Object.freeze({\n type: 'ModelError',\n message: 'provider attempt failed; inspect the stable code and request ID',\n code: failure.code,\n ...(failure.status === undefined ? {} : { status: failure.status }),\n })\n}\n\nexport function redactHeaders(\n headers: Readonly<Record<string, string>>,\n sensitiveHeaderNames: readonly string[] = [],\n): Record<string, string> {\n const provenance = new Set(sensitiveHeaderNames.map(name => name.toLowerCase()))\n return Object.fromEntries(Object.entries(headers).map(([name, value]) => [\n name,\n provenance.has(name.toLowerCase()) || isSensitiveHeaderName(name) ? '[REDACTED]' : value,\n ]))\n}\n\nexport function requestLogId(): string {\n return globalThis.crypto?.randomUUID?.()\n ?? `request-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\nexport function catalogModelInfo(provider: string, model: ProviderCatalogModel): ModelInfo {\n return {\n provider,\n id: model.id,\n name: model.name ?? model.id,\n ...(model.description === undefined ? {} : { description: model.description }),\n inputModalities: model.inputModalities ?? ['text'],\n ...(model.outputModalities === undefined ? {} : { outputModalities: model.outputModalities }),\n ...(model.nativeTools === undefined ? {} : { nativeTools: model.nativeTools }),\n }\n}\n\n/** Resolve exact metadata from an advisory catalog without opening a connection. */\nexport function resolvedCatalogModelInfo(\n provider: string,\n modelId: string,\n models: readonly ProviderCatalogModel[],\n defaultMaxTokens: number,\n defaultContextWindow: number,\n): ResolvedModelInfo {\n const configured = models.find(entry => entry.id === modelId)\n return {\n ...(configured === undefined\n ? { provider, id: modelId, name: modelId, inputModalities: ['text' as const] }\n : catalogModelInfo(provider, configured)),\n context: { contextWindow: configured?.contextWindow ?? defaultContextWindow },\n defaultMaxTokens: configured?.maxTokens ?? defaultMaxTokens,\n maxOutputTokens: configured?.maxTokens ?? defaultMaxTokens,\n ...(configured?.reasoning === undefined ? {} : { reasoning: configured.reasoning }),\n ...(configured?.outputModalities === undefined ? {} : { outputModalities: configured.outputModalities }),\n }\n}\n\nexport function abortError(displayName: string, cause: unknown): ModelError {\n return new ModelError(\n `${displayName} request aborted by caller`,\n MODEL_ERROR_CODES.ABORTED,\n { cause },\n )\n}\n","/**\n * The single HTTP/SSE pipeline every provider in this package runs through.\n *\n * This is a template method, and that is the point. `stream()` is implemented\n * HERE and is not an extension point: a provider cannot accidentally ship its own\n * fetch loop that forgets attribution headers, mishandles abort, leaks a response\n * body, or invents its own error codes. What a provider supplies is only the four\n * things that are genuinely vendor-specific:\n *\n * - {@link HttpModelAdapter.connect} — where to send it and with what credentials\n * - {@link HttpModelAdapter.endpointPath} — the path under the base URL\n * - {@link HttpModelAdapter.buildBody} — normalized request to wire JSON\n * - {@link HttpModelAdapter.translate} — wire SSE events to `StreamChunk`s\n *\n * Everything else — connection snapshotting, the catalog, modality checks, the\n * request, HTTP error mapping, `retry-after`, request ids, SSE decoding, the idle\n * bound, and teardown — is shared and happens exactly once, here.\n *\n * @module ai-agent-sdk/providers/base/http-adapter\n */\n\nimport { ModelAdapter, type PreparedAdapterCall } from '@alvin0/ai-agent-sdk-core'\nimport type { GenerateOptions } from '@alvin0/ai-agent-sdk-core'\nimport type {\n ModelInfo,\n ModelModality,\n ModelReasoningInfo,\n ProviderInfo,\n ResolvedModelInfo,\n} from '@alvin0/ai-agent-sdk-core'\nimport type { ResolvedRetryPolicy } from '@alvin0/ai-agent-sdk-core'\nimport type { NativeToolName } from '@alvin0/ai-agent-sdk-core'\nimport { MODEL_ERROR_CODES, ModelError } from '@alvin0/ai-agent-sdk-core'\nimport { contentHasImage } from '@alvin0/ai-agent-sdk-core'\nimport type { StreamChunk } from '@alvin0/ai-agent-sdk-core'\nimport type { ModelInvocationContext } from '@alvin0/ai-agent-sdk-core'\nimport type {\n ProviderAttemptHandle,\n SafeErrorRecord,\n TokenUsage,\n UsageCounters,\n} from '@alvin0/ai-agent-sdk-core'\nimport { validateUsageCounters } from '@alvin0/ai-agent-sdk-core'\nimport { parseSseBounded } from '../stream/parser.ts'\nimport type { SseEvent } from '../stream/sse.ts'\nimport { DEFAULT_MAX_SSE_EVENT_CHARS, DEFAULT_MAX_SSE_EVENTS } from '../stream/config.ts'\nimport { createStreamIdleDeadline } from '../stream/idle-deadline.ts'\nimport { requireTerminalFinish } from '../stream/terminal.ts'\nimport type { ProviderProtocolChunk } from '../stream/types.ts'\nimport { HTTP_PROVIDER_ERROR_CODES } from '../common/config.ts'\nimport { normalizeHttpBoundaryError } from '../common/failure.ts'\nimport { mergeHeaderLayers } from '../common/header-layers.ts'\nimport { attributionHeaders } from '@alvin0/ai-agent-sdk-core'\nimport { httpErrorCode, parseErrorBody, requestIdFrom, retryAfterMs } from './http-errors.ts'\nimport {\n abortError,\n boundedResponseBody,\n cancelResponseBody,\n catalogModelInfo,\n endpointUrl,\n positiveFinite,\n positiveInteger,\n raceWithSignal,\n readBoundedText,\n redactHeaders,\n rejectProviderRedirect,\n resolvedCatalogModelInfo,\n requestLogId,\n safeProviderFailure,\n withAbortSignal,\n} from './transport.ts'\n\nexport { redactHeaders } from './transport.ts'\n\n/** Default idle bound: five minutes without a single byte is a hung stream. */\nexport const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000\n/** Default end-to-end bound once provider request construction begins. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 10 * 60_000\n/** Default serialized request ceiling. */\nexport const DEFAULT_MAX_REQUEST_BYTES = 32 * 1024 * 1024\n/** Default cumulative successful response-body ceiling. */\nexport const DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024\n/** Default number of raw response chunks accepted from one request. */\nexport const DEFAULT_MAX_RESPONSE_CHUNKS = 100_000\n/** Default error body retained for classification and diagnostics. */\nexport const DEFAULT_MAX_ERROR_BODY_BYTES = 1024 * 1024\n/** Default diagnostic observer deadline; logging must never gate dispatch indefinitely. */\nexport const DEFAULT_REQUEST_LOGGER_TIMEOUT_MS = 5_000\n\n/** One model a provider's configuration advertises. */\nexport interface ProviderCatalogModel {\n /** Wire model id, passed to the provider verbatim. */\n id: string\n /** Selector label; defaults to {@link id}. */\n name?: string\n /** Optional detail distinguishing similar variants. */\n description?: string\n /** Combined request/response capacity, when known. */\n contextWindow?: number\n /** Per-request output cap for this model. */\n maxTokens?: number\n /** Accepted request modalities; omission is treated as text-only. */\n inputModalities?: readonly ModelModality[]\n /** Modalities this model route may return. */\n outputModalities?: readonly ModelModality[]\n /** Provider-native tools explicitly supported; omission means unknown. */\n nativeTools?: readonly NativeToolName[]\n /** Reasoning levels this model offers, when any. */\n reasoning?: ModelReasoningInfo\n}\n\n/**\n * Everything needed to issue ONE request, captured as a single snapshot.\n *\n * The snapshot exists to close a specific gap: if the endpoint and the credential\n * were read separately, a configuration change between the two reads would send\n * one generation's secret to another generation's URL. Reading them together, once\n * per call, makes that impossible.\n */\nexport interface HttpConnection {\n /** Endpoint base; the provider's {@link HttpModelAdapter.endpointPath} is appended. */\n readonly baseUrl: string\n /**\n * Every header for the request, INCLUDING authorization.\n *\n * Resolved in `connect()` so the credential travels with the endpoint it will\n * be sent to. The base pipeline adds attribution and `accept` on top.\n */\n readonly headers: Readonly<Record<string, string>>\n /** Auth-produced names that must be redacted regardless of spelling. */\n readonly sensitiveHeaderNames?: readonly string[]\n /** Maximum idle interval while a read is outstanding. */\n readonly streamIdleTimeoutMs: number\n /** End-to-end request/stream timeout. */\n readonly requestTimeoutMs?: number\n /** Maximum serialized outbound request bytes. */\n readonly maxRequestBytes?: number\n /** Maximum cumulative successful response bytes. */\n readonly maxResponseBytes?: number\n /** Maximum raw chunks accepted from a successful response. */\n readonly maxResponseChunks?: number\n /** Maximum decoded SSE events accepted from one response. */\n readonly maxSseEvents?: number\n /** Maximum characters accepted in one decoded SSE event. */\n readonly maxSseEventChars?: number\n /** Maximum bytes read from a non-success response. */\n readonly maxErrorBodyBytes?: number\n /** Maximum time granted to the optional request logger. */\n readonly requestLoggerTimeoutMs?: number\n /** Permit cleartext HTTP explicitly, for trusted local development endpoints only. */\n readonly allowInsecureHttp?: boolean\n /** Captured fetch implementation; omission uses the platform global. */\n readonly fetch?: typeof globalThis.fetch\n /** Retry policy this route owns. */\n readonly retryPolicy: ResolvedRetryPolicy\n /** Advisory catalog; requests are never restricted to it. */\n readonly models: readonly ProviderCatalogModel[]\n /** Output cap applied when neither the caller nor the model entry names one. */\n readonly defaultMaxTokens: number\n /** Context capacity used when the selected model has no exact value. */\n readonly defaultContextWindow: number\n}\n\n/** What {@link HttpModelAdapter.buildBody} and `translate` receive. */\nexport interface ProviderRequest {\n /** The normalized request, with registry-resolved defaults already applied. */\n readonly options: GenerateOptions\n /** Exact model metadata for this call. */\n readonly model: ResolvedModelInfo\n /** The connection snapshot this call is bound to. */\n readonly connection: HttpConnection\n /** Output cap to send; always resolved to a number, which some APIs require. */\n readonly maxTokens: number\n}\n\n/**\n * One exact wire request observed immediately before the shared pipeline calls `fetch`.\n * @deprecated High-risk compatibility diagnostics; prefer structured observation.\n */\nexport interface ProviderRequestLogRecord {\n /** Version of this durable/debug record shape. */\n readonly schemaVersion: 1\n readonly type: 'provider-request'\n /** Locally generated correlation id; providers may assign a different id later. */\n readonly id: string\n readonly timestamp: string\n readonly provider: string\n readonly model: string\n readonly method: 'POST'\n readonly url: string\n /** Request headers with credentials and cookies replaced by `[REDACTED]`. */\n readonly headers: Readonly<Record<string, string>>\n /** Exact protocol-serialized JSON body. This may contain prompts and tool output. */\n readonly body: unknown\n readonly bodyBytes: number\n}\n\n/**\n * Optional observer for exact provider-wire requests.\n * @deprecated High-risk compatibility diagnostics; prefer structured observation.\n */\nexport type ProviderRequestLogger = (\n record: ProviderRequestLogRecord,\n) => Promise<void> | void\n\ninterface PreparedWireBody {\n readonly value: unknown\n readonly encoded: string\n readonly bytes: number\n}\n\ninterface PreparedWireBodyCache {\n prepared?: Promise<PreparedWireBody>\n}\n\n/** Base for every HTTP provider adapter in this package. */\nexport abstract class HttpModelAdapter extends ModelAdapter {\n /** Human-readable provider name reported by {@link providerInfo}. */\n protected abstract readonly displayName: string\n\n /**\n * Capture the connection facts for one operation.\n *\n * Called once per operation and never re-read mid-request. Resolve the\n * credential here, together with the endpoint.\n * @param provider - the route being served.\n * @param signal - cancellation for any I/O this resolution performs.\n */\n protected abstract connect(\n provider: string,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<HttpConnection>\n\n /** Path appended to {@link HttpConnection.baseUrl}, e.g. `/v1/messages`. */\n protected abstract endpointPath(request: ProviderRequest): string\n\n /** Convert the normalized request into this provider's wire JSON. */\n protected abstract buildBody(request: ProviderRequest): Promise<unknown> | unknown\n\n /**\n * Convert this provider's SSE events into the SDK's chunk protocol.\n *\n * Owns termination: this generator decides what ends the stream (a `[DONE]`\n * sentinel, a named terminal event, or end of body) and must raise\n * `STREAM_CLOSED` when the body ends before the provider said it was finished.\n */\n protected abstract translate(\n events: AsyncIterable<SseEvent>,\n request: ProviderRequest,\n ): AsyncGenerator<ProviderProtocolChunk>\n\n /**\n * Extra headers merged in by the base pipeline. Override to change `accept`.\n * @returns headers applied beneath {@link HttpConnection.headers}.\n */\n protected baseHeaders(): Record<string, string> {\n return {\n 'content-type': 'application/json',\n 'accept': 'text/event-stream',\n }\n }\n\n /**\n * Observe an exact, credential-redacted wire request before dispatch.\n *\n * The default is a no-op so library users do not silently persist prompts.\n * Implementations should treat this as diagnostics, not a dispatch veto.\n * @deprecated High-risk compatibility diagnostics; prefer structured observation.\n */\n protected observeRequest(_record: ProviderRequestLogRecord): Promise<void> | void {}\n\n /**\n * Map a non-2xx response to a stable code. Override only to add codes this\n * provider reports that the shared mapping cannot infer from the status.\n */\n protected providerErrorCode(status: number, detail: string): string {\n return httpErrorCode(status, detail)\n }\n\n override providerInfo(provider: string): ProviderInfo {\n return { id: provider, name: this.displayName }\n }\n\n override async listModels(provider: string, signal?: AbortSignal): Promise<readonly ModelInfo[]> {\n const connection = this.captureConnection(await this.connect(provider, signal))\n return connection.models.map(model => catalogModelInfo(provider, model))\n }\n\n override async resolveModel(\n provider: string,\n model: string,\n signal?: AbortSignal,\n ): Promise<ResolvedModelInfo> {\n const connection = this.captureConnection(await this.connect(provider, signal))\n return this.decorateModel(this.modelInfoFor(connection, provider, model), connection)\n }\n\n override async prepareCall(\n provider: string,\n model: string,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<PreparedAdapterCall> {\n context?.declareProviderAttemptAccounting?.()\n // Snapshot once, then bind both the capability answer and the eventual\n // dispatch to it, so the two cannot come from different generations.\n const connection = this.captureConnection(await this.connect(provider, signal, context))\n const info = this.decorateModel(this.modelInfoFor(connection, provider, model), connection)\n const wireBody: PreparedWireBodyCache = {}\n return {\n model: info,\n stream: (options, invocation = context) => this.run(\n options,\n connection,\n info,\n invocation,\n wireBody,\n ),\n }\n }\n\n /**\n * Stream one model call.\n *\n * Intentionally NOT an extension point — see the module note. Providers\n * customize behaviour through the abstract members instead.\n */\n stream(options: GenerateOptions, context?: ModelInvocationContext): AsyncIterable<StreamChunk> {\n return this.runResolving(options, context)\n }\n\n /** Resolve a connection first, for the un-prepared entry point. */\n private async * runResolving(options: GenerateOptions, context?: ModelInvocationContext): AsyncGenerator<StreamChunk> {\n context?.declareProviderAttemptAccounting?.()\n const connection = this.captureConnection(\n await this.connect(options.provider, options.signal, context),\n )\n const info = this.decorateModel(\n this.modelInfoFor(connection, options.provider, options.model),\n connection,\n )\n yield* this.run(options, connection, info, context, {})\n }\n\n /** Resolve exact-model metadata from the catalog, falling back to config defaults. */\n protected modelInfoFor(\n connection: HttpConnection,\n provider: string,\n model: string,\n ): ResolvedModelInfo {\n return resolvedCatalogModelInfo(\n provider, model, connection.models,\n connection.defaultMaxTokens, connection.defaultContextWindow,\n )\n }\n\n /** Decorate resolved metadata without reopening the captured connection generation. */\n protected decorateModel(\n info: ResolvedModelInfo,\n _connection: HttpConnection,\n ): ResolvedModelInfo {\n return info\n }\n\n /** Capture legacy subclass transport/auth layers once; configured adapters already return all five. */\n private captureConnection(connection: HttpConnection): HttpConnection {\n const transport = this.baseHeaders()\n if (Reflect.ownKeys(transport).length === 0) return connection\n const merged = mergeHeaderLayers([\n { layer: 'transport', headers: transport },\n { layer: 'sdk-attribution', headers: attributionHeaders() },\n { layer: 'auth', headers: connection.headers },\n ])\n return Object.freeze({\n ...connection,\n headers: merged.headers,\n sensitiveHeaderNames: Object.freeze([\n ...new Set([...(connection.sensitiveHeaderNames ?? []), ...merged.sensitiveHeaderNames]),\n ]),\n })\n }\n\n /**\n * The shared pipeline: guard, build, send, classify, decode, bound, translate.\n */\n private async * run(\n options: GenerateOptions,\n connection: HttpConnection,\n model: ResolvedModelInfo,\n context?: ModelInvocationContext,\n wireBodyCache: PreparedWireBodyCache = {},\n ): AsyncGenerator<StreamChunk> {\n context?.declareProviderAttemptAccounting?.()\n if (options.messages.some(message => contentHasImage(message.content))\n && model.inputModalities?.includes('image') !== true) {\n throw new ModelError(\n `${this.displayName} model \"${options.model}\" does not accept image input`,\n MODEL_ERROR_CODES.UNSUPPORTED_CONTENT,\n )\n }\n\n const request: ProviderRequest = {\n options,\n model,\n connection,\n maxTokens: options.maxTokens ?? model.defaultMaxTokens ?? connection.defaultMaxTokens,\n }\n\n // One controller for our own teardown, fused with the caller's. Aborting ours\n // in `finally` is what tears down an in-flight response when the consumer\n // stops reading early, instead of leaking the connection.\n const consumer = new AbortController()\n const requestTimeoutMs = positiveFinite(\n connection.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs',\n )\n const timeout = AbortSignal.timeout(requestTimeoutMs)\n const signal = AbortSignal.any([\n consumer.signal,\n timeout,\n ...options.signal === undefined ? [] : [options.signal],\n ])\n const maxRequestBytes = positiveInteger(\n connection.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES,\n 'maxRequestBytes',\n )\n const maxResponseBytes = positiveInteger(\n connection.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,\n 'maxResponseBytes',\n )\n const maxResponseChunks = positiveInteger(\n connection.maxResponseChunks ?? DEFAULT_MAX_RESPONSE_CHUNKS,\n 'maxResponseChunks',\n )\n const maxSseEvents = positiveInteger(\n connection.maxSseEvents ?? DEFAULT_MAX_SSE_EVENTS,\n 'maxSseEvents',\n )\n const maxSseEventChars = positiveInteger(\n connection.maxSseEventChars ?? DEFAULT_MAX_SSE_EVENT_CHARS,\n 'maxSseEventChars',\n )\n const maxErrorBodyBytes = positiveInteger(\n connection.maxErrorBodyBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES,\n 'maxErrorBodyBytes',\n )\n const requestLoggerTimeoutMs = positiveFinite(\n connection.requestLoggerTimeoutMs ?? DEFAULT_REQUEST_LOGGER_TIMEOUT_MS,\n 'requestLoggerTimeoutMs',\n )\n\n let admissionFailure: { readonly value: unknown } | undefined\n let ownedResponse: Response | undefined\n try {\n signal.throwIfAborted()\n const preparedBody = await (wireBodyCache.prepared ??= this.prepareWireBody(\n request,\n maxRequestBytes,\n signal,\n ))\n const wireBody = preparedBody.value\n const body = preparedBody.encoded\n const bodyBytes = preparedBody.bytes\n const endpoint = endpointUrl(\n connection.baseUrl,\n this.endpointPath(request),\n connection.allowInsecureHttp ?? false,\n )\n const url = endpoint.href\n const origin = endpoint.origin\n const headers = connection.headers\n\n // Logging is deliberately best-effort. A full disk or broken debug sink\n // must not turn a valid provider request into an application outage.\n try {\n const loggerSignal = AbortSignal.any([signal, AbortSignal.timeout(requestLoggerTimeoutMs)])\n await raceWithSignal(Promise.resolve(this.observeRequest({\n schemaVersion: 1,\n type: 'provider-request',\n id: requestLogId(),\n timestamp: new Date().toISOString(),\n provider: options.provider,\n model: options.model,\n method: 'POST',\n url,\n headers: redactHeaders(headers, connection.sensitiveHeaderNames),\n body: wireBody,\n bodyBytes,\n })), loggerSignal)\n } catch {\n // Contained by contract; see `observeRequest` above.\n }\n\n let attempt: ProviderAttemptHandle | undefined\n let dispatchState: 'not-sent' | 'sent' | 'unknown' = 'not-sent'\n let httpStatus: number | undefined\n let providerRequestId: string | undefined\n let attemptStatus: 'success' | 'error' | 'aborted' | 'unknown' = 'unknown'\n let attemptUsage: UsageCounters | undefined\n let attemptError: SafeErrorRecord | undefined\n try {\n signal.throwIfAborted()\n try {\n attempt = await context?.startProviderAttempt?.({\n provider: options.provider,\n model: options.model,\n method: 'POST',\n origin,\n }, signal)\n } catch (error: unknown) {\n admissionFailure = { value: error }\n throw error\n }\n signal.throwIfAborted()\n dispatchState = 'unknown'\n const fetchImplementation = connection.fetch ?? globalThis.fetch\n const pendingResponse = fetchImplementation(url, {\n method: 'POST',\n headers,\n body,\n signal,\n redirect: 'manual',\n })\n // Retain cleanup ownership even if an injected fetch ignores abort.\n void pendingResponse.then(response => {\n if (signal.aborted) return cancelResponseBody(response)\n return undefined\n }, () => undefined)\n const response = await raceWithSignal(pendingResponse, signal)\n ownedResponse = response\n signal.throwIfAborted()\n dispatchState = 'sent'\n httpStatus = response.status\n providerRequestId = requestIdFrom(response.headers)\n await rejectProviderRedirect(response, url)\n\n if (!response.ok) throw await this.httpFailure(response, origin, maxErrorBodyBytes, signal)\n const mediaType = response.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase()\n if (mediaType !== 'text/event-stream') {\n throw new ModelError(\n `${this.displayName} response is not text/event-stream`,\n HTTP_PROVIDER_ERROR_CODES.STREAM_MEDIA_TYPE_INVALID,\n )\n }\n if (response.body === null) {\n throw new ModelError(\n `${this.displayName} returned no response body`,\n MODEL_ERROR_CODES.STREAM_CLOSED,\n )\n }\n\n const declaredLength = response.headers.get('content-length')\n if (declaredLength !== null && /^\\d+$/.test(declaredLength)\n && Number(declaredLength) > maxResponseBytes) {\n throw new ModelError(\n `${this.displayName} response exceeds the ${maxResponseBytes}-byte limit`,\n MODEL_ERROR_CODES.TRANSPORT,\n )\n }\n const idleDeadline = createStreamIdleDeadline(\n connection.streamIdleTimeoutMs,\n this.displayName,\n 30_000,\n )\n const events = parseSseBounded(boundedResponseBody(\n response.body,\n maxResponseBytes,\n maxResponseChunks,\n this.displayName,\n signal,\n ), idleDeadline.activity, 30_000, {\n maxEvents: maxSseEvents,\n maxEventChars: maxSseEventChars,\n })\n const translated = requireTerminalFinish(this.translate(events, request), this.displayName)\n for await (const chunk of withAbortSignal(idleDeadline.guard(translated), signal)) {\n if (chunk.type === 'usage') {\n attemptUsage = chunk.usage\n const validated = validateUsageCounters(chunk.usage, true)\n // Partial and malformed reports remain provider-attempt evidence but\n // never escape as the SDK's exact TokenUsage contract.\n if (!validated.complete) continue\n yield { type: 'usage', usage: validated.reported as TokenUsage }\n continue\n }\n if (chunk.type === 'finish') {\n attemptStatus = chunk.reason.kind === 'aborted' ? 'aborted'\n : chunk.reason.kind === 'error' ? 'error' : 'success'\n if (chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted') {\n attemptError = safeProviderFailure(chunk.reason.failure)\n }\n }\n yield chunk\n }\n } catch (error: unknown) {\n if (admissionFailure !== undefined && error === admissionFailure.value) throw error\n const mapped = timeout.aborted && options.signal?.aborted !== true\n ? new ModelError(\n `${this.displayName} request exceeded its ${requestTimeoutMs}ms time limit`,\n MODEL_ERROR_CODES.TIMEOUT,\n { cause: error },\n )\n : signal.aborted\n ? abortError(this.displayName, error)\n : normalizeHttpBoundaryError(\n error,\n `${this.displayName} request to ${origin} failed`,\n )\n attemptStatus = mapped.code === MODEL_ERROR_CODES.ABORTED ? 'aborted' : 'error'\n attemptError = safeProviderFailure(mapped.failure)\n throw mapped\n } finally {\n attempt?.end({\n status: attemptStatus,\n dispatchState,\n ...attemptUsage === undefined ? {} : { reported: attemptUsage },\n ...httpStatus === undefined ? {} : { httpStatus },\n ...providerRequestId === undefined ? {} : { providerRequestId },\n ...attemptError === undefined ? {} : { error: attemptError },\n })\n }\n } catch (error: unknown) {\n if (options.signal?.aborted === true) throw abortError(this.displayName, error)\n if (timeout.aborted) {\n throw new ModelError(\n `${this.displayName} request exceeded its ${requestTimeoutMs}ms time limit`,\n MODEL_ERROR_CODES.TIMEOUT,\n { cause: error },\n )\n }\n if (admissionFailure !== undefined && error === admissionFailure.value) throw error\n throw normalizeHttpBoundaryError(error, `${this.displayName} stream failed`)\n } finally {\n consumer.abort(new Error(`${this.displayName} stream consumer stopped`))\n if (ownedResponse !== undefined) await cancelResponseBody(ownedResponse)\n }\n }\n\n private async prepareWireBody(\n request: ProviderRequest,\n maxRequestBytes: number,\n signal: AbortSignal,\n ): Promise<PreparedWireBody> {\n signal.throwIfAborted()\n const value = await raceWithSignal(Promise.resolve(this.buildBody(request)), signal)\n const encoded = JSON.stringify(value)\n const bytes = new TextEncoder().encode(encoded).byteLength\n if (bytes > maxRequestBytes) {\n throw new ModelError(\n `${this.displayName} request exceeds the ${maxRequestBytes}-byte limit`,\n MODEL_ERROR_CODES.INVALID_REQUEST,\n )\n }\n return Object.freeze({ value, encoded, bytes })\n }\n\n /** Turn a non-2xx response into a fully populated {@link ModelError}. */\n private async httpFailure(\n response: Response,\n url: string,\n maxBytes: number,\n signal: AbortSignal,\n ): Promise<ModelError> {\n let raw = ''\n try {\n raw = await readBoundedText(response, maxBytes, signal)\n } catch {\n // A truncated error body must not replace the status, which is the more\n // reliable signal anyway.\n }\n const { message, detail } = parseErrorBody(raw)\n const delay = retryAfterMs(response.headers.get('retry-after'))\n const id = requestIdFrom(response.headers)\n return new ModelError(\n message ?? `${this.displayName} error (HTTP ${response.status}) from ${url}`,\n this.providerErrorCode(response.status, detail),\n {\n cause: new Error(raw.length > 0 ? raw : `HTTP ${response.status}`),\n status: response.status,\n ...delay === undefined ? {} : { providerRetryAfterMs: delay },\n ...id === undefined ? {} : { requestId: id },\n },\n )\n }\n}\n","const ENCODER = new TextEncoder()\n\n/** Read an own data property without evaluating accessors or inherited state. */\nexport function ownData(\n source: object,\n key: PropertyKey,\n required = true,\n): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)\n if (descriptor === undefined) {\n if (!required) return undefined\n throw new TypeError(`Missing ${String(key)}`)\n }\n if (!('value' in descriptor)) throw new TypeError(`${String(key)} must not be an accessor`)\n return descriptor.value\n}\n\n/** Require a plain configuration object. */\nexport function plainObject(value: unknown, label: string): Record<PropertyKey, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(`${label} must be a plain object`)\n }\n return value as Record<PropertyKey, unknown>\n}\n\n/** Capture a method once while retaining its original receiver. */\nexport function capturedMethod<Args extends readonly unknown[], Result>(\n source: object,\n key: PropertyKey,\n): (...args: Args) => Result {\n const value = ownData(source, key)\n if (typeof value !== 'function') throw new TypeError(`${String(key)} must be a function`)\n return (...args: Args) => Reflect.apply(value, source, args) as Result\n}\n\n/** Capture an optional method once while retaining its original receiver. */\nexport function optionalCapturedMethod<Args extends readonly unknown[], Result>(\n source: object,\n key: PropertyKey,\n): ((...args: Args) => Result) | undefined {\n const value = ownData(source, key, false)\n if (value === undefined) return undefined\n if (typeof value !== 'function') throw new TypeError(`${String(key)} must be a function`)\n return (...args: Args) => Reflect.apply(value, source, args) as Result\n}\n\n/** Validate one bounded non-empty UTF-8 identifier. */\nexport function boundedIdentifier(value: unknown, maxBytes: number, label: string): string {\n if (typeof value !== 'string' || value.length === 0 || value.trim() !== value\n || ENCODER.encode(value).byteLength > maxBytes) {\n throw new TypeError(`${label} must be a bounded non-empty string`)\n }\n return value\n}\n","export interface JsonObjectSnapshotLimits {\n readonly maxObjectFields: number\n readonly maxArrayItems: number\n readonly maxDepth: number\n readonly maxNodes: number\n readonly maxKeyBytes: number\n readonly maxBytes: number\n}\n\n/** Clone bounded JSON data without invoking accessors, prototypes, or serialization hooks. */\nexport function snapshotJsonObject(\n value: unknown,\n limits: JsonObjectSnapshotLimits,\n): Readonly<Record<string, unknown>> {\n let nodes = 0\n const seen = new Set<object>()\n const encoder = new TextEncoder()\n\n const clone = (input: unknown, depth: number): unknown => {\n nodes++\n if (nodes > limits.maxNodes || depth > limits.maxDepth) {\n throw new TypeError('JSON data exceeds its structural bound')\n }\n if (input === null || typeof input === 'boolean' || typeof input === 'string') return input\n if (typeof input === 'number') {\n if (!Number.isFinite(input)) throw new TypeError('JSON number must be finite')\n return input\n }\n if (Array.isArray(input)) return cloneArray(input, depth)\n if (input === null || typeof input !== 'object') {\n throw new TypeError('JSON data contains an unsupported value')\n }\n return cloneRecord(input, depth)\n }\n\n const cloneArray = (source: readonly unknown[], depth: number): readonly unknown[] => {\n if (seen.has(source)) throw new TypeError('JSON data is cyclic')\n const length = ownValue(source, 'length')\n if (!Number.isSafeInteger(length) || Number(length) < 0 || Number(length) > limits.maxArrayItems) {\n throw new TypeError('JSON array exceeds its item bound')\n }\n seen.add(source)\n try {\n const result: unknown[] = []\n for (let index = 0; index < Number(length); index++) {\n result.push(clone(ownValue(source, String(index)), depth + 1))\n }\n return Object.freeze(result)\n } finally {\n seen.delete(source)\n }\n }\n\n const cloneRecord = (source: object, depth: number): Readonly<Record<string, unknown>> => {\n const prototype = Object.getPrototypeOf(source)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError('JSON object must be plain')\n }\n if (seen.has(source)) throw new TypeError('JSON data is cyclic')\n const keys = Reflect.ownKeys(source)\n if (keys.some(key => typeof key !== 'string') || keys.length > limits.maxObjectFields) {\n throw new TypeError('JSON object exceeds its field bound')\n }\n seen.add(source)\n try {\n const result: Record<string, unknown> = Object.create(null) as Record<string, unknown>\n for (const key of keys as string[]) {\n if (encoder.encode(key).byteLength > limits.maxKeyBytes) {\n throw new TypeError('JSON object key exceeds its byte bound')\n }\n result[key] = clone(ownValue(source, key), depth + 1)\n }\n return Object.freeze(result)\n } finally {\n seen.delete(source)\n }\n }\n\n const snapshot = clone(value, 0)\n if (snapshot === null || Array.isArray(snapshot) || typeof snapshot !== 'object') {\n throw new TypeError('Expected a JSON object')\n }\n if (encoder.encode(JSON.stringify(snapshot)).byteLength > limits.maxBytes) {\n throw new TypeError('JSON data exceeds its byte bound')\n }\n return snapshot as Readonly<Record<string, unknown>>\n}\n\nfunction ownValue(source: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)\n if (descriptor === undefined) throw new TypeError('JSON arrays must not be sparse')\n if (!('value' in descriptor)) throw new TypeError('JSON data must not use accessors')\n return descriptor.value\n}\n","import {\n boundedIdentifier,\n capturedMethod,\n optionalCapturedMethod,\n ownData,\n plainObject,\n} from '../common/data.ts'\nimport { snapshotJsonObject } from '../common/json-snapshot.ts'\nimport { HTTP_PROTOCOL_API_VERSION, HTTP_PROTOCOL_LIMITS } from './config.ts'\nimport type {\n ProtocolRequest,\n ProtocolSseEvent,\n ProtocolStreamChunk,\n RuntimeWireProtocol,\n WireProtocolDefinition,\n} from './runtime-types.ts'\n\n/**\n * Stamp a protocol definition without allocating transport state or performing I/O.\n * All executable properties are captured once and retain the author's receiver.\n */\nexport function defineWireProtocol<Dialect extends object>(\n definition: WireProtocolDefinition<Dialect>,\n): RuntimeWireProtocol<Dialect> {\n const source = plainObject(definition, 'wire protocol definition')\n const id = boundedIdentifier(ownData(source, 'id'), HTTP_PROTOCOL_LIMITS.idBytes, 'protocol id')\n const defaultDialect = snapshotJsonObject(ownData(source, 'defaultDialect'), {\n maxDepth: HTTP_PROTOCOL_LIMITS.dialectDepth,\n maxNodes: HTTP_PROTOCOL_LIMITS.dialectNodes,\n maxObjectFields: HTTP_PROTOCOL_LIMITS.dialectObjectFields,\n maxArrayItems: HTTP_PROTOCOL_LIMITS.dialectArrayItems,\n maxKeyBytes: HTTP_PROTOCOL_LIMITS.dialectKeyBytes,\n maxBytes: HTTP_PROTOCOL_LIMITS.dialectBytes,\n }) as Dialect\n const endpointPath = capturedMethod<[ProtocolRequest, Dialect], string>(source, 'endpointPath')\n const protocolHeaders = optionalCapturedMethod<[Dialect], Readonly<Record<string, string>>>(\n source,\n 'protocolHeaders',\n )\n const serialize = capturedMethod<\n [ProtocolRequest, Dialect], Readonly<Record<string, unknown>>\n >(source, 'serialize')\n const translate = capturedMethod<\n [AsyncIterable<ProtocolSseEvent>, ProtocolRequest, string],\n AsyncGenerator<ProtocolStreamChunk>\n >(source, 'translate')\n\n return Object.freeze({\n kind: 'http-wire-protocol' as const,\n apiVersion: HTTP_PROTOCOL_API_VERSION,\n id,\n defaultDialect,\n endpointPath,\n ...(protocolHeaders === undefined ? {} : { protocolHeaders }),\n serialize,\n translate,\n })\n}\n","/**\n * A wire protocol, separated from the endpoint that speaks it.\n *\n * This split is what makes adding a provider cheap. \"Which JSON shapes and SSE\n * events\" is a PROTOCOL concern; \"which URL, which credential, which models\" is an\n * ENDPOINT concern. Dozens of endpoints speak the protocols this package\n * implements, so an endpoint that speaks one should be expressible as data rather\n * than as another adapter class.\n *\n * A protocol object owns no endpoint, no credential, and no state. It is a pure\n * translation pair plus the small amount of metadata the pipeline needs.\n *\n * @module ai-agent-sdk/providers/protocols/protocol\n */\n\nimport type { SseEvent } from '../stream/sse.ts'\nimport type { ProviderRequest } from '../base/http-adapter.ts'\nimport type { ProviderProtocolChunk } from '../stream/types.ts'\n\nexport { HTTP_PROTOCOL_API_VERSION, HTTP_PROVIDER_ERROR_CODES } from './config.ts'\nexport { defineWireProtocol } from './definition.ts'\nexport type {\n HttpAuthResolveOptions,\n ProtocolRequest,\n ProtocolSseEvent,\n ProtocolStreamChunk,\n RuntimeWireProtocol,\n WireProtocolDefinition,\n} from './runtime-types.ts'\n\n/** A protocol may report partial/untrusted usage before transport validation. */\nexport type WireProtocolChunk = ProviderProtocolChunk\n\n/**\n * One wire protocol.\n *\n * `Dialect` is the protocol's own knob record — the per-endpoint variations that\n * change which optional fields are sent without changing any behaviour. Keeping it\n * a type parameter means an endpoint can override exactly the knobs its protocol\n * defines and nothing else.\n */\nexport interface WireProtocol<Dialect> {\n /** Stable identifier, used in diagnostics and to name the protocol in config. */\n readonly id: string\n\n /**\n * Knob defaults.\n *\n * An endpoint supplies a partial override, so a new knob can be added to a\n * protocol without touching any endpoint that does not care about it.\n */\n readonly defaultDialect: Dialect\n\n /** Path appended to the endpoint's base URL. */\n endpointPath(request: ProviderRequest, dialect: Dialect): string\n\n /**\n * Headers the PROTOCOL requires, as opposed to the ones authentication supplies.\n *\n * `anthropic-version` is the motivating case: it is mandatory on every request\n * to that API regardless of which endpoint or credential is used, so it belongs\n * to the protocol rather than being copied into each endpoint's config.\n */\n protocolHeaders?(dialect: Dialect): Record<string, string>\n\n /** Normalized request to this protocol's wire JSON. */\n serialize(request: ProviderRequest, dialect: Dialect): unknown | Promise<unknown>\n\n /**\n * This protocol's SSE events to the SDK's chunk protocol.\n *\n * Owns termination: it decides what ends the stream and must raise\n * `STREAM_CLOSED` when the body ends before the provider said it was finished.\n */\n translate(\n events: AsyncIterable<SseEvent>,\n request: ProviderRequest,\n displayName: string,\n ): AsyncGenerator<WireProtocolChunk>\n}\n\n/** Any protocol, when the dialect type does not matter to the holder. */\nexport type AnyWireProtocol = WireProtocol<never>\n\n/**\n * Merge an endpoint's partial dialect over a protocol's defaults.\n *\n * `undefined` entries are dropped rather than applied, so an override object built\n * with optional fields cannot accidentally erase a default.\n * @param protocol - the protocol supplying defaults.\n * @param overrides - the endpoint's partial override.\n * @returns the effective, frozen dialect.\n */\nexport function resolveDialect<Dialect extends object>(\n protocol: WireProtocol<Dialect>,\n overrides: Partial<Dialect> | undefined,\n): Dialect {\n if (overrides === undefined) return protocol.defaultDialect\n const applied = Object.fromEntries(\n Object.entries(overrides).filter(([, value]) => value !== undefined),\n ) as Partial<Dialect>\n return Object.freeze({ ...protocol.defaultDialect, ...applied })\n}\n","import {\n createOperationId,\n isSpanId,\n isTraceId,\n safeErrorRecord,\n type CorrelationContext,\n type JsonObject,\n type ModelInvocationContext,\n type ObservationEvent,\n type ObservationEventName,\n type ObservationSpanName,\n} from '@alvin0/ai-agent-sdk-core'\n\ninterface ProviderOperationInput {\n readonly name: Extract<ObservationEventName, 'sdk.credential.operation' | 'sdk.integration.request'>\n readonly spanName: Extract<ObservationSpanName, 'sdk.credential.operation' | 'sdk.integration.request'>\n readonly data: JsonObject\n readonly failureMessage: string\n}\n\nconst SAFE_OPERATION_ERROR_TYPES = new Set([\n 'AbortError',\n 'AgentSdkError',\n 'CodexRefreshError',\n 'Error',\n 'ModelError',\n 'RangeError',\n 'TypeError',\n])\n\nconst SAFE_OPERATION_ERROR_CODES = new Set([\n 'ABORTED',\n 'CODEX_AUTH_FAILED',\n 'CODEX_AUTH_MALFORMED',\n 'CODEX_REAUTH_REQUIRED',\n 'CODEX_REFRESH_TRANSIENT',\n 'INVALID_CREDENTIAL',\n 'MISSING_CREDENTIAL',\n 'TIMEOUT',\n])\n\n/** Observe one nested provider operation without exposing its sensitive values. */\nasync function observeProviderOperation<T>(\n context: ModelInvocationContext | undefined,\n input: ProviderOperationInput,\n task: () => Promise<T>,\n): Promise<T> {\n const port = context?.observation\n const parent = context?.correlation\n const resource = context?.resource\n const scope = context?.scope\n if (port === undefined || parent?.runId === undefined || resource === undefined || scope === undefined\n || !isTraceId(parent.traceId) || !isSpanId(parent.spanId)\n || (parent.parentSpanId !== null && !isSpanId(parent.parentSpanId))) {\n return await task()\n }\n const correlationParent = parent as CorrelationContext\n\n const startedAt = new Date().toISOString()\n let correlation: CorrelationContext = correlationParent\n let span: ReturnType<typeof port.openSpan> | undefined\n try {\n span = port.openSpan({\n name: input.spanName,\n runId: parent.runId,\n parent: correlationParent,\n startedAt,\n monotonicMs: scope.monotonicMs(),\n })\n correlation = span.correlation\n } catch { /* provider work must not fail because an observer is broken */ }\n\n const capture = (phase: 'start' | 'end', data: JsonObject): void => {\n const event: ObservationEvent = {\n schemaVersion: 1,\n eventId: createOperationId(),\n sequence: scope.nextSequence(),\n name: input.name,\n phase,\n occurredAt: new Date().toISOString(),\n monotonicMs: scope.monotonicMs(),\n priority: 'critical',\n resource,\n correlation,\n data,\n }\n try { port.capture(event) } catch { /* contained; terminal call accounting remains authoritative */ }\n }\n\n capture('start', input.data)\n try {\n const result = await task()\n const endedAt = new Date().toISOString()\n try { span?.end('success', endedAt, scope.monotonicMs()) } catch { /* contained */ }\n capture('end', { ...input.data, status: 'success' })\n return result\n } catch (error) {\n const endedAt = new Date().toISOString()\n try { span?.end('error', endedAt, scope.monotonicMs()) } catch { /* contained */ }\n const safe = safeErrorRecord(error)\n const type = SAFE_OPERATION_ERROR_TYPES.has(safe.type) ? safe.type : 'Error'\n capture('end', {\n ...input.data,\n status: 'error',\n error: {\n type,\n message: input.failureMessage,\n ...safe.code !== undefined && SAFE_OPERATION_ERROR_CODES.has(safe.code)\n ? { code: safe.code }\n : {},\n ...safe.status === undefined ? {} : { status: safe.status },\n ...safe.retryable === undefined ? {} : { retryable: safe.retryable },\n },\n })\n throw error\n }\n}\n\nexport function observeCredentialOperation<T>(\n context: ModelInvocationContext | undefined,\n provider: string,\n operation: 'resolve' | 'refresh' | 'login',\n task: () => Promise<T>,\n): Promise<T> {\n return observeProviderOperation(context, {\n name: 'sdk.credential.operation',\n spanName: 'sdk.credential.operation',\n data: { provider, operation },\n failureMessage: 'credential operation failed',\n }, task)\n}\n\nexport function observeModelCatalogOperation<T>(\n context: ModelInvocationContext | undefined,\n provider: string,\n origin: string,\n task: () => Promise<T>,\n): Promise<T> {\n return observeProviderOperation(context, {\n name: 'sdk.integration.request',\n spanName: 'sdk.integration.request',\n data: { integration: 'model-catalog', provider, operation: 'discover', origin },\n failureMessage: 'model catalog operation failed',\n }, task)\n}\n","/**\n * Build a provider from CONFIGURATION instead of from a subclass.\n *\n * This is the path most endpoints should take. Adding an endpoint that speaks a\n * protocol this package already implements — an OpenAI-compatible gateway, a\n * self-hosted server, a proxy, a regional deployment — should not require another\n * adapter class, another folder, or an edit to this package's build config. It\n * requires a config object:\n *\n * ```ts\n * const openrouter = createHttpProvider({\n * displayName: 'OpenRouter',\n * protocol: openAiResponsesProtocol,\n * baseUrl: 'https://openrouter.ai/api/v1',\n * auth: { kind: 'bearer', token: () => credentialStore.read('openrouter') },\n * })\n * registry.registerAdapter(['openrouter'], openrouter)\n * ```\n *\n * Subclass {@link HttpModelAdapter} directly only when the endpoint's connection\n * facts cannot be expressed as data — request signing that depends on the request\n * body (AWS SigV4), or a credential exchange with its own state machine. Note that\n * OAuth is NOT such a case: `auth: { kind: 'dynamic' }` resolves headers per\n * operation, which is enough for a token that refreshes.\n *\n * @module ai-agent-sdk/providers/http-provider\n */\n\nimport type {\n ModelCatalogOptions,\n ModelCatalogSnapshot,\n ModelInfo,\n ModelInvocationContext,\n ResolvedModelInfo,\n} from '@alvin0/ai-agent-sdk-core'\nimport { resolveRetryPolicy, type RetryPolicyConfig } from '@alvin0/ai-agent-sdk-core'\nimport type { ResolvedRetryPolicy } from '@alvin0/ai-agent-sdk-core'\nimport { assertUsableApiKey } from '@alvin0/ai-agent-sdk-core'\nimport { attributionHeaders } from '@alvin0/ai-agent-sdk-core'\nimport { detachedFrozen } from '@alvin0/ai-agent-sdk-core'\nimport type { SseEvent } from '../stream/sse.ts'\nimport {\n DEFAULT_STREAM_IDLE_TIMEOUT_MS,\n DEFAULT_REQUEST_TIMEOUT_MS,\n DEFAULT_MAX_REQUEST_BYTES,\n DEFAULT_MAX_RESPONSE_BYTES,\n DEFAULT_MAX_RESPONSE_CHUNKS,\n DEFAULT_MAX_ERROR_BODY_BYTES,\n HttpModelAdapter,\n type HttpConnection,\n type ProviderCatalogModel,\n type ProviderRequest,\n type ProviderRequestLogger,\n type ProviderRequestLogRecord,\n} from '../base/http-adapter.ts'\nimport type { ProviderProtocolChunk } from '../stream/types.ts'\nimport { resolveDialect, type WireProtocol } from '../protocol/protocol.ts'\nimport {\n observeCredentialOperation,\n observeModelCatalogOperation,\n} from '../observation/operations.ts'\nimport {\n captureHeaderLayer,\n DEFAULT_TRANSPORT_HEADERS,\n mergeHeaderLayers,\n} from '../common/header-layers.ts'\nimport {\n catalogModelInfo,\n resolvedCatalogModelInfo,\n} from '../base/transport.ts'\n\n/** A credential, either literal or resolved per operation. */\nexport type CredentialSource = string | ((\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n) => string | Promise<string>)\n\n/**\n * How requests are authenticated.\n *\n * `dynamic` is the escape hatch that keeps OAuth out of subclass territory: it is\n * called once per operation, so it can refresh a token, read a rotating secret, or\n * add account-scoping headers.\n */\nexport type AuthScheme =\n /** Unauthenticated — a local server, or an endpoint behind a network boundary. */\n | { kind: 'none' }\n /** `authorization: Bearer <token>`. */\n | { kind: 'bearer'; token: CredentialSource; label?: string }\n /** A named header, e.g. `x-api-key`. */\n | { kind: 'header'; name: string; value: CredentialSource; label?: string }\n /** Arbitrary headers resolved per operation. */\n | {\n kind: 'dynamic'\n resolve: (\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n provider?: string,\n ) => Record<string, string> | Promise<Record<string, string>>\n }\n\ninterface ResolvedAuthHeaders {\n readonly headers: Readonly<Record<string, string>>\n}\n\n/** What a model-discovery hook receives. */\nexport interface ModelDiscoveryContext {\n /** The endpoint base, with no trailing slash. */\n readonly baseUrl: string\n /** Every header the request would carry, including authentication. */\n readonly headers: Readonly<Record<string, string>>\n readonly signal?: AbortSignal\n /** Additive runtime context; legacy discovery hooks may ignore it. */\n readonly provider?: string\n /** Additive invocation context; legacy discovery hooks may ignore it. */\n readonly context?: ModelInvocationContext\n}\n\n/** Configuration for {@link createHttpProvider}. */\nexport interface HttpProviderOptions<Dialect extends object> {\n /** Human-readable name used in every diagnostic. */\n displayName: string\n /** The wire protocol this endpoint speaks. */\n protocol: WireProtocol<Dialect>\n /** Endpoint base; the protocol's path is appended. */\n baseUrl: string\n /** Permit cleartext HTTP explicitly, for trusted local development only. */\n allowInsecureHttp?: boolean\n /** Captured fetch implementation for tests, custom runtimes, and transport policy. */\n fetch?: typeof globalThis.fetch\n /** How to authenticate. */\n auth: AuthScheme\n /**\n * Per-endpoint protocol knobs, merged over the protocol's defaults.\n *\n * Partial, so a protocol can gain a knob without any endpoint needing an edit.\n */\n dialect?: Partial<Dialect>\n /** Extra static headers, or a resolver for them. */\n headers?: Record<string, string> | (() => Record<string, string>)\n /**\n * Advisory model catalog.\n *\n * Requests are never restricted to it. Supply entries to declare capabilities\n * the SDK cannot infer — most importantly image support, since an uncatalogued\n * model is treated as text-only and its images are projected to text.\n */\n models?: readonly ProviderCatalogModel[]\n /**\n * Fetch the catalog from the endpoint instead of declaring it.\n *\n * Result is memoized for {@link catalogTtlMs}. A failure here is NOT fatal:\n * refusing the actual model call because a metadata request failed would be the\n * wrong trade.\n */\n discoverModels?: (context: ModelDiscoveryContext) => Promise<readonly ProviderCatalogModel[]>\n /** How long a discovered catalog is reused. Defaults to five minutes. */\n catalogTtlMs?: number\n /** Additional opt-in lifetime for the last valid catalog after refresh failure. */\n catalogStaleTtlMs?: number\n /** Backoff after discovery failure before another refresh is attempted. */\n catalogFailureBackoffMs?: number\n /** Maximum catalog entries retained from static config or discovery. Defaults to 2,048. */\n maxCatalogModels?: number\n /** Maximum serialized catalog bytes retained. Defaults to 4 MiB. */\n maxCatalogBytes?: number\n /**\n * Decorate resolved model metadata.\n *\n * The hook for capabilities that come from the endpoint's configuration rather\n * than its catalog — Anthropic uses it to advertise thinking budgets as\n * selectable reasoning efforts.\n */\n describeModel?: (info: ResolvedModelInfo, dialect: Dialect) => ResolvedModelInfo\n /** Output cap when neither caller nor catalog names one. */\n defaultMaxTokens?: number\n /** Context capacity assumed for an uncatalogued model. */\n defaultContextWindow?: number\n /** Idle bound while a stream read is outstanding. */\n streamIdleTimeoutMs?: number\n /** End-to-end request/stream timeout. Defaults to ten minutes. */\n requestTimeoutMs?: number\n /** Maximum serialized outbound request bytes. Defaults to 32 MiB. */\n maxRequestBytes?: number\n /** Maximum cumulative successful response bytes. Defaults to 32 MiB. */\n maxResponseBytes?: number\n /** Maximum raw response chunks. Defaults to 100,000. */\n maxResponseChunks?: number\n /** Maximum decoded SSE events accepted from one response. */\n maxSseEvents?: number\n /** Maximum characters accepted in one decoded SSE event. */\n maxSseEventChars?: number\n /** Maximum non-success response bytes retained. Defaults to 1 MiB. */\n maxErrorBodyBytes?: number\n /** Maximum time granted to the optional request logger. Defaults to 5 seconds. */\n requestLoggerTimeoutMs?: number\n /** Retry policy this route owns. */\n retryPolicy?: RetryPolicyConfig\n /**\n * Classify a status this endpoint reports specially.\n *\n * Return `undefined` to fall through to the shared mapping, so an override only\n * has to describe what is genuinely different.\n */\n errorCode?: (status: number, detail: string) => string | undefined\n /** Override the `accept` / `content-type` the pipeline sends. */\n baseHeaders?: Record<string, string>\n /**\n * Observe exact protocol-serialized requests immediately before `fetch`.\n * Credentials are redacted, but bodies still contain prompts and tool output.\n * @deprecated High-risk compatibility bridge. Prefer structured observation.\n */\n requestLogger?: ProviderRequestLogger\n}\n\nconst DEFAULT_CATALOG_TTL_MS = 5 * 60 * 1_000\nconst DEFAULT_CATALOG_STALE_TTL_MS = 0\nconst DEFAULT_CATALOG_FAILURE_BACKOFF_MS = 5_000\nconst DEFAULT_MAX_CATALOG_MODELS = 2_048\nconst DEFAULT_MAX_CATALOG_BYTES = 4 * 1024 * 1024\n\n/** Resolve one credential source, with a useful label on failure. */\nasync function credential(\n source: CredentialSource,\n displayName: string,\n label: string,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n): Promise<string> {\n const value = typeof source === 'function' ? await source(signal, context) : source\n return assertUsableApiKey(value, displayName, label)\n}\n\n/**\n * A provider whose every endpoint fact is configuration.\n *\n * Kept private: the exported surface is {@link createHttpProvider}, so this class\n * is free to change and callers cannot come to depend on its shape.\n */\nclass ConfiguredHttpAdapter<Dialect extends object> extends HttpModelAdapter {\n protected readonly displayName: string\n\n private readonly options: HttpProviderOptions<Dialect>\n private readonly dialect: Dialect\n private readonly retry: ResolvedRetryPolicy\n private catalog: { models: readonly ProviderCatalogModel[]; fetchedAt: number } | undefined\n private catalogFailureAt: number | undefined\n\n constructor(options: HttpProviderOptions<Dialect>) {\n super()\n const maxCatalogModels = positiveSafeInteger(\n options.maxCatalogModels ?? DEFAULT_MAX_CATALOG_MODELS,\n 'maxCatalogModels',\n )\n const maxCatalogBytes = positiveSafeInteger(\n options.maxCatalogBytes ?? DEFAULT_MAX_CATALOG_BYTES,\n 'maxCatalogBytes',\n )\n const models = options.models === undefined\n ? undefined\n : boundedCatalog(options.models, maxCatalogModels, maxCatalogBytes)\n this.options = Object.freeze({\n ...options,\n catalogTtlMs: positiveFinite(options.catalogTtlMs ?? DEFAULT_CATALOG_TTL_MS, 'catalogTtlMs'),\n catalogStaleTtlMs: nonNegativeFinite(\n options.catalogStaleTtlMs ?? DEFAULT_CATALOG_STALE_TTL_MS,\n 'catalogStaleTtlMs',\n ),\n catalogFailureBackoffMs: nonNegativeFinite(\n options.catalogFailureBackoffMs ?? DEFAULT_CATALOG_FAILURE_BACKOFF_MS,\n 'catalogFailureBackoffMs',\n ),\n maxCatalogModels,\n maxCatalogBytes,\n auth: Object.freeze({ ...options.auth }),\n ...(models === undefined ? {} : { models }),\n ...(options.headers === undefined || typeof options.headers === 'function'\n ? {}\n : { headers: Object.freeze({ ...options.headers }) }),\n ...(options.baseHeaders === undefined ? {} : { baseHeaders: Object.freeze({ ...options.baseHeaders }) }),\n })\n this.displayName = options.displayName\n this.dialect = resolveDialect(options.protocol, options.dialect)\n this.retry = resolveRetryPolicy(options.retryPolicy, `${options.displayName}.retryPolicy`)\n }\n\n override providerRetryPolicy(): ResolvedRetryPolicy {\n return this.retry\n }\n\n override listModels(provider: string, signal?: AbortSignal): Promise<readonly ModelInfo[]> {\n if (!this.hasStaticCatalog()) return super.listModels(provider, signal)\n signal?.throwIfAborted()\n return Promise.resolve(this.staticModels(provider))\n }\n\n override resolveModel(\n provider: string,\n model: string,\n signal?: AbortSignal,\n ): Promise<ResolvedModelInfo> {\n if (!this.hasStaticCatalog()) return super.resolveModel(provider, model, signal)\n signal?.throwIfAborted()\n return Promise.resolve(this.decorateModel(resolvedCatalogModelInfo(\n provider,\n model,\n this.options.models ?? [],\n this.options.defaultMaxTokens ?? 8_192,\n this.options.defaultContextWindow ?? 128_000,\n )))\n }\n\n override async modelCatalog(\n provider: string,\n options: ModelCatalogOptions = {},\n ): Promise<ModelCatalogSnapshot> {\n if (this.hasStaticCatalog()) {\n options.signal?.throwIfAborted()\n return Object.freeze({\n provider: Object.freeze({ id: provider, name: this.displayName }),\n state: 'static',\n revision: 'http-static',\n models: this.staticModels(provider),\n observedAt: new Date().toISOString(),\n })\n }\n const snapshot = await super.modelCatalog(provider, options)\n if (this.catalogFailureAt !== undefined) {\n throw new Error('HTTP provider model catalog is unavailable')\n }\n return snapshot\n }\n\n protected override decorateModel(base: ResolvedModelInfo): ResolvedModelInfo {\n return this.options.describeModel?.(base, this.dialect) ?? base\n }\n\n private hasStaticCatalog(): boolean {\n return this.options.models !== undefined || this.options.discoverModels === undefined\n }\n\n private staticModels(provider: string): readonly ModelInfo[] {\n return Object.freeze((this.options.models ?? []).map(model =>\n Object.freeze(catalogModelInfo(provider, model))))\n }\n\n /** Resolve the authentication headers for one operation. */\n private async authHeaders(\n provider: string,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<ResolvedAuthHeaders> {\n const auth = this.options.auth\n switch (auth.kind) {\n case 'none':\n return { headers: {} }\n case 'bearer': {\n const token = await observeCredentialOperation(context, provider, 'resolve', () => credential(\n auth.token, this.displayName, auth.label ?? 'the `auth.token` option', signal, context,\n ))\n return { headers: { authorization: `Bearer ${token}` } }\n }\n case 'header': {\n const value = await observeCredentialOperation(context, provider, 'resolve', () => credential(\n auth.value, this.displayName, auth.label ?? `the \\`${auth.name}\\` credential`, signal, context,\n ))\n return { headers: { [auth.name]: value } }\n }\n case 'dynamic':\n return { headers: await observeCredentialOperation(\n context, provider, 'resolve', async () => await auth.resolve(signal, context, provider),\n ) }\n default:\n return { headers: {} }\n }\n }\n\n protected override async connect(\n provider: string,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<HttpConnection> {\n const timeoutMs = positiveFinite(\n this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs',\n )\n const timeout = AbortSignal.timeout(timeoutMs)\n const operationSignal = signal === undefined ? timeout : AbortSignal.any([signal, timeout])\n const baseUrl = this.options.baseUrl.replace(/\\/+$/, '')\n // Credential and endpoint resolve together, in one snapshot, so a rotating\n // secret can never be paired with a different generation's URL.\n const extra = typeof this.options.headers === 'function'\n ? this.options.headers()\n : this.options.headers ?? {}\n const publicLayers = [\n captureHeaderLayer({\n layer: 'transport', headers: this.options.baseHeaders ?? DEFAULT_TRANSPORT_HEADERS,\n }),\n captureHeaderLayer({ layer: 'sdk-attribution', headers: attributionHeaders() }),\n captureHeaderLayer({\n layer: 'wire-protocol',\n headers: this.options.protocol.protocolHeaders?.(this.dialect) ?? {},\n }),\n captureHeaderLayer({ layer: 'endpoint', headers: extra }),\n ] as const\n // Structural conflicts that do not depend on credentials fail before secret\n // resolution. The captured layer snapshots cannot mutate while auth awaits.\n mergeHeaderLayers(publicLayers)\n const auth = await raceAbort(this.authHeaders(provider, operationSignal, context), operationSignal)\n const merged = mergeHeaderLayers([\n ...publicLayers,\n captureHeaderLayer({ layer: 'auth', headers: auth.headers }),\n ])\n const headers = merged.headers\n\n return {\n baseUrl,\n headers,\n sensitiveHeaderNames: merged.sensitiveHeaderNames,\n streamIdleTimeoutMs: this.options.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS,\n requestTimeoutMs: this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n maxRequestBytes: this.options.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES,\n maxResponseBytes: this.options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,\n maxResponseChunks: this.options.maxResponseChunks ?? DEFAULT_MAX_RESPONSE_CHUNKS,\n ...(this.options.maxSseEvents === undefined ? {} : { maxSseEvents: this.options.maxSseEvents }),\n ...(this.options.maxSseEventChars === undefined\n ? {}\n : { maxSseEventChars: this.options.maxSseEventChars }),\n maxErrorBodyBytes: this.options.maxErrorBodyBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES,\n ...this.options.allowInsecureHttp === undefined\n ? {}\n : { allowInsecureHttp: this.options.allowInsecureHttp },\n ...this.options.fetch === undefined ? {} : { fetch: this.options.fetch },\n ...this.options.requestLoggerTimeoutMs === undefined\n ? {}\n : { requestLoggerTimeoutMs: this.options.requestLoggerTimeoutMs },\n retryPolicy: this.retry,\n models: this.options.models ?? await this.resolveCatalog(\n provider, baseUrl, headers, operationSignal, context,\n ),\n defaultMaxTokens: this.options.defaultMaxTokens ?? 8_192,\n defaultContextWindow: this.options.defaultContextWindow ?? 128_000,\n }\n }\n\n /** Run the discovery hook, memoized, tolerating failure. */\n private async resolveCatalog(\n provider: string,\n baseUrl: string,\n headers: Record<string, string>,\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n ): Promise<readonly ProviderCatalogModel[]> {\n const discover = this.options.discoverModels\n if (discover === undefined) return []\n const ttl = this.options.catalogTtlMs ?? DEFAULT_CATALOG_TTL_MS\n const staleTtl = this.options.catalogStaleTtlMs ?? DEFAULT_CATALOG_STALE_TTL_MS\n const failureBackoff = this.options.catalogFailureBackoffMs\n ?? DEFAULT_CATALOG_FAILURE_BACKOFF_MS\n const now = Date.now()\n const cached = this.catalog\n if (cached !== undefined && now - cached.fetchedAt < ttl) return cached.models\n if (this.catalogFailureAt !== undefined && now - this.catalogFailureAt < failureBackoff) {\n return staleCatalog(cached, now, ttl, staleTtl)\n }\n\n try {\n const discovered = await observeModelCatalogOperation(\n context,\n provider,\n new URL(baseUrl).origin,\n async () => {\n const pending = discover({\n baseUrl,\n headers,\n provider,\n ...(context === undefined ? {} : { context }),\n ...signal === undefined ? {} : { signal },\n })\n return signal === undefined ? await pending : await raceAbort(pending, signal)\n },\n )\n const models = boundedCatalog(\n discovered,\n this.options.maxCatalogModels ?? DEFAULT_MAX_CATALOG_MODELS,\n this.options.maxCatalogBytes ?? DEFAULT_MAX_CATALOG_BYTES,\n )\n this.catalog = { models, fetchedAt: Date.now() }\n this.catalogFailureAt = undefined\n return models\n } catch (error: unknown) {\n // Cancellation belongs to the caller/runtime refresh generation. Treating\n // it as an offline empty catalog would publish a false successful result.\n if (signal?.aborted === true) throw signal.reason ?? error\n // Offline, unauthorized for metadata, or transient. An empty catalog only\n // costs capability detail; failing the call would cost the whole request.\n this.catalogFailureAt = Date.now()\n return staleCatalog(cached, this.catalogFailureAt, ttl, staleTtl)\n }\n }\n\n protected override baseHeaders(): Record<string, string> {\n return {}\n }\n\n protected override observeRequest(record: ProviderRequestLogRecord): Promise<void> | void {\n return this.options.requestLogger?.(record)\n }\n\n protected override providerErrorCode(status: number, detail: string): string {\n return this.options.errorCode?.(status, detail) ?? super.providerErrorCode(status, detail)\n }\n\n protected override endpointPath(request: ProviderRequest): string {\n return this.options.protocol.endpointPath(request, this.dialect)\n }\n\n protected override buildBody(request: ProviderRequest): unknown | Promise<unknown> {\n return this.options.protocol.serialize(request, this.dialect)\n }\n\n protected override translate(\n events: AsyncIterable<SseEvent>,\n request: ProviderRequest,\n ): AsyncGenerator<ProviderProtocolChunk> {\n return this.options.protocol.translate(events, request, this.displayName)\n }\n}\n\nfunction positiveFinite(value: number, field: string): number {\n if (!Number.isFinite(value) || value <= 0) {\n throw new RangeError(`${field} must be a positive finite number`)\n }\n return value\n}\n\nfunction positiveSafeInteger(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new RangeError(`${field} must be a positive safe integer`)\n }\n return value\n}\n\nfunction nonNegativeFinite(value: number, field: string): number {\n if (!Number.isFinite(value) || value < 0) {\n throw new RangeError(`${field} must be a non-negative finite number`)\n }\n return value\n}\n\nfunction staleCatalog(\n cached: { models: readonly ProviderCatalogModel[]; fetchedAt: number } | undefined,\n now: number,\n ttl: number,\n staleTtl: number,\n): readonly ProviderCatalogModel[] {\n if (cached === undefined || now - cached.fetchedAt >= ttl + staleTtl) return []\n return cached.models\n}\n\n/** Validate resource bounds before retaining a provider-controlled catalog. */\nfunction boundedCatalog(\n value: readonly ProviderCatalogModel[],\n maxModels: number,\n maxBytes: number,\n): readonly ProviderCatalogModel[] {\n if (!Array.isArray(value)) throw new TypeError('model catalog must be an array')\n if (value.length > maxModels) {\n throw new RangeError(`model catalog exceeds maxCatalogModels (${maxModels})`)\n }\n let encoded: string\n try {\n encoded = JSON.stringify(value)\n } catch (error) {\n throw new TypeError('model catalog must be JSON-serializable', { cause: error })\n }\n if (new TextEncoder().encode(encoded).byteLength > maxBytes) {\n throw new RangeError(`model catalog exceeds maxCatalogBytes (${maxBytes})`)\n }\n return detachedFrozen(value)\n}\n\nfunction raceAbort<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) return Promise.reject(signal.reason ?? new Error('HTTP provider operation aborted'))\n return new Promise<T>((resolve, reject) => {\n const abort = () => { cleanup(); reject(signal.reason ?? new Error('HTTP provider operation aborted')) }\n const cleanup = () => signal.removeEventListener('abort', abort)\n signal.addEventListener('abort', abort, { once: true })\n void pending.then(\n value => { cleanup(); resolve(value) },\n error => { cleanup(); reject(error) },\n )\n })\n}\n\n/**\n * Create a provider adapter from configuration.\n * @param options - protocol, endpoint, credential, and optional capability hooks.\n * @returns an adapter ready for `registry.registerAdapter`.\n */\nexport function createHttpProvider<Dialect extends object>(\n options: HttpProviderOptions<Dialect>,\n): HttpModelAdapter {\n return new ConfiguredHttpAdapter(options)\n}\n","import { ModelError } from '@alvin0/ai-agent-sdk-core'\nimport { HTTP_PROVIDER_ERROR_CODES } from './config.ts'\nimport { snapshotJsonObject } from './json-snapshot.ts'\n\nconst WIRE_BODY_LIMITS = Object.freeze({\n maxDepth: 64,\n maxNodes: 200_000,\n maxObjectFields: 100_000,\n maxArrayItems: 100_000,\n maxKeyBytes: 16_384,\n})\n\n/** Validate and detach one synchronous protocol JSON object before dispatch. */\nexport function snapshotWireBody(\n value: unknown,\n maxBytes: number,\n): Readonly<Record<string, unknown>> {\n if (isThenable(value)) {\n throw new ModelError(\n 'runtime wire protocol serialize() must return synchronously',\n HTTP_PROVIDER_ERROR_CODES.WIRE_BODY_INVALID,\n )\n }\n try {\n return snapshotJsonObject(value, { ...WIRE_BODY_LIMITS, maxBytes })\n } catch (error) {\n const tooLarge = error instanceof Error && /byte bound/.test(error.message)\n throw new ModelError(\n tooLarge ? 'runtime wire body exceeds maxRequestBytes' : 'runtime wire body is not bounded JSON',\n tooLarge\n ? HTTP_PROVIDER_ERROR_CODES.WIRE_BODY_TOO_LARGE\n : HTTP_PROVIDER_ERROR_CODES.WIRE_BODY_INVALID,\n { cause: error },\n )\n }\n}\n\nfunction isThenable(value: unknown): boolean {\n if (value === null || (typeof value !== 'object' && typeof value !== 'function')) return false\n const descriptor = Object.getOwnPropertyDescriptor(value, 'then')\n if (descriptor !== undefined && !('value' in descriptor)) return true\n return descriptor !== undefined && typeof descriptor.value === 'function'\n}\n","import {\n AgentSdkError,\n CREDENTIAL_CAPABILITY_API_VERSION,\n type CredentialOperationOptions,\n type ModelInvocationContext,\n type SdkLogger,\n} from '@alvin0/ai-agent-sdk-core/provider'\nimport {\n boundedIdentifier,\n capturedMethod,\n optionalCapturedMethod,\n ownData,\n plainObject,\n} from '../common/data.ts'\nimport { HTTP_PROTOCOL_API_VERSION, HTTP_PROVIDER_ERROR_CODES } from '../protocol/config.ts'\nimport { defineWireProtocol } from '../protocol/definition.ts'\nimport { DEFAULT_MAX_REQUEST_BYTES, type HttpModelAdapter } from '../base/http-adapter.ts'\nimport { snapshotWireBody } from '../common/wire-body.ts'\nimport type {\n ProtocolRequest,\n ProtocolSseEvent,\n ProtocolStreamChunk,\n RuntimeWireProtocol,\n} from '../protocol/runtime-types.ts'\nimport {\n createHttpProvider,\n type AuthScheme,\n type HttpProviderOptions,\n type ModelDiscoveryContext,\n} from './http-provider.ts'\nimport type { RuntimeHttpProviderOptions, RuntimeModelDiscoveryContext } from './runtime-types.ts'\nimport { snapshotJsonObject } from '../common/json-snapshot.ts'\nimport { HTTP_RUNTIME_OPTION_LIMITS } from '../common/config.ts'\nimport { mergeHeaderLayers, type HeaderLayer } from '../common/header-layers.ts'\n\nconst NEVER_ABORTED_SIGNAL = new AbortController().signal\nconst NULL_LOGGER: SdkLogger = Object.freeze({\n child: () => NULL_LOGGER,\n trace: () => undefined,\n debug: () => undefined,\n info: () => undefined,\n warn: () => undefined,\n error: () => undefined,\n fatal: () => undefined,\n})\n\n/** Create the versioned HTTP extension adapter without performing credential or network I/O. */\nexport function createRuntimeHttpProvider<Dialect extends object>(\n options: RuntimeHttpProviderOptions<Dialect>,\n): HttpModelAdapter {\n const source = plainObject(options, 'runtime HTTP provider options')\n const displayName = boundedIdentifier(ownData(source, 'displayName'), 256, 'displayName')\n const baseUrl = captureBaseUrl(ownData(source, 'baseUrl'))\n const protocol = boundedRuntimeProtocol(\n captureRuntimeProtocol<Dialect>(ownData(source, 'protocol')),\n )\n const auth = captureRuntimeAuth(ownData(source, 'auth'), baseUrl)\n const discover = optionalCapturedMethod<\n [RuntimeModelDiscoveryContext], Promise<readonly import('../base/http-adapter.ts').ProviderCatalogModel[]>\n >(source, 'discoverModels')\n const fetch = optionalCapturedMethod<Parameters<typeof globalThis.fetch>, ReturnType<typeof globalThis.fetch>>(\n source,\n 'fetch',\n )\n const describeModel = optionalCapturedMethod<\n [import('@alvin0/ai-agent-sdk-core/provider').ResolvedModelInfo, Dialect],\n import('@alvin0/ai-agent-sdk-core/provider').ResolvedModelInfo\n >(source, 'describeModel')\n const errorCode = optionalCapturedMethod<[number, string], string | undefined>(source, 'errorCode')\n const requestLogger = optionalCapturedMethod<\n [import('../base/http-adapter.ts').ProviderRequestLogRecord], Promise<void> | void\n >(source, 'requestLogger')\n const headers = captureHeaders(source)\n\n const legacy: HttpProviderOptions<Dialect> = {\n displayName,\n protocol,\n baseUrl: baseUrl.href,\n auth,\n ...copyOptional(source, 'allowInsecureHttp'),\n ...copyJsonOptional(source, 'models', 'models'),\n ...copyJsonOptional(source, 'dialect', 'dialect'),\n ...(fetch === undefined ? {} : { fetch }),\n ...(headers === undefined ? {} : { headers }),\n ...copyOptional(source, 'catalogTtlMs'),\n ...copyOptional(source, 'catalogStaleTtlMs'),\n ...copyOptional(source, 'catalogFailureBackoffMs'),\n ...copyOptional(source, 'maxCatalogModels'),\n ...copyOptional(source, 'maxCatalogBytes'),\n ...(describeModel === undefined ? {} : { describeModel }),\n ...copyOptional(source, 'defaultMaxTokens'),\n ...copyOptional(source, 'defaultContextWindow'),\n ...copyOptional(source, 'streamIdleTimeoutMs'),\n ...copyOptional(source, 'requestTimeoutMs'),\n ...copyOptional(source, 'maxRequestBytes'),\n ...copyOptional(source, 'maxResponseBytes'),\n ...copyOptional(source, 'maxResponseChunks'),\n ...copyOptional(source, 'maxSseEvents'),\n ...copyOptional(source, 'maxSseEventChars'),\n ...copyOptional(source, 'maxErrorBodyBytes'),\n ...copyOptional(source, 'requestLoggerTimeoutMs'),\n ...copyJsonOptional(source, 'retryPolicy', 'retryPolicy'),\n ...(errorCode === undefined ? {} : { errorCode }),\n ...copyHeaderOptional(source, 'baseHeaders', 'transport'),\n ...(requestLogger === undefined ? {} : { requestLogger }),\n ...(discover === undefined ? {} : {\n discoverModels: async (context: ModelDiscoveryContext) => discover({\n provider: context.provider ?? '',\n baseUrl: new URL(context.baseUrl),\n headers: context.headers,\n signal: context.signal ?? NEVER_ABORTED_SIGNAL,\n ...(context.context === undefined ? {} : { context: context.context }),\n }),\n }),\n }\n return createHttpProvider(legacy)\n}\n\nfunction boundedRuntimeProtocol<Dialect extends object>(\n protocol: RuntimeWireProtocol<Dialect>,\n): RuntimeWireProtocol<Dialect> {\n return Object.freeze({\n ...protocol,\n serialize(request: ProtocolRequest, dialect: Dialect) {\n return snapshotWireBody(\n protocol.serialize(request, dialect),\n request.connection.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES,\n )\n },\n })\n}\n\nfunction captureRuntimeProtocol<Dialect extends object>(value: unknown): RuntimeWireProtocol<Dialect> {\n try {\n const source = plainObject(value, 'runtime wire protocol')\n if (ownData(source, 'kind') !== 'http-wire-protocol'\n || ownData(source, 'apiVersion') !== HTTP_PROTOCOL_API_VERSION) {\n throw new TypeError('unsupported protocol marker')\n }\n const endpointPath = capturedMethod<[ProtocolRequest, Dialect], string>(source, 'endpointPath')\n const protocolHeaders = optionalCapturedMethod<\n [Dialect], Readonly<Record<string, string>>\n >(source, 'protocolHeaders')\n const serialize = capturedMethod<\n [ProtocolRequest, Dialect], Readonly<Record<string, unknown>>\n >(source, 'serialize')\n const translate = capturedMethod<\n [AsyncIterable<ProtocolSseEvent>, ProtocolRequest, string], AsyncGenerator<ProtocolStreamChunk>\n >(source, 'translate')\n return defineWireProtocol({\n id: ownData(source, 'id') as string,\n defaultDialect: ownData(source, 'defaultDialect') as Dialect,\n endpointPath,\n ...(protocolHeaders === undefined ? {} : { protocolHeaders }),\n serialize,\n translate,\n })\n } catch (error) {\n throw new AgentSdkError(\n 'Runtime HTTP protocol is incompatible',\n HTTP_PROVIDER_ERROR_CODES.PROTOCOL_API_UNSUPPORTED,\n { cause: error },\n )\n }\n}\n\nfunction captureRuntimeAuth(value: unknown, baseUrl: URL): AuthScheme {\n const source = plainObject(value, 'runtime HTTP auth')\n const kind = ownData(source, 'kind')\n if (kind === 'none') return Object.freeze({ kind })\n if (kind === 'bearer') {\n return Object.freeze({\n kind,\n token: captureCredential(ownData(source, 'token')),\n ...copyOptional(source, 'label'),\n })\n }\n if (kind === 'header') {\n const name = boundedIdentifier(ownData(source, 'name'), 256, 'auth header name')\n return Object.freeze({\n kind,\n name,\n value: captureCredential(ownData(source, 'value')),\n ...copyOptional(source, 'label'),\n })\n }\n if (kind === 'dynamic') {\n const resolve = capturedMethod<\n [import('../protocol/runtime-types.ts').HttpAuthResolveOptions],\n Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>\n >(source, 'resolve')\n return Object.freeze({\n kind,\n resolve: async (\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n provider = '',\n ) => ({\n ...await resolve({\n provider,\n baseUrl,\n signal: signal ?? NEVER_ABORTED_SIGNAL,\n ...(context === undefined ? {} : { context }),\n }),\n }),\n })\n }\n throw new AgentSdkError('Runtime HTTP auth is invalid', HTTP_PROVIDER_ERROR_CODES.HEADER_INVALID)\n}\n\nfunction captureCredential(input: unknown): string | ((\n signal?: AbortSignal,\n context?: ModelInvocationContext,\n) => string | Promise<string>) {\n if (typeof input === 'string') return input\n // auth-node's envCredential intentionally retains its historical callable\n // surface while carrying the current credential-source capability fields.\n // Capture those fields exactly like a plain source object; never invoke the\n // callable compatibility view during provider construction.\n const source = typeof input === 'function'\n ? input\n : plainObject(input, 'credential source')\n if (ownData(source, 'kind') !== 'credential-source'\n || ownData(source, 'apiVersion') !== CREDENTIAL_CAPABILITY_API_VERSION) {\n throw new AgentSdkError('Credential source is incompatible', 'CREDENTIAL_SOURCE_INVALID')\n }\n const resolve = capturedMethod<\n [CredentialOperationOptions], string | Promise<string>\n >(source, 'resolve')\n return (signal, context) => resolve({\n signal: signal ?? NEVER_ABORTED_SIGNAL,\n logger: context?.logger ?? NULL_LOGGER,\n })\n}\n\nfunction captureBaseUrl(value: unknown): URL {\n if (value instanceof URL) return new URL(value.href)\n if (typeof value === 'string') return new URL(value)\n throw new TypeError('baseUrl must be an absolute URL or URL string')\n}\n\nfunction copyOptional(source: object, key: string): Record<string, unknown> {\n const value = ownData(source, key, false)\n return value === undefined ? {} : { [key]: value }\n}\n\nfunction copyJsonOptional(source: object, key: string, envelopeKey: string): Record<string, unknown> {\n const value = ownData(source, key, false)\n if (value === undefined) return {}\n const snapshot = snapshotJsonObject({ [envelopeKey]: value }, HTTP_RUNTIME_OPTION_LIMITS)\n return { [key]: snapshot[envelopeKey] }\n}\n\nfunction copyHeaderOptional(\n source: object,\n key: string,\n layer: HeaderLayer,\n): Record<string, unknown> {\n const value = ownData(source, key, false)\n return value === undefined ? {} : { [key]: snapshotHeaders(value, layer) }\n}\n\nfunction captureHeaders(\n source: object,\n): Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>) | undefined {\n const value = ownData(source, 'headers', false)\n if (value === undefined) return undefined\n if (typeof value !== 'function') return snapshotHeaders(value, 'endpoint')\n const captured = (...args: []) => Reflect.apply(value, source, args) as unknown\n return () => snapshotHeaders(captured(), 'endpoint')\n}\n\nfunction snapshotHeaders(value: unknown, layer: HeaderLayer): Readonly<Record<string, string>> {\n return mergeHeaderLayers([{ layer, headers: value as Readonly<Record<string, string>> }]).headers\n}\n","/**\n * Decode an SSE byte stream into events.\n *\n * All the genuinely hard framing work  Echunk reassembly, UTF-8 sequences split\n * across reads, CRLF and BOM handling, comment and unknown-field skipping,\n * joining multiple `data:` lines of one event  Ebelongs to `eventsource-parser`.\n *\n * Note what is deliberately NOT decided here. OpenAI terminates with a literal\n * `data: [DONE]` sentinel; Anthropic terminates with a named `message_stop` event\n * and sends no sentinel at all. Baking in either rule would make the parser lie\n * about the other, so termination is the adapter's call and this generator simply\n * runs to the end of the body.\n *\n * The callback-based parser is used rather than `EventSourceParserStream` so the\n * SDK does not require `TextDecoderStream` to exist  Eit is absent on some\n * runtimes this package should still work on.\n *\n * @module @alvin0/ai-agent-sdk-provider-http/sse\n */\n\nimport {\n DEFAULT_MAX_SSE_EVENT_CHARS,\n DEFAULT_MAX_SSE_EVENTS,\n DEFAULT_SSE_TEARDOWN_TIMEOUT_MS,\n} from './config.ts'\nimport { parseSseBounded } from './parser.ts'\n\n/**\n * Ceiling on characters the parser may buffer across reads.\n *\n * A stream that never sends an event terminator would otherwise buffer without\n * bound. 1 MiB is far above any legitimate single SSE event from either provider\n * and far below a memory problem.\n */\n/** One decoded server-sent event. */\nexport interface SseEvent {\n /**\n * The event name, or `undefined` when the server declared none.\n *\n * NOT defaulted to `'message'` the way a browser `EventSource` would. Absence is\n * reported faithfully, which is what lets an adapter tell Anthropic's named\n * events apart from OpenAI's anonymous data-only frames.\n */\n event: string | undefined\n /** The event's data payload. */\n data: string\n}\n\n/**\n * Parse an SSE byte stream into events, in arrival order.\n *\n * Framing is spec-strict: an event dispatches only on its blank-line terminator,\n * so an unterminated tail at EOF is truncation rather than a flushable payload.\n * @param stream - raw SSE bytes, as `Response.body` provides them. Reads may split\n * anywhere, including mid-codepoint; the streaming decoder handles that.\n * @param onActivity - called on every frame INCLUDING comments. Providers send\n * comment-only keepalives during long pauses, so a liveness watchdog has to\n * count them as activity even though they carry no data.\n * @returns each event in arrival order; returns normally at end of body.\n */\nexport async function* parseSse(\n stream: ReadableStream<Uint8Array>,\n onActivity?: () => void,\n teardownTimeoutMs = DEFAULT_SSE_TEARDOWN_TIMEOUT_MS,\n): AsyncGenerator<SseEvent> {\n yield* parseSseBounded(stream, onActivity, teardownTimeoutMs, {\n maxEvents: DEFAULT_MAX_SSE_EVENTS,\n maxEventChars: DEFAULT_MAX_SSE_EVENT_CHARS,\n })\n}\n"],"mappings":";;;;;;AACA,MAAa,4BAA4B;;AAGzC,MAAa,4BAA4B,OAAO,OAAO;CACrD,0BAA0B;CAC1B,gBAAgB;CAChB,iBAAiB;CACjB,kBAAkB;CAClB,mBAAmB;CACnB,qBAAqB;CACrB,2BAA2B;CAC3B,oBAAoB;CACpB,mBAAmB;AACrB,CAAU;AAEV,MAAa,uBAAuB,OAAO,OAAO;CAChD,SAAS;CACT,cAAc;CACd,cAAc;CACd,qBAAqB;CACrB,mBAAmB;CACnB,iBAAiB;CACjB,cAAc;AAChB,CAAC;;AAGD,MAAa,6BAA6B,OAAO,OAAO;CACtD,UAAU;CACV,UAAU;CACV,iBAAiB;CACjB,eAAe;CACf,aAAa;CACb,UAAU;AACZ,CAAC;;AAGD,MAAa,8BAA8B,OAAO,OAAO;CACvD,cAAc;CACd,WAAW;CACX,gBAAgB;AAClB,CAAC;;;;;AClCD,gBAAuB,gBACrB,QACA,YACA,mBACA,QAC0B;CAC1B,MAAM,UAAsB,CAAC;CAC7B,IAAI,UAAU;CACd,MAAM,SAAS,aAAa;EAC1B,eAAe,OAAO;EACtB,QAAQ,OAAO;GACb,IAAI,MAAM,SAAS,4BAA4B,MAAM,WAAW,WAAW;EAC7E;EACA,QAAQ,OAAO;GACb;GACA,IAAI,UAAU,OAAO,aAAa,MAAM,KAAK,SAAS,OAAO,eAC3D,MAAM,WAAW,UAAU,OAAO,YAAY,gBAAgB,WAAW;GAE3E,QAAQ,KAAK;IAAE,OAAO,MAAM;IAAO,MAAM,MAAM;GAAK,CAAC;EACvD;EACA,YAAY;GAAE,aAAa;EAAE;CAC/B,CAAC;CAED,MAAM,UAAU,IAAI,YAAY;CAChC,MAAM,SAAS,O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oB,iCACM;CAC1B,OAAO,gBAAgB,QAAQ,YAAY,mBAAmB;EAC5D,WAAW;EACX,eAAe;CACjB,CAAC;AACH"}
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@alvin0/ai-agent-sdk-provider-http",
3
+ "author": {
4
+ "name": "alvin0 - chaulamdinhai",
5
+ "email": "chaulamdinhai@gmail.com"
6
+ },
7
+ "version": "0.1.0",
8
+ "description": "Universal fetch, SSE, configurable provider, and provider-attempt accounting for ai-agent-sdk",
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/alvin0/ai-agent-sdk.git",
13
+ "directory": "packages/provider-http"
14
+ },
15
+ "homepage": "https://github.com/alvin0/ai-agent-sdk/tree/main/packages/provider-http#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/alvin0/ai-agent-sdk/issues"
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "provenance": true
39
+ },
40
+ "dependencies": {
41
+ "eventsource-parser": "4.1.0"
42
+ },
43
+ "peerDependencies": {
44
+ "@alvin0/ai-agent-sdk-core": "^0.1.0"
45
+ },
46
+ "devDependencies": {
47
+ "@alvin0/ai-agent-sdk-core": "^0.1.0",
48
+ "@arethetypeswrong/cli": "0.18.5",
49
+ "playwright": "1.62.1",
50
+ "publint": "0.3.24",
51
+ "tsdown": "0.22.14",
52
+ "typescript": "7.0.2",
53
+ "vitest": "4.1.11",
54
+ "wrangler": "4.127.1"
55
+ },
56
+ "aiAgentSdk": {
57
+ "runtime": "universal",
58
+ "coreApi": 1,
59
+ "roles": [
60
+ "provider-extension-kit"
61
+ ]
62
+ },
63
+ "scripts": {
64
+ "build": "tsdown",
65
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true});require('node:fs').rmSync('artifacts',{recursive:true,force:true})\"",
66
+ "typecheck": "tsc --noEmit",
67
+ "test": "vitest run --config vitest.config.ts",
68
+ "pack": "pnpm pack --pack-destination artifacts",
69
+ "test:pack": "node scripts/test-packed.mts",
70
+ "check:publint": "publint",
71
+ "check:types": "attw --profile esm-only --pack ."
72
+ }
73
+ }