@alvin0/ai-agent-sdk-provider-http 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -739,6 +739,10 @@ declare function createRuntimeHttpProvider<Dialect extends object>(options: Runt
739
739
  declare function observeCredentialOperation<T>(context: ModelInvocationContext | undefined, provider: string, operation: 'resolve' | 'refresh' | 'login', task: () => Promise<T>): Promise<T>;
740
740
  declare function observeModelCatalogOperation<T>(context: ModelInvocationContext | undefined, provider: string, origin: string, task: () => Promise<T>): Promise<T>;
741
741
  //#endregion
742
+ //#region src/common/endpoint-headers.d.ts
743
+ /** Capture custom endpoint headers per operation, rejecting reserved names and collisions. */
744
+ declare function endpointHeaders(headers: Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>) | undefined, defaults?: Readonly<Record<string, string>>): () => Readonly<Record<string, string>>;
745
+ //#endregion
742
746
  //#region src/transport/embedding-connection.d.ts
743
747
  /**
744
748
  * One embedding model an HTTP route declares.
@@ -940,5 +944,5 @@ declare function transportJson<T>(input: HttpTransportRequestInput, decode: (ses
940
944
  /** True when a `content-type` value names one of {@link JSON_MEDIA_TYPES}. */
941
945
  declare function isJsonMediaType(contentType: string | null): boolean;
942
946
  //#endregion
943
- export { AnyWireProtocol, AuthScheme, CredentialSource, DEFAULT_MAX_ERROR_BODY_BYTES, DEFAULT_MAX_REQUEST_BYTES, DEFAULT_MAX_RESPONSE_BYTES, DEFAULT_MAX_RESPONSE_CHUNKS, DEFAULT_REQUEST_LOGGER_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, EmbeddingCatalogModel, EmbeddingHttpConnection, HTTP_PROTOCOL_API_VERSION, HTTP_PROVIDER_ERROR_CODES, type HttpAuthResolveOptions, type HttpConnection, HttpModelAdapter, HttpProviderOptions, type HttpTransportConnection, type HttpTransportRequestInput, type HttpTransportSession, JSON_MEDIA_TYPES, ModelContextPolicy, ModelContextPolicyOptions, ModelDiscoveryContext, type ParsedErrorBody, type PreparedWireBody, type ProtocolRequest, type ProtocolSseEvent, type ProtocolStreamChunk, type ProviderCatalogModel, type ProviderRequest, type ProviderRequestLogRecord, type ProviderRequestLogger, type ResolvedTransportLimits, type RuntimeAuthScheme, type RuntimeCredentialSource, type RuntimeHttpProviderOptions, type RuntimeModelDiscoveryContext, type RuntimeWireProtocol, SseEvent, type WireBodySource, WireProtocol, WireProtocolChunk, type WireProtocolDefinition, applyModelContextPolicy, captureTransportConnection, createHttpProvider, createModelContextPolicy, createRuntimeHttpProvider, defineWireProtocol, embeddingCatalogModelInfo, httpErrorCode, isJsonMediaType, observeCredentialOperation, observeModelCatalogOperation, parseErrorBody, parseSse, redactHeaders, requestIdFrom, resolveDialect, resolveTransportLimits, resolvedEmbeddingCatalogModelInfo, retryAfterMs, transportJson };
947
+ export { AnyWireProtocol, AuthScheme, CredentialSource, DEFAULT_MAX_ERROR_BODY_BYTES, DEFAULT_MAX_REQUEST_BYTES, DEFAULT_MAX_RESPONSE_BYTES, DEFAULT_MAX_RESPONSE_CHUNKS, DEFAULT_REQUEST_LOGGER_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, EmbeddingCatalogModel, EmbeddingHttpConnection, HTTP_PROTOCOL_API_VERSION, HTTP_PROVIDER_ERROR_CODES, type HttpAuthResolveOptions, type HttpConnection, HttpModelAdapter, HttpProviderOptions, type HttpTransportConnection, type HttpTransportRequestInput, type HttpTransportSession, JSON_MEDIA_TYPES, ModelContextPolicy, ModelContextPolicyOptions, ModelDiscoveryContext, type ParsedErrorBody, type PreparedWireBody, type ProtocolRequest, type ProtocolSseEvent, type ProtocolStreamChunk, type ProviderCatalogModel, type ProviderRequest, type ProviderRequestLogRecord, type ProviderRequestLogger, type ResolvedTransportLimits, type RuntimeAuthScheme, type RuntimeCredentialSource, type RuntimeHttpProviderOptions, type RuntimeModelDiscoveryContext, type RuntimeWireProtocol, SseEvent, type WireBodySource, WireProtocol, WireProtocolChunk, type WireProtocolDefinition, applyModelContextPolicy, captureTransportConnection, createHttpProvider, createModelContextPolicy, createRuntimeHttpProvider, defineWireProtocol, embeddingCatalogModelInfo, endpointHeaders, httpErrorCode, isJsonMediaType, observeCredentialOperation, observeModelCatalogOperation, parseErrorBody, parseSse, redactHeaders, requestIdFrom, resolveDialect, resolveTransportLimits, resolvedEmbeddingCatalogModelInfo, retryAfterMs, transportJson };
944
948
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/stream/sse.ts","../src/stream/types.ts","../src/transport/connection.ts","../src/transport/http.ts","../src/transport/limits.ts","../src/base/http-adapter.ts","../src/transport/errors.ts","../src/base/context-policy.ts","../src/common/config.ts","../src/protocol/runtime-types.ts","../src/protocol/definition.ts","../src/protocol/protocol.ts","../src/configurable/http-provider.ts","../src/configurable/runtime-types.ts","../src/configurable/runtime-provider.ts","../src/observation/operations.ts","../src/transport/embedding-connection.ts","../src/transport/session.ts","../src/transport/json.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAmCiB;;;;;;;;EAQf;;EAEA;;;;;;;;;;;;;;iBAeqB,SACrB,QAAQ,eAAe,aACvB,yBACA,6BACC,eAAe;;;;KC7DN,wBACR,QAAQ;WAAwB;;WACrB;WAAwB,OAAO;;;;;UCiB7B;;WAEN;;;;;;;WAOA,SAAS,SAAS;;WAElB;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,eAAe,WAAW;;WAE1B,aAAa;;;;;;;;;;;;;;;;;iBAkBR,2BAA2B,UAAU,yBACnD,YAAY,GACZ,kBAAkB,SAAS,0BAC1B;;;;iBCyJa,cACd,SAAS,SAAS,yBAClB,2CACC;;;;cCrNU;;cAEA;;cAEA;;cAEA;;cAEA;;cAEA;;;;;;;UAsBI;;W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B,gBAAgB;;;;;iBCxBX,0BAA0B,wBACxC,SAAS,2BAA2B,WACnC;;;iBCqEa,2BAA2B,GACzC,SAAS,oCACT,kBACA,4CACA,YAAY,QAAQ,KACnB,QAAQ;iBASK,6BAA6B,GAC3C,SAAS,oCACT,kBACA,gBACA,YAAY,QAAQ,KACnB,QAAQ;;;;;;;;;;;;;UCtFM;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;;;;WASA,kBAAkB;;WAElB,gBAAgB;;;;;;;;WAQhB;;;;;;;;;;UAWM,gCAAgC;;WAEtC,iBAAiB;;;;;;;;;;;;;;iBAkCZ,0BACd,kBACA,OAAO,wBACN;;;;;;;;;;;;;iBAgCa,kCACd,kBACA,iBACA,iBAAiB,0BAChB;;;;UCrHc;;WAEN;;WAEA;;WAEA;;;;;;;;;;KAWC,iBACR,qBACE,QAAQ,gBAAgB,mBAAmB,QAAQ;;;;;;;UAQxC;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;WAEA,SAAS,SAAS;;WAElB;WACA;;;UAIM;;WAEN,YAAY;;WAEZ;;WAEA;;WAEA;;WAEA;;;;;;;;WAQA;WACA,MAAM;;WAEN,SAAS;WACT,UAAU;;WAEV,aAAa,gBAAgB;;WAE7B,kBAAkB,QAAQ,sBAAsB;;;KAI/C;;UAGK;;WAEN,UAAU;WACV;WACA;;WAEA,QAAQ;;WAER,oBAAoB;;WAEpB;WACA,QAAQ;;;;;;;WAOR;EACT,YAAY,OAAO,eAAe;;EAElC,cAAc,QAAQ,wBAAwB,UAAU;;;;;cCrH7C;;;;;;;;;;iBAWS,cAAc,GAClC,OAAO,2BACP,SAAS,SAAS,sBAAsB,kBAAkB,IAAI,QAAQ,KACrE,QAAQ;;iBA4BK,gBAAgB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/stream/sse.ts","../src/stream/types.ts","../src/transport/connection.ts","../src/transport/http.ts","../src/transport/limits.ts","../src/base/http-adapter.ts","../src/transport/errors.ts","../src/base/context-policy.ts","../src/common/config.ts","../src/protocol/runtime-types.ts","../src/protocol/definition.ts","../src/protocol/protocol.ts","../src/configurable/http-provider.ts","../src/configurable/runtime-types.ts","../src/configurable/runtime-provider.ts","../src/observation/operations.ts","../src/common/endpoint-headers.ts","../src/transport/embedding-connection.ts","../src/transport/session.ts","../src/transport/json.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAmCiB;;;;;;;;EAQf;;EAEA;;;;;;;;;;;;;;iBAeqB,SACrB,QAAQ,eAAe,aACvB,yBACA,6BACC,eAAe;;;;KC7DN,wBACR,QAAQ;WAAwB;;WACrB;WAAwB,OAAO;;;;;UCiB7B;;WAEN;;;;;;;WAOA,SAAS,SAAS;;WAElB;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,eAAe,WAAW;;WAE1B,aAAa;;;;;;;;;;;;;;;;;iBAkBR,2BAA2B,UAAU,yBACnD,YAAY,GACZ,kBAAkB,SAAS,0BAC1B;;;;iBCyJa,cACd,SAAS,SAAS,yBAClB,2CACC;;;;cCrNU;;cAEA;;cAEA;;cAEA;;cAEA;;cAEA;;;;;;;UAsBI;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;;;;;;iBAYK,uBACd,YAAY,0BACX;;;;cCEU;;UAGI;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,2BAA2B;;EAE3B,4BAA4B;;EAE5B,uBAAuB;;EAEvB,YAAY;;;;;;;;;;;;;;;;UAiBG,uBAAuB;;WAE7B;;WAEA;;WAEA;;WAEA,iBAAiB;;WAEjB;;WAEA;;;UAIM;;WAEN,SAAS;;WAET,OAAO;;WAEP,YAAY;;WAEZ;;;;;;UAOM;;WAEN;WACA;;WAEA;WACA;WACA;WACA;WACA;WACA;;WAEA,SAAS,SAAS;;WAElB;WACA;;;;;;KAOC,yBAC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;;;;;;;;;;;;;iBAkCZ,0BACd,kBACA,OAAO,wBACN;;;;;;;;;;;;;iBAgCa,kCACd,kBACA,iBACA,iBAAiB,0BAChB;;;;UCrHc;;WAEN;;WAEA;;WAEA;;;;;;;;;;KAWC,iBACR,qBACE,QAAQ,gBAAgB,mBAAmB,QAAQ;;;;;;;UAQxC;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;WAEA,SAAS,SAAS;;WAElB;WACA;;;UAIM;;WAEN,YAAY;;WAEZ;;WAEA;;WAEA;;WAEA;;;;;;;;WAQA;WACA,MAAM;;WAEN,SAAS;WACT,UAAU;;WAEV,aAAa,gBAAgB;;WAE7B,kBAAkB,QAAQ,sBAAsB;;;KAI/C;;UAGK;;WAEN,UAAU;WACV;WACA;;WAEA,QAAQ;;WAER,oBAAoB;;WAEpB;WACA,QAAQ;;;;;;;WAOR;EACT,YAAY,OAAO,eAAe;;EAElC,cAAc,QAAQ,wBAAwB,UAAU;;;;;cCrH7C;;;;;;;;;;iBAWS,cAAc,GAClC,OAAO,2BACP,SAAS,SAAS,sBAAsB,kBAAkB,IAAI,QAAQ,KACrE,QAAQ;;iBA4BK,gBAAgB"}
package/dist/index.js CHANGED
@@ -2051,6 +2051,26 @@ async function* parseSse(stream, onActivity, teardownTimeoutMs = DEFAULT_SSE_TEA
2051
2051
  });
2052
2052
  }
2053
2053
 
2054
+ //#endregion
2055
+ //#region src/common/endpoint-headers.ts
2056
+ /** Capture custom endpoint headers per operation, rejecting reserved names and collisions. */
2057
+ function endpointHeaders(headers, defaults = {}) {
2058
+ const fixedDefaults = mergeHeaderLayers([{
2059
+ layer: "endpoint",
2060
+ headers: defaults
2061
+ }]).headers;
2062
+ const capture = (value) => mergeHeaderLayers([{
2063
+ layer: "endpoint",
2064
+ headers: fixedDefaults
2065
+ }, {
2066
+ layer: "endpoint",
2067
+ headers: value
2068
+ }]).headers;
2069
+ if (typeof headers === "function") return () => capture(headers());
2070
+ const fixed = capture(headers ?? {});
2071
+ return () => fixed;
2072
+ }
2073
+
2054
2074
  //#endregion
2055
2075
  //#region src/transport/embedding-connection.ts
2056
2076
  /**
@@ -2253,5 +2273,5 @@ function parseJsonBody(text, displayName) {
2253
2273
  }
2254
2274
 
2255
2275
  //#endregion
2256
- export { DEFAULT_MAX_ERROR_BODY_BYTES, DEFAULT_MAX_REQUEST_BYTES, DEFAULT_MAX_RESPONSE_BYTES, DEFAULT_MAX_RESPONSE_CHUNKS, DEFAULT_REQUEST_LOGGER_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, HTTP_PROTOCOL_API_VERSION, HTTP_PROVIDER_ERROR_CODES, HttpModelAdapter, JSON_MEDIA_TYPES, applyModelContextPolicy, captureTransportConnection, createHttpProvider, createModelContextPolicy, createRuntimeHttpProvider, defineWireProtocol, embeddingCatalogModelInfo, httpErrorCode, isJsonMediaType, observeCredentialOperation, observeModelCatalogOperation, parseErrorBody, parseSse, redactHeaders, requestIdFrom, resolveDialect, resolveTransportLimits, resolvedEmbeddingCatalogModelInfo, retryAfterMs, transportJson };
2276
+ export { DEFAULT_MAX_ERROR_BODY_BYTES, DEFAULT_MAX_REQUEST_BYTES, DEFAULT_MAX_RESPONSE_BYTES, DEFAULT_MAX_RESPONSE_CHUNKS, DEFAULT_REQUEST_LOGGER_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, HTTP_PROTOCOL_API_VERSION, HTTP_PROVIDER_ERROR_CODES, HttpModelAdapter, JSON_MEDIA_TYPES, applyModelContextPolicy, captureTransportConnection, createHttpProvider, createModelContextPolicy, createRuntimeHttpProvider, defineWireProtocol, embeddingCatalogModelInfo, endpointHeaders, httpErrorCode, isJsonMediaType, observeCredentialOperation, observeModelCatalogOperation, parseErrorBody, parseSse, redactHeaders, requestIdFrom, resolveDialect, resolveTransportLimits, resolvedEmbeddingCatalogModelInfo, retryAfterMs, transportJson };
2257
2277
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["positiveFinite","ENCODER"],"sources":["../src/common/config.ts","../src/stream/parser.ts","../src/stream/config.ts","../src/stream/idle-deadline.ts","../src/stream/terminal.ts","../src/common/header-layers.ts","../src/transport/connection.ts","../src/transport/limits.ts","../src/transport/http.ts","../src/common/failure.ts","../src/transport/errors.ts","../src/transport/session.ts","../src/transport/stream.ts","../src/base/context-policy.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","../src/transport/embedding-connection.ts","../src/transport/json.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 JSON_MEDIA_TYPE_INVALID: 'HTTP_JSON_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 { 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 connection snapshot every HTTP pipeline in this package shares.\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 operation, makes that impossible.\n *\n * What lives here is only what a request needs regardless of what comes back:\n * where to send it, with what credentials, under what bounds, and with which retry\n * policy. A pipeline's own vocabulary stays with the pipeline — the generation\n * catalog is on {@link ../base/http-adapter.HttpConnection}, and the embedding\n * catalog will be on its own extension, because merging the two catalogs is\n * exactly the mistake that makes one model shape stand in for another.\n *\n * @module ai-agent-sdk/providers/transport/connection\n */\n\nimport { attributionHeaders, type ResolvedRetryPolicy } from '@alvin0/ai-agent-sdk-core'\nimport { mergeHeaderLayers } from '../common/header-layers.ts'\n\n/** The transport-shared half of a connection snapshot. */\nexport interface HttpTransportConnection {\n /** Endpoint base; the pipeline's endpoint path is appended. */\n readonly baseUrl: string\n /**\n * Every header for the request, INCLUDING authorization.\n *\n * Resolved together with the endpoint so the credential travels with the URL it\n * will be sent to. The transport 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 /** 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 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}\n\n/**\n * Merge the transport's own header layer beneath the snapshot's auth layer, once.\n *\n * Layer ownership is what makes this safe to call on a snapshot a subclass or a\n * configuration produced: a transport header can never silently overwrite a\n * credential, and the names the auth layer marked sensitive survive the merge so\n * redaction still covers them.\n *\n * A snapshot that already carries every layer — which configured adapters return —\n * passes an empty transport layer and is returned untouched, so capturing twice\n * cannot re-apply attribution.\n * @param connection - the snapshot captured for this operation.\n * @param transportHeaders - the transport layer to merge underneath; may be empty.\n * @returns the snapshot with merged headers and the union of sensitive names.\n */\nexport function captureTransportConnection<T extends HttpTransportConnection>(\n connection: T,\n transportHeaders: Readonly<Record<string, string>>,\n): T {\n if (Reflect.ownKeys(transportHeaders).length === 0) return connection\n const merged = mergeHeaderLayers([\n { layer: 'transport', headers: transportHeaders },\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 * Transport limits: the numbers that bound ONE HTTP request, wherever it goes.\n *\n * These belong to the transport rather than to a pipeline because every pipeline\n * needs exactly the same bounds — how big a request may be, how much of a\n * response may be read, how long a diagnostic observer may hold up dispatch.\n * A pipeline adds its own decoding limits on top (the SSE pipeline bounds events\n * and event characters); it does not redefine these.\n *\n * @module ai-agent-sdk/providers/transport/limits\n */\n\nimport type { HttpTransportConnection } from './connection.ts'\n\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\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\n/**\n * Every transport bound for one request, defaulted and validated exactly once.\n *\n * Resolved from the connection snapshot, so a configuration change between two\n * reads cannot move a bound mid-request.\n */\nexport interface ResolvedTransportLimits {\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 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}\n\n/**\n * Apply defaults and reject nonsense bounds before any I/O happens.\n *\n * Validation order is fixed and part of the contract: a configuration with two\n * invalid bounds always reports the earlier field, so the error a caller sees does\n * not depend on which limit the pipeline happens to consult first.\n * @param connection - the captured snapshot this request is bound to.\n * @returns fully resolved bounds; never partially defaulted.\n */\nexport function resolveTransportLimits(\n connection: HttpTransportConnection,\n): ResolvedTransportLimits {\n return Object.freeze({\n requestTimeoutMs: positiveFinite(\n connection.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs',\n ),\n maxRequestBytes: positiveInteger(\n connection.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES,\n 'maxRequestBytes',\n ),\n maxResponseBytes: positiveInteger(\n connection.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,\n 'maxResponseBytes',\n ),\n maxResponseChunks: positiveInteger(\n connection.maxResponseChunks ?? DEFAULT_MAX_RESPONSE_CHUNKS,\n 'maxResponseChunks',\n ),\n maxErrorBodyBytes: positiveInteger(\n connection.maxErrorBodyBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES,\n 'maxErrorBodyBytes',\n ),\n requestLoggerTimeoutMs: positiveFinite(\n connection.requestLoggerTimeoutMs ?? DEFAULT_REQUEST_LOGGER_TIMEOUT_MS,\n 'requestLoggerTimeoutMs',\n ),\n })\n}\n","/**\n * The pipeline-independent HTTP primitives the shared chain is built from.\n *\n * Each one exists because the obvious version of it is wrong in a way that only\n * shows up under failure: a body read without a byte bound is a memory bug waiting\n * for a hostile response, a promise raced against a signal that disposes nothing\n * leaks a socket, a redirect followed once is a credential sent somewhere the\n * caller never named, and an iterator abandoned without `return()` leaves a reader\n * locked forever.\n *\n * None of it knows anything about SSE, JSON, catalogs, or model shapes — which is\n * why it sits under the transport and not beside a pipeline.\n *\n * @module ai-agent-sdk/providers/transport/http\n */\n\nimport {\n MODEL_ERROR_CODES,\n ModelError,\n waitForSettlement,\n type ModelFailure,\n type SafeErrorRecord,\n} from '@alvin0/ai-agent-sdk-core'\nimport { HTTP_PROVIDER_ERROR_CODES } from '../common/config.ts'\nimport { isSensitiveHeaderName } from '../common/header-layers.ts'\n\n/** Bound a response body by cumulative bytes and by chunk count, whichever trips first. */\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\n/** Read at most `maxBytes` of text, marking the truncation in the returned string. */\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\n/** Await a promise but surrender as soon as the signal aborts. */\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\n/** Iterate an async source under a signal, closing the iterator when it is cut short. */\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\n/** Join a base URL and a path while refusing credentials, cleartext, and origin escapes. */\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\n/** Reduce a failure to what a support report may carry: a code, a status, no prose. */\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\n/** Replace credential-bearing header values, by provenance and by name shape. */\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\n/** Local correlation id for a diagnostic record, without requiring a crypto global. */\nexport function requestLogId(): string {\n return globalThis.crypto?.randomUUID?.()\n ?? `request-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** The one shape a caller-requested cancellation takes on the way out. */\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","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","/**\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 * It lives in the transport rather than beside the generation pipeline because\n * every pipeline maps the same statuses the same way; the SSE half of generation\n * has no opinion about what a 429 means.\n *\n * @module ai-agent-sdk/providers/transport/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","/**\n * The one risky chain every HTTP pipeline in this package runs, written once.\n *\n * Everything here is a step that is invisible when it works and expensive when it\n * is missing: fusing the caller's cancellation with our own teardown controller and\n * the request deadline, bounding the outbound body, letting a diagnostic observer\n * look at the request without letting it veto dispatch, opening a provider attempt\n * before the socket and closing it exactly once afterwards, refusing a redirect\n * instead of replaying credentials to wherever it points, turning a non-2xx into a\n * stable code with `retry-after` and a request id attached, and releasing the\n * response body when the consumer walks away early.\n *\n * A second copy of this chain for embedding would be a second chance to forget one\n * of those steps — which is precisely why the chain, and not the decoding, is what\n * gets shared. What a pipeline supplies is only `decode`: what to do with a\n * response that already passed every guard above.\n *\n * The classification order at the bottom is part of the contract and is deliberately\n * not simplified: a fired deadline outranks an abort the caller did not request,\n * an aborted fused signal outranks a transport failure, and an admission refusal\n * from `startProviderAttempt` is rethrown untouched so audit mode's decision is not\n * relabelled as a transport error.\n *\n * @module ai-agent-sdk/providers/transport/session\n */\n\nimport { MODEL_ERROR_CODES, ModelError } from '@alvin0/ai-agent-sdk-core'\nimport type {\n ModelFailure,\n ModelInvocationContext,\n ProviderAttemptHandle,\n ProviderRequestId,\n SafeErrorRecord,\n UsageCounters,\n} from '@alvin0/ai-agent-sdk-core'\nimport { normalizeHttpBoundaryError } from '../common/failure.ts'\nimport type { HttpTransportConnection } from './connection.ts'\nimport {\n httpErrorCode,\n parseErrorBody,\n requestIdFrom,\n retryAfterMs,\n} from './errors.ts'\nimport {\n abortError,\n cancelResponseBody,\n endpointUrl,\n raceWithSignal,\n readBoundedText,\n redactHeaders,\n rejectProviderRedirect,\n requestLogId,\n safeProviderFailure,\n} from './http.ts'\nimport { resolveTransportLimits, type ResolvedTransportLimits } from './limits.ts'\n\n/** One serialized request body, measured before anything is sent. */\nexport interface PreparedWireBody {\n /** The value handed to the diagnostic observer; never re-serialized. */\n readonly value: unknown\n /** Exact bytes sent on the wire. */\n readonly encoded: string\n /** UTF-8 length of {@link encoded}. */\n readonly bytes: number\n}\n\n/**\n * How the transport obtains the body.\n *\n * A thunk exists because the pipeline that owns serialization also owns caching it\n * across repeated `stream()` calls on one prepared call, and because building the\n * body may itself do work that must observe the fused signal — which does not exist\n * until the transport creates it.\n */\nexport type WireBodySource =\n | PreparedWireBody\n | ((signal: AbortSignal) => PreparedWireBody | Promise<PreparedWireBody>)\n\n/**\n * One exact wire request, observed immediately before dispatch.\n *\n * Structurally identical to the generation pipeline's record, and deliberately\n * declared here so the transport does not depend on a pipeline for its own shape.\n */\nexport interface WireRequestRecord {\n readonly schemaVersion: 1\n readonly type: 'provider-request'\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 /** Credentials and cookies already replaced by `[REDACTED]`. */\n readonly headers: Readonly<Record<string, string>>\n /** The exact serialized value. This may contain prompts and tool output. */\n readonly body: unknown\n readonly bodyBytes: number\n}\n\n/** Everything the shared chain needs to issue ONE request. */\nexport interface HttpTransportRequestInput {\n /** The snapshot this request is bound to; read once, never re-read mid-request. */\n readonly connection: HttpTransportConnection\n /** Provider display name used in every message this chain raises. */\n readonly displayName: string\n /** Route being served. */\n readonly provider: string\n /** Wire model id. */\n readonly model: string\n /** Path appended to {@link HttpTransportConnection.baseUrl}. */\n readonly path: string\n /**\n * Media type this pipeline requires back.\n *\n * The transport does not enforce it — the `accept` header travels on the\n * connection snapshot and the check belongs to whoever decodes — but it is carried\n * on the session so `decode` states its expectation in one place.\n */\n readonly accept: string\n readonly body: WireBodySource\n /** The caller's cancellation, fused with the deadline and our teardown. */\n readonly signal?: AbortSignal\n readonly context?: ModelInvocationContext\n /** Override status-to-code mapping for a provider with codes of its own. */\n readonly errorCode?: (status: number, detail: string) => string\n /** Best-effort diagnostic observer; never a dispatch veto. */\n readonly observeRequest?: (record: WireRequestRecord) => Promise<void> | void\n}\n\n/** Outcome vocabulary a pipeline may report for the attempt ledger. */\nexport type TransportAttemptStatus = 'success' | 'error' | 'aborted' | 'unknown'\n\n/** A response that already cleared every transport guard, plus its ledger hooks. */\nexport interface HttpTransportSession {\n /** The response; its body is still unread and is owned by the transport. */\n readonly response: Response\n readonly url: string\n readonly origin: string\n /** Fused signal: caller + request deadline + transport teardown. */\n readonly signal: AbortSignal\n /** Provider correlation id, when the response carried one. */\n readonly providerRequestId?: ProviderRequestId\n /** Media type the pipeline asked for; see {@link HttpTransportRequestInput.accept}. */\n readonly accept: string\n readonly limits: ResolvedTransportLimits\n /**\n * Record a usage report as attempt evidence.\n *\n * Evidence only: whether a report is complete enough to leave the SDK as\n * `TokenUsage` is a pipeline decision, and this hook does not make it.\n */\n readonly attemptId?: string\n reportUsage(usage: UsageCounters, final?: boolean): void\n /** Record the terminal outcome the decoded stream reported. */\n reportOutcome(status: TransportAttemptStatus, failure?: ModelFailure): void\n}\n\n/**\n * Run one request through the shared safety chain and stream `use`'s output.\n *\n * The generator shape matters: the provider attempt stays open, and the response\n * body stays owned, for as long as the consumer keeps pulling. A consumer that\n * stops early aborts the teardown controller in `finally`, which is what tears down\n * an in-flight response instead of leaking the connection.\n * @param input - the request facts, all captured from one connection snapshot.\n * @param use - decodes a guarded response; its failures are classified here.\n * @returns whatever `use` yields, unchanged.\n */\nexport async function* withTransportSession<T>(\n input: HttpTransportRequestInput,\n use: (session: HttpTransportSession) => AsyncIterable<T>,\n): AsyncGenerator<T> {\n const { connection, context, displayName, model, provider } = input\n const callerSignal = input.signal\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 limits = resolveTransportLimits(connection)\n const timeout = AbortSignal.timeout(limits.requestTimeoutMs)\n const signal = AbortSignal.any([\n consumer.signal,\n timeout,\n ...callerSignal === undefined ? [] : [callerSignal],\n ])\n\n let admissionFailure: { readonly value: unknown } | undefined\n let ownedResponse: Response | undefined\n try {\n signal.throwIfAborted()\n const preparedBody = typeof input.body === 'function'\n ? await input.body(signal)\n : input.body\n if (preparedBody.bytes > limits.maxRequestBytes) {\n throw new ModelError(\n `${displayName} request exceeds the ${limits.maxRequestBytes}-byte limit`,\n MODEL_ERROR_CODES.INVALID_REQUEST,\n )\n }\n const endpoint = endpointUrl(\n connection.baseUrl,\n input.path,\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([\n signal,\n AbortSignal.timeout(limits.requestLoggerTimeoutMs),\n ])\n await raceWithSignal(Promise.resolve(input.observeRequest?.({\n schemaVersion: 1,\n type: 'provider-request',\n id: requestLogId(),\n timestamp: new Date().toISOString(),\n provider,\n model,\n method: 'POST',\n url,\n headers: redactHeaders(headers, connection.sensitiveHeaderNames),\n body: preparedBody.value,\n bodyBytes: preparedBody.bytes,\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: ProviderRequestId | undefined\n let attemptStatus: TransportAttemptStatus = 'unknown'\n let attemptUsage: UsageCounters | undefined\n let usageFinal = true\n let attemptError: SafeErrorRecord | undefined\n try {\n signal.throwIfAborted()\n try {\n attempt = await context?.startProviderAttempt?.({\n provider,\n model,\n method: 'POST',\n origin,\n }, signal)\n } catch (error: unknown) {\n // Audit mode refused this dispatch. That decision travels out verbatim.\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: preparedBody.encoded,\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) {\n throw await httpFailure(response, origin, limits.maxErrorBodyBytes, signal, input)\n }\n\n const session: HttpTransportSession = Object.freeze({\n response,\n url,\n origin,\n signal,\n accept: input.accept,\n limits,\n ...providerRequestId === undefined ? {} : { providerRequestId },\n reportUsage(usage: UsageCounters, final = true) {\n attemptUsage = usage\n usageFinal = final\n },\n ...(attempt === undefined ? {} : { attemptId: attempt.attemptId }),\n reportOutcome(status: TransportAttemptStatus, failure?: ModelFailure) {\n attemptStatus = status\n if (failure !== undefined) attemptError = safeProviderFailure(failure)\n },\n })\n yield* use(session)\n } catch (error: unknown) {\n if (admissionFailure !== undefined && error === admissionFailure.value) throw error\n const mapped = timeout.aborted && callerSignal?.aborted !== true\n ? new ModelError(\n `${displayName} request exceeded its ${limits.requestTimeoutMs}ms time limit`,\n MODEL_ERROR_CODES.TIMEOUT,\n { cause: error },\n )\n : signal.aborted\n ? abortError(displayName, error)\n : normalizeHttpBoundaryError(\n error,\n `${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 ...usageFinal ? {} : { usageFinal: false },\n ...httpStatus === undefined ? {} : { httpStatus },\n ...providerRequestId === undefined ? {} : { providerRequestId },\n ...attemptError === undefined ? {} : { error: attemptError },\n })\n }\n } catch (error: unknown) {\n if (callerSignal?.aborted === true) throw abortError(displayName, error)\n if (timeout.aborted) {\n throw new ModelError(\n `${displayName} request exceeded its ${limits.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, `${displayName} stream failed`)\n } finally {\n consumer.abort(new Error(`${displayName} stream consumer stopped`))\n if (ownedResponse !== undefined) await cancelResponseBody(ownedResponse)\n }\n}\n\n/**\n * Turn a non-2xx response into a fully populated {@link ModelError}.\n *\n * The body is read under the same bound and the same signal as everything else,\n * and a body that cannot be read does not replace the status — the status is the\n * more reliable signal of the two anyway.\n * @param response - the non-success response.\n * @param origin - request origin, reported in the message instead of the full URL.\n * @param maxBytes - error-body bound from the resolved limits.\n * @param signal - the fused signal.\n * @param input - request facts, for the display name and code override.\n * @returns the mapped error, carrying status, `retry-after`, and request id.\n */\nasync function httpFailure(\n response: Response,\n origin: string,\n maxBytes: number,\n signal: AbortSignal,\n input: HttpTransportRequestInput,\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 ?? `${input.displayName} error (HTTP ${response.status}) from ${origin}`,\n (input.errorCode ?? httpErrorCode)(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 * The streaming pipeline's entry into the shared transport chain.\n *\n * Two properties define it, and both are about what happens while a consumer is\n * still pulling. The provider attempt stays open for the whole stream, because a\n * stream that fails halfway through is one attempt with a failure — not a success\n * followed by a mystery. And every pull is raced against the fused signal, so a\n * decoder that blocks on a provider which has stopped sending still surrenders when\n * the caller aborts, the deadline fires, or the consumer walks away.\n *\n * What `decode` sees is a response that already cleared every guard in\n * {@link withTransportSession}: bounded body, no redirect, 2xx, attempt open. What\n * it owns is the format — media type, framing, termination.\n *\n * @module ai-agent-sdk/providers/transport/stream\n */\n\nimport { withAbortSignal } from './http.ts'\nimport {\n withTransportSession,\n type HttpTransportRequestInput,\n type HttpTransportSession,\n} from './session.ts'\n\n/**\n * Send one request and stream whatever `decode` makes of the response.\n *\n * @param input - request facts captured from one connection snapshot.\n * @param decode - turns a guarded response into the pipeline's own values.\n * @returns the decoded values, with the attempt held open until iteration ends.\n */\nexport function transportStream<T>(\n input: HttpTransportRequestInput,\n decode: (session: HttpTransportSession) => AsyncIterable<T>,\n): AsyncGenerator<T> {\n return withTransportSession(\n input,\n session => withAbortSignal(decode(session), session.signal),\n )\n}\n","import type { ResolvedModelInfo } from '@alvin0/ai-agent-sdk-core'\nimport type { ProviderCatalogModel } from './http-adapter.ts'\n\n/** Context facts only: never advertises models or guesses their capabilities. */\nexport interface ModelContextPolicy {\n readonly defaultContextWindow: number\n readonly maxContextWindow?: number\n readonly standardPriceInputTokens?: number\n}\n\nexport interface ModelContextPolicyOptions {\n readonly baseUrl?: string\n readonly models?: readonly ProviderCatalogModel[]\n readonly defaultContextWindow?: number\n}\n\nexport function applyModelContextPolicy(\n info: ResolvedModelInfo,\n policy: ModelContextPolicy | undefined,\n configured?: ProviderCatalogModel,\n providerOverride?: number,\n): ResolvedModelInfo {\n const defaultContextWindow = configured?.defaultContextWindow ?? policy?.defaultContextWindow ?? info.context?.defaultContextWindow\n const knownMaximum = policy?.maxContextWindow ?? info.context?.maxContextWindow\n const maxContextWindow = knownMaximum === undefined\n ? configured?.maxContextWindow\n : Math.min(knownMaximum, configured?.maxContextWindow ?? knownMaximum)\n const standardPriceInputTokens = configured?.standardPriceInputTokens ?? policy?.standardPriceInputTokens ?? info.context?.standardPriceInputTokens\n const contextWindow = configured?.contextWindow ?? providerOverride ?? defaultContextWindow ?? info.context?.contextWindow\n for (const [name, value] of Object.entries({ contextWindow, defaultContextWindow, maxContextWindow, standardPriceInputTokens })) {\n if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {\n throw new TypeError(`${name} must be a positive safe integer`)\n }\n }\n if (maxContextWindow !== undefined && (\n (contextWindow !== undefined && contextWindow > maxContextWindow)\n || (defaultContextWindow !== undefined && defaultContextWindow > maxContextWindow)\n )) throw new RangeError('contextWindow exceeds maxContextWindow')\n if (contextWindow === undefined) return info\n return { ...info, context: {\n contextWindow,\n ...(defaultContextWindow === undefined ? {} : { defaultContextWindow }),\n ...(maxContextWindow === undefined ? {} : { maxContextWindow }),\n ...(standardPriceInputTokens === undefined ? {} : { standardPriceInputTokens }),\n ...(standardPriceInputTokens !== undefined && contextWindow > standardPriceInputTokens\n ? { pricingWarning: 'extended-context-may-cost-more' as const } : {}),\n } }\n}\n\n/** Capture configuration so later caller mutations cannot change model resolution. */\nexport function createModelContextPolicy(\n policies: Readonly<Record<string, ModelContextPolicy>>,\n models: readonly ProviderCatalogModel[] | undefined,\n providerOverride?: number,\n): (info: ResolvedModelInfo) => ResolvedModelInfo {\n const captured = structuredClone(policies)\n const configured = structuredClone(models ?? [])\n return info => applyModelContextPolicy(info,\n Object.hasOwn(captured, info.id) ? captured[info.id] : undefined,\n configured.find(model => model.id === info.id), providerOverride)\n}\n","/**\n * Generation's transport facade: the catalog helpers, plus the shared primitives\n * at the path existing callers already import.\n *\n * The pipeline-independent half moved to {@link ../transport/http} and\n * {@link ../transport/limits} when the transport layer was split out, so a second\n * pipeline could reuse it without importing the generation pipeline. What stays\n * here is what genuinely belongs to generation: turning an advisory model catalog\n * into model metadata.\n *\n * @module ai-agent-sdk/providers/base/transport\n */\n\nimport type { ModelInfo, ResolvedModelInfo } from '@alvin0/ai-agent-sdk-core'\nimport type { ProviderCatalogModel } from './http-adapter.ts'\nimport { applyModelContextPolicy } from './context-policy.ts'\n\n/** Shared HTTP primitives live in the transport; re-exported for existing callers. */\nexport {\n abortError,\n boundedResponseBody,\n cancelResponseBody,\n endpointUrl,\n raceWithSignal,\n readBoundedText,\n redactHeaders,\n rejectProviderRedirect,\n requestLogId,\n safeProviderFailure,\n withAbortSignal,\n} from '../transport/http.ts'\n/** Bound validation belongs to the transport limits module; re-exported for existing callers. */\nexport { positiveFinite, positiveInteger } from '../transport/limits.ts'\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 applyModelContextPolicy({\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?.defaultMaxTokens ?? configured?.maxTokens ?? defaultMaxTokens,\n ...(configured?.maxTokens === undefined ? {} : { maxOutputTokens: configured.maxTokens }),\n ...(configured?.reasoning === undefined ? {} : { reasoning: configured.reasoning }),\n ...(configured?.outputModalities === undefined ? {} : { outputModalities: configured.outputModalities }),\n }, undefined, configured)\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 * The risky half of that list — signal fusion, request bounds, the diagnostic\n * observer, attempt accounting, redirect refusal, status mapping, teardown — now\n * lives in {@link ../transport/session.withTransportSession} so a second pipeline\n * cannot reimplement it slightly differently. What stays in this file is what is\n * genuinely generation's: the modality guard, the catalog, the serialized-body\n * cache for one prepared call, and {@link HttpModelAdapter.decodeSse} — the SSE\n * half, unchanged, applied to a response that already cleared every guard.\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 { NativeToolName } from '@alvin0/ai-agent-sdk-core'\nimport { MODEL_ERROR_CODES, ModelError } from '@alvin0/ai-agent-sdk-core'\nimport { contentHasDocument, 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 { TokenUsage } 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 { captureTransportConnection, type HttpTransportConnection } from '../transport/connection.ts'\nimport { positiveInteger } from '../transport/limits.ts'\nimport type { HttpTransportSession, PreparedWireBody } from '../transport/session.ts'\nimport { transportStream } from '../transport/stream.ts'\nimport { httpErrorCode } from './http-errors.ts'\nimport {\n boundedResponseBody,\n catalogModelInfo,\n raceWithSignal,\n resolvedCatalogModelInfo,\n} from './transport.ts'\n\nexport { redactHeaders } from './transport.ts'\nexport {\n DEFAULT_MAX_ERROR_BODY_BYTES,\n DEFAULT_MAX_REQUEST_BYTES,\n DEFAULT_MAX_RESPONSE_BYTES,\n DEFAULT_MAX_RESPONSE_CHUNKS,\n DEFAULT_REQUEST_LOGGER_TIMEOUT_MS,\n DEFAULT_REQUEST_TIMEOUT_MS,\n} from '../transport/limits.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\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 /** Standard-price operating budget before a contextWindow override. */\n defaultContextWindow?: number\n /** Known technical ceiling; overrides cannot exceed it. */\n maxContextWindow?: number\n /** Input-token threshold for long-context pricing, when known. */\n standardPriceInputTokens?: number\n /** Per-request output cap for this model. */\n maxTokens?: number\n /** Default output budget, independently of the ceiling. Falls back to maxTokens. */\n defaultMaxTokens?: 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 generation request, captured as a single snapshot.\n *\n * The transport half — endpoint, headers, bounds, retry policy — is\n * {@link HttpTransportConnection} and is shared with every other pipeline in this\n * package. What this interface adds is the part only generation has: the SSE\n * decoding bounds and the advisory model catalog. The field set and the optionality\n * of every field are unchanged from before the split, so existing provider\n * configurations satisfy it exactly as they did.\n *\n * The catalog stays here deliberately. Embedding routes carry a catalog with\n * different semantics, and folding the two into one shape is precisely the\n * conflation this split avoids.\n */\nexport interface HttpConnection extends HttpTransportConnection {\n /** Maximum idle interval while a read is outstanding. */\n readonly streamIdleTimeoutMs: 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 /** 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\n/**\n * The serialized body of ONE prepared call, kept across repeated `stream()` calls.\n *\n * This stays with the pipeline rather than moving into the transport: the transport\n * issues one request and has no notion of a prepared call to cache against, and a\n * cache that outlived a request would be a way for one call's body to reach another\n * call's wire.\n */\ninterface PreparedWireBodyCache {\n prepared?: Promise<PreparedWireBody>\n}\n\n/** The decoding bounds the SSE pipeline adds on top of the transport's. */\ninterface ResolvedSseLimits {\n /** Maximum decoded SSE events accepted from one response. */\n readonly maxEvents: number\n /** Maximum characters accepted in one decoded SSE event. */\n readonly maxEventChars: number\n}\n\n/**\n * Resolve the SSE bounds before any transport work starts.\n *\n * Deliberately validated in the pipeline and not inside `decodeSse`: an\n * unusable bound is a configuration error, and configuration errors must not\n * arrive after a provider attempt has been opened and a request sent.\n * @param connection - the snapshot this call is bound to.\n * @returns defaulted, validated event bounds.\n */\nfunction resolveSseLimits(connection: HttpConnection): ResolvedSseLimits {\n return Object.freeze({\n maxEvents: positiveInteger(\n connection.maxSseEvents ?? DEFAULT_MAX_SSE_EVENTS,\n 'maxSseEvents',\n ),\n maxEventChars: positiveInteger(\n connection.maxSseEventChars ?? DEFAULT_MAX_SSE_EVENT_CHARS,\n 'maxSseEventChars',\n ),\n })\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 return captureTransportConnection(connection, this.baseHeaders())\n }\n\n /**\n * The generation pipeline: guard the modalities, then hand one request to the\n * shared transport chain with SSE decoding as its only pipeline-specific part.\n *\n * Still a generator, and deliberately so: the modality guard, the body\n * serialization and every transport step stay lazy until a consumer pulls, which\n * is the behaviour every existing caller of `stream()` already relies on.\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 if (options.messages.some(message => contentHasDocument(message.content))\n && model.inputModalities?.includes('document') !== true) {\n throw new ModelError(\n `${this.displayName} model \"${options.model}\" does not accept document 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 const sseLimits = resolveSseLimits(connection)\n const adapter = this\n yield* transportStream<StreamChunk>({\n connection,\n displayName: this.displayName,\n provider: options.provider,\n model: options.model,\n accept: 'text/event-stream',\n /**\n * Read by the transport AFTER the body is prepared, which is exactly where\n * the pipeline used to call it. A provider whose path computation fails\n * therefore still fails inside the transport's classification, and a\n * protocol that reports its routing decision from `endpointPath` still\n * reports it once, in the same place in the sequence, as before.\n */\n get path(): string {\n return adapter.endpointPath(request)\n },\n // The transport bounds and rejects this body; the cache that keeps it across\n // repeated `stream()` calls on one prepared call belongs to the pipeline.\n body: signal => wireBodyCache.prepared ??= this.prepareWireBody(request, signal),\n ...options.signal === undefined ? {} : { signal: options.signal },\n ...context === undefined ? {} : { context },\n errorCode: (status, detail) => this.providerErrorCode(status, detail),\n observeRequest: record => this.observeRequest(record),\n }, session => this.decodeSse(session, request, sseLimits))\n }\n\n /**\n * The SSE half: media type, bounds, idle deadline, translation, usage honesty.\n *\n * Everything this sees has already cleared the transport's guards — 2xx, no\n * redirect, attempt open, teardown owned — so what remains is only the format.\n * Abort racing is not repeated here: {@link transportStream} already iterates\n * this generator under the fused signal.\n * @param session - the guarded response and its attempt-evidence hooks.\n * @param request - the request this response answers.\n * @param sse - event bounds resolved before any transport work began.\n * @returns the provider's chunks, with incomplete usage held back.\n */\n private async * decodeSse(\n session: HttpTransportSession,\n request: ProviderRequest,\n sse: ResolvedSseLimits,\n ): AsyncGenerator<StreamChunk> {\n const response = session.response\n const mediaType = response.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase()\n if (mediaType !== session.accept) {\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 maxResponseBytes = session.limits.maxResponseBytes\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 request.connection.streamIdleTimeoutMs,\n this.displayName,\n 30_000,\n )\n const events = parseSseBounded(boundedResponseBody(\n response.body,\n maxResponseBytes,\n session.limits.maxResponseChunks,\n this.displayName,\n session.signal,\n ), idleDeadline.activity, 30_000, {\n maxEvents: sse.maxEvents,\n maxEventChars: sse.maxEventChars,\n })\n const translated = requireTerminalFinish(this.translate(events, request), this.displayName)\n for await (const chunk of idleDeadline.guard(translated)) {\n if (chunk.type === 'usage-progress') {\n session.reportUsage(chunk.usage, false)\n const validated = validateUsageCounters(chunk.usage, true)\n if (Object.keys(validated.reported).length > 0) {\n yield { type: 'usage-progress', usage: validated.reported,\n ...(session.attemptId === undefined ? {} : { attemptId: session.attemptId }) }\n }\n continue\n }\n if (chunk.type === 'usage') {\n session.reportUsage(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 const status = chunk.reason.kind === 'aborted' ? 'aborted'\n : chunk.reason.kind === 'error' ? 'error' : 'success'\n session.reportOutcome(\n status,\n chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted'\n ? chunk.reason.failure\n : undefined,\n )\n }\n yield chunk\n }\n }\n\n private async prepareWireBody(\n request: ProviderRequest,\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 return Object.freeze({ value, encoded, bytes })\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","/**\n * Embedding's half of a connection snapshot, plus the one translation from a\n * declared route catalog into `Embedding_Catalog` capabilities.\n *\n * This module sits on top of {@link HttpTransportConnection} rather than inside\n * it: the transport and the JSON pipeline know nothing about embedding\n * vocabulary, and they must not, or a second pipeline could not exist without\n * dragging the first one's catalog along. What embedding adds is a catalog with\n * its own semantics — vector widths, batch ceilings, purpose handling, and a\n * declaration about which embedding space the vectors belong to.\n *\n * The translation rule has exactly one shape and it runs in one direction: a\n * field the configuration DECLARES becomes `supported`, a field it OMITS becomes\n * `unknown` (Requirement 10.5). Nothing here manufactures a `supported` value\n * from a default, because a default is the SDK's opinion, not the route's claim,\n * and `unknown` is never a reason to reject a request.\n *\n * Two things are deliberately NOT here:\n *\n * - Cleartext HTTP handling. `EmbeddingHttpConnection` extends the transport\n * snapshot, so `allowInsecureHttp` is the same field the same `endpointUrl()`\n * already enforces for generation — a self-hosted `http://` endpoint is\n * rejected unless the caller opts in explicitly, and embedding gets that for\n * free rather than through a second copy of the rule (Requirement 15.5).\n * - The generation catalog. `models`, `defaultMaxTokens` and\n * `defaultContextWindow` stay on `HttpConnection`; folding the two catalogs\n * into one shape is the conflation Requirement 10.1 rules out.\n *\n * @module ai-agent-sdk/providers/transport/embedding-connection\n */\n\nimport {\n type EmbeddingCapability,\n type EmbeddingModelInfo,\n type EmbeddingNormalization,\n type EmbeddingPurposeHandling,\n type ResolvedEmbeddingModelInfo,\n unknownEmbeddingModel,\n} from '@alvin0/ai-agent-sdk-core/embedding'\nimport type { HttpTransportConnection } from './connection.ts'\n\n/**\n * One embedding model an HTTP route declares.\n *\n * Every capability field is optional but one: {@link compatibilityIdentity}. A\n * vector is only meaningful next to another vector from the same space, and no\n * amount of matching dimension counts establishes that. Requiring the claim in\n * the type means a self-hosted \"OpenAI-compatible\" endpoint is a tested profile\n * someone declared, not an assumption drawn from the endpoint having an\n * `/embeddings` path (Requirement 15.3).\n */\nexport interface EmbeddingCatalogModel {\n /** Wire model id, passed to the provider verbatim. */\n readonly id: string\n /** Selector label; defaults to {@link id}. */\n readonly name?: string\n /** Optional detail distinguishing similar variants. */\n readonly description?: string\n /** Selectable vector widths this route accepts. */\n readonly dimensions?: readonly number[]\n /** Width used when the caller requests none. */\n readonly defaultDimensions?: number\n /** Per-input token ceiling. Only a declared value may reject an input. */\n readonly maxInputTokens?: number\n /** Items accepted in one physical batch. */\n readonly maxBatchItems?: number\n /** Estimated tokens accepted in one physical batch. */\n readonly maxBatchTokens?: number\n /** Payload bytes accepted in one physical batch. */\n readonly maxBatchBytes?: number\n /**\n * How this route expresses purpose on the wire.\n *\n * `'unsupported'` is the positive negative claim — the route states it has no\n * mechanism, which is what OpenAI's embeddings API is — and it is distinct\n * from omitting the field, which claims nothing. Either way the adapter sends\n * the text verbatim and never invents an undocumented prefix.\n */\n readonly purposeHandling?: EmbeddingPurposeHandling | 'unsupported'\n /** Whether vectors arrive normalized. Never inferred from dimension count. */\n readonly normalization?: EmbeddingNormalization\n /**\n * The route's explicit declaration about the embedding space.\n *\n * Required, including for a self-hosted endpoint. Models sharing a declared\n * space share this string; a new model generation gets a new one even when the\n * vector width is unchanged.\n */\n readonly compatibilityIdentity: string\n}\n\n/**\n * Everything needed to issue ONE embedding request, captured as a single snapshot.\n *\n * The transport half — endpoint, headers, bounds, cleartext opt-in, retry\n * policy — is {@link HttpTransportConnection} and is shared with the generation\n * pipeline verbatim. Both `OpenAI_Embedding_Adapter` and\n * `Gemini_Embedding_Adapter` are configured through this one shape.\n */\nexport interface EmbeddingHttpConnection extends HttpTransportConnection {\n /** Advisory catalog; requests are never restricted to it. */\n readonly models: readonly EmbeddingCatalogModel[]\n}\n\n/** The `unknown` capability, shared so translations need not re-allocate it. */\nconst UNKNOWN: EmbeddingCapability<never> = Object.freeze({ state: 'unknown' })\n\n/** The `unsupported` capability, for a route's positive negative claim. */\nconst UNSUPPORTED: EmbeddingCapability<never> = Object.freeze({ state: 'unsupported' })\n\n/** Declared value becomes `supported`; omission stays `unknown`. */\nfunction declared<T>(value: T | undefined): EmbeddingCapability<T> {\n return value === undefined ? UNKNOWN : Object.freeze({ state: 'supported' as const, value })\n}\n\n/** The one place `'unsupported'` is separated from an omitted declaration. */\nfunction declaredPurpose(\n value: EmbeddingCatalogModel['purposeHandling'],\n): EmbeddingCapability<EmbeddingPurposeHandling> {\n if (value === undefined) return UNKNOWN\n return value === 'unsupported' ? UNSUPPORTED : Object.freeze({ state: 'supported', value })\n}\n\n/**\n * Translate one declared catalog entry into `Embedding_Catalog` metadata.\n *\n * `inputTypes` and `representation` come out `unknown` rather than filled in\n * from the v1 scope: the scope is already readable from the types\n * (`EmbeddingInputType` is `'text'`, `EmbeddingRepresentation` is\n * `'dense-float32'`), and stating `supported` on the route's behalf would be\n * the SDK asserting a claim the route never made.\n * @param provider - route that owns the entry.\n * @param model - the declared catalog entry.\n * @returns advisory embedding metadata for this entry.\n */\nexport function embeddingCatalogModelInfo(\n provider: string,\n model: EmbeddingCatalogModel,\n): EmbeddingModelInfo {\n return {\n provider,\n id: model.id,\n name: model.name ?? model.id,\n ...(model.description === undefined ? {} : { description: model.description }),\n inputTypes: UNKNOWN,\n representation: UNKNOWN,\n dimensions: declared(model.dimensions),\n defaultDimensions: declared(model.defaultDimensions),\n maxInputTokens: declared(model.maxInputTokens),\n maxBatchItems: declared(model.maxBatchItems),\n maxBatchTokens: declared(model.maxBatchTokens),\n maxBatchBytes: declared(model.maxBatchBytes),\n purposeHandling: declaredPurpose(model.purposeHandling),\n normalization: declared(model.normalization),\n compatibilityIdentity: declared(model.compatibilityIdentity),\n }\n}\n\n/**\n * Resolve exact embedding metadata for a model id from an advisory catalog.\n *\n * An id the catalog does not describe stays usable: the caller gets an\n * identity-only descriptor with every capability `unknown` and the provider\n * decides (Requirement 10.3). The catalog restricting the request would make\n * membership authoritative, which it is not.\n * @param provider - route being resolved.\n * @param modelId - requested model id.\n * @param models - the route's declared catalog.\n * @returns exact metadata for the id, or the identity-only descriptor.\n */\nexport function resolvedEmbeddingCatalogModelInfo(\n provider: string,\n modelId: string,\n models: readonly EmbeddingCatalogModel[],\n): ResolvedEmbeddingModelInfo {\n const configured = models.find(entry => entry.id === modelId)\n if (configured === undefined) return unknownEmbeddingModel(provider, modelId)\n return embeddingCatalogModelInfo(provider, configured)\n}\n","/**\n * The JSON pipeline's entry into the shared transport chain.\n *\n * Where the streaming pipeline keeps a provider attempt open for as long as a\n * consumer keeps pulling, this one has a single, bounded shape: read the whole body\n * under the configured byte and chunk bounds, parse it, hand the parsed value to\n * `decode`, close the attempt. There is no framing to track and no idle deadline to\n * enforce, because there is nothing to wait for between events.\n *\n * Three failures are stated rather than inferred, since each one has a\n * plausible-looking wrong answer:\n *\n * - A response whose media type is not JSON is refused with a code of its own\n * ({@link HTTP_PROVIDER_ERROR_CODES.JSON_MEDIA_TYPE_INVALID}), symmetric with the\n * SSE check. Parsing an HTML error page as if it were the provider's answer is how\n * a proxy outage becomes a mysterious schema error further up.\n * - A body past `maxResponseBytes` is a transport failure, the same as on the SSE\n * path, and is refused instead of truncated: half a JSON document is not data.\n * - A body that is not valid JSON is a protocol failure, never something to guess\n * at.\n *\n * What `decode` receives is a response that already cleared every guard in\n * {@link withTransportSession} — 2xx, no redirect, attempt open, teardown owned —\n * plus a parsed body. What it owns is the schema.\n *\n * @module ai-agent-sdk/providers/transport/json\n */\n\nimport { MODEL_ERROR_CODES, ModelError } from '@alvin0/ai-agent-sdk-core'\nimport { HTTP_PROVIDER_ERROR_CODES } from '../common/config.ts'\nimport { boundedResponseBody, raceWithSignal } from './http.ts'\nimport {\n withTransportSession,\n type HttpTransportRequestInput,\n type HttpTransportSession,\n} from './session.ts'\n\n/** Media types this pipeline accepts back from a provider. */\nexport const JSON_MEDIA_TYPES = Object.freeze(['application/json'] as const)\n\n/**\n * Send one request, read its JSON body under bound, and return `decode`'s value.\n *\n * The attempt closes as soon as the value is produced; nothing here stays open for\n * a consumer, because the whole response is already in memory by then.\n * @param input - request facts captured from one connection snapshot.\n * @param decode - turns a parsed body into the pipeline's own value.\n * @returns whatever `decode` returns.\n */\nexport async function transportJson<T>(\n input: HttpTransportRequestInput,\n decode: (session: HttpTransportSession, body: unknown) => T | Promise<T>,\n): Promise<T> {\n const decoded: { value: T }[] = []\n // `break` closes the generator, which is what runs the shared `finally`:\n // attempt accounting, consumer teardown, response-body release.\n for await (const value of withTransportSession(input, async function* (session) {\n const body = parseJsonBody(\n await readBoundedBody(session, input.displayName),\n input.displayName,\n )\n const result = await decode(session, body)\n // A value returned from `decode` is what a successful attempt looks like.\n session.reportOutcome('success')\n yield result\n })) {\n decoded.push({ value })\n break\n }\n const first = decoded[0]\n if (first === undefined) {\n throw new ModelError(\n `${input.displayName} produced no JSON response`,\n MODEL_ERROR_CODES.MALFORMED_RESPONSE,\n )\n }\n return first.value\n}\n\n/** True when a `content-type` value names one of {@link JSON_MEDIA_TYPES}. */\nexport function isJsonMediaType(contentType: string | null): boolean {\n const mediaType = contentType?.split(';', 1)[0]?.trim().toLowerCase()\n if (mediaType === undefined) return false\n return (JSON_MEDIA_TYPES as readonly string[]).includes(mediaType)\n}\n\n/**\n * Read the whole body as text, refusing anything past the configured bounds.\n *\n * The declared `content-length` is checked first so an oversized response is\n * refused before a single byte of it is buffered; the streaming bound still applies\n * afterwards, because the header is a claim and not a guarantee.\n * @param session - the guarded response and its resolved limits.\n * @param displayName - provider name used in every message raised here.\n * @returns the exact body text.\n */\nasync function readBoundedBody(\n session: HttpTransportSession,\n displayName: string,\n): Promise<string> {\n const response = session.response\n if (!isJsonMediaType(response.headers.get('content-type'))) {\n throw new ModelError(\n `${displayName} response is not ${JSON_MEDIA_TYPES.join(' or ')}`,\n HTTP_PROVIDER_ERROR_CODES.JSON_MEDIA_TYPE_INVALID,\n )\n }\n if (response.body === null) {\n throw new ModelError(\n `${displayName} returned no response body`,\n MODEL_ERROR_CODES.MALFORMED_RESPONSE,\n )\n }\n\n const maxResponseBytes = session.limits.maxResponseBytes\n const declaredLength = response.headers.get('content-length')\n if (declaredLength !== null && /^\\d+$/.test(declaredLength)\n && Number(declaredLength) > maxResponseBytes) {\n throw new ModelError(\n `${displayName} response exceeds the ${maxResponseBytes}-byte limit`,\n MODEL_ERROR_CODES.TRANSPORT,\n )\n }\n\n const reader = boundedResponseBody(\n response.body,\n maxResponseBytes,\n session.limits.maxResponseChunks,\n displayName,\n session.signal,\n ).getReader()\n const decoder = new TextDecoder()\n let text = ''\n try {\n while (true) {\n const { done, value } = await raceWithSignal(reader.read(), session.signal)\n if (done) break\n if (value === undefined) continue\n text += decoder.decode(value, { stream: true })\n }\n return text + decoder.decode()\n } finally {\n reader.releaseLock()\n }\n}\n\n/** Parse a body, turning a parse failure into a protocol error rather than a guess. */\nfunction parseJsonBody(text: string, displayName: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error: unknown) {\n throw new ModelError(\n `${displayName} response body is not valid JSON`,\n MODEL_ERROR_CODES.MALFORMED_RESPONSE,\n { cause: error },\n )\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,yBAAyB;CACzB,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;;;;;ACnCD,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,YA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QAAQ,OAAO,mBACf,aACA,QAAQ,MACV,CAAC,CAAC,UAAU;CACZ,MAAM,UAAU,IAAI,YAAY;CAChC,IAAI,OAAO;CACX,IAAI;EACF,OAAO,MAAM;GACX,MAAM,EAAE,MAAM,UAAU,MAAM,eAAe,OAAO,KAAK,GAAG,QAAQ,MAAM;GAC1E,IAAI,MAAM;GACV,IAAI,UAAU,QAAW;GACzB,QAAQ,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;EAChD;EACA,OAAO,OAAO,QAAQ,OAAO;CAC/B,UAAU;EACR,OAAO,YAAY;CACrB;AACF;;AAGA,SAAS,cAAc,MAAc,aAA8B;CACjE,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,SAAS,OAAgB;EACvB,MAAM,IAAI,WACR,GAAG,YAAY,mCACf,kBAAkB,oBAClB,EAAE,OAAO,MAAM,CACjB;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["positiveFinite","ENCODER"],"sources":["../src/common/config.ts","../src/stream/parser.ts","../src/stream/config.ts","../src/stream/idle-deadline.ts","../src/stream/terminal.ts","../src/common/header-layers.ts","../src/transport/connection.ts","../src/transport/limits.ts","../src/transport/http.ts","../src/common/failure.ts","../src/transport/errors.ts","../src/transport/session.ts","../src/transport/stream.ts","../src/base/context-policy.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","../src/common/endpoint-headers.ts","../src/transport/embedding-connection.ts","../src/transport/json.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 JSON_MEDIA_TYPE_INVALID: 'HTTP_JSON_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 { 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 connection snapshot every HTTP pipeline in this package shares.\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 operation, makes that impossible.\n *\n * What lives here is only what a request needs regardless of what comes back:\n * where to send it, with what credentials, under what bounds, and with which retry\n * policy. A pipeline's own vocabulary stays with the pipeline — the generation\n * catalog is on {@link ../base/http-adapter.HttpConnection}, and the embedding\n * catalog will be on its own extension, because merging the two catalogs is\n * exactly the mistake that makes one model shape stand in for another.\n *\n * @module ai-agent-sdk/providers/transport/connection\n */\n\nimport { attributionHeaders, type ResolvedRetryPolicy } from '@alvin0/ai-agent-sdk-core'\nimport { mergeHeaderLayers } from '../common/header-layers.ts'\n\n/** The transport-shared half of a connection snapshot. */\nexport interface HttpTransportConnection {\n /** Endpoint base; the pipeline's endpoint path is appended. */\n readonly baseUrl: string\n /**\n * Every header for the request, INCLUDING authorization.\n *\n * Resolved together with the endpoint so the credential travels with the URL it\n * will be sent to. The transport 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 /** 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 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}\n\n/**\n * Merge the transport's own header layer beneath the snapshot's auth layer, once.\n *\n * Layer ownership is what makes this safe to call on a snapshot a subclass or a\n * configuration produced: a transport header can never silently overwrite a\n * credential, and the names the auth layer marked sensitive survive the merge so\n * redaction still covers them.\n *\n * A snapshot that already carries every layer — which configured adapters return —\n * passes an empty transport layer and is returned untouched, so capturing twice\n * cannot re-apply attribution.\n * @param connection - the snapshot captured for this operation.\n * @param transportHeaders - the transport layer to merge underneath; may be empty.\n * @returns the snapshot with merged headers and the union of sensitive names.\n */\nexport function captureTransportConnection<T extends HttpTransportConnection>(\n connection: T,\n transportHeaders: Readonly<Record<string, string>>,\n): T {\n if (Reflect.ownKeys(transportHeaders).length === 0) return connection\n const merged = mergeHeaderLayers([\n { layer: 'transport', headers: transportHeaders },\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 * Transport limits: the numbers that bound ONE HTTP request, wherever it goes.\n *\n * These belong to the transport rather than to a pipeline because every pipeline\n * needs exactly the same bounds — how big a request may be, how much of a\n * response may be read, how long a diagnostic observer may hold up dispatch.\n * A pipeline adds its own decoding limits on top (the SSE pipeline bounds events\n * and event characters); it does not redefine these.\n *\n * @module ai-agent-sdk/providers/transport/limits\n */\n\nimport type { HttpTransportConnection } from './connection.ts'\n\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\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\n/**\n * Every transport bound for one request, defaulted and validated exactly once.\n *\n * Resolved from the connection snapshot, so a configuration change between two\n * reads cannot move a bound mid-request.\n */\nexport interface ResolvedTransportLimits {\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 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}\n\n/**\n * Apply defaults and reject nonsense bounds before any I/O happens.\n *\n * Validation order is fixed and part of the contract: a configuration with two\n * invalid bounds always reports the earlier field, so the error a caller sees does\n * not depend on which limit the pipeline happens to consult first.\n * @param connection - the captured snapshot this request is bound to.\n * @returns fully resolved bounds; never partially defaulted.\n */\nexport function resolveTransportLimits(\n connection: HttpTransportConnection,\n): ResolvedTransportLimits {\n return Object.freeze({\n requestTimeoutMs: positiveFinite(\n connection.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs',\n ),\n maxRequestBytes: positiveInteger(\n connection.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES,\n 'maxRequestBytes',\n ),\n maxResponseBytes: positiveInteger(\n connection.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,\n 'maxResponseBytes',\n ),\n maxResponseChunks: positiveInteger(\n connection.maxResponseChunks ?? DEFAULT_MAX_RESPONSE_CHUNKS,\n 'maxResponseChunks',\n ),\n maxErrorBodyBytes: positiveInteger(\n connection.maxErrorBodyBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES,\n 'maxErrorBodyBytes',\n ),\n requestLoggerTimeoutMs: positiveFinite(\n connection.requestLoggerTimeoutMs ?? DEFAULT_REQUEST_LOGGER_TIMEOUT_MS,\n 'requestLoggerTimeoutMs',\n ),\n })\n}\n","/**\n * The pipeline-independent HTTP primitives the shared chain is built from.\n *\n * Each one exists because the obvious version of it is wrong in a way that only\n * shows up under failure: a body read without a byte bound is a memory bug waiting\n * for a hostile response, a promise raced against a signal that disposes nothing\n * leaks a socket, a redirect followed once is a credential sent somewhere the\n * caller never named, and an iterator abandoned without `return()` leaves a reader\n * locked forever.\n *\n * None of it knows anything about SSE, JSON, catalogs, or model shapes — which is\n * why it sits under the transport and not beside a pipeline.\n *\n * @module ai-agent-sdk/providers/transport/http\n */\n\nimport {\n MODEL_ERROR_CODES,\n ModelError,\n waitForSettlement,\n type ModelFailure,\n type SafeErrorRecord,\n} from '@alvin0/ai-agent-sdk-core'\nimport { HTTP_PROVIDER_ERROR_CODES } from '../common/config.ts'\nimport { isSensitiveHeaderName } from '../common/header-layers.ts'\n\n/** Bound a response body by cumulative bytes and by chunk count, whichever trips first. */\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\n/** Read at most `maxBytes` of text, marking the truncation in the returned string. */\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\n/** Await a promise but surrender as soon as the signal aborts. */\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\n/** Iterate an async source under a signal, closing the iterator when it is cut short. */\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\n/** Join a base URL and a path while refusing credentials, cleartext, and origin escapes. */\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\n/** Reduce a failure to what a support report may carry: a code, a status, no prose. */\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\n/** Replace credential-bearing header values, by provenance and by name shape. */\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\n/** Local correlation id for a diagnostic record, without requiring a crypto global. */\nexport function requestLogId(): string {\n return globalThis.crypto?.randomUUID?.()\n ?? `request-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** The one shape a caller-requested cancellation takes on the way out. */\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","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","/**\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 * It lives in the transport rather than beside the generation pipeline because\n * every pipeline maps the same statuses the same way; the SSE half of generation\n * has no opinion about what a 429 means.\n *\n * @module ai-agent-sdk/providers/transport/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","/**\n * The one risky chain every HTTP pipeline in this package runs, written once.\n *\n * Everything here is a step that is invisible when it works and expensive when it\n * is missing: fusing the caller's cancellation with our own teardown controller and\n * the request deadline, bounding the outbound body, letting a diagnostic observer\n * look at the request without letting it veto dispatch, opening a provider attempt\n * before the socket and closing it exactly once afterwards, refusing a redirect\n * instead of replaying credentials to wherever it points, turning a non-2xx into a\n * stable code with `retry-after` and a request id attached, and releasing the\n * response body when the consumer walks away early.\n *\n * A second copy of this chain for embedding would be a second chance to forget one\n * of those steps — which is precisely why the chain, and not the decoding, is what\n * gets shared. What a pipeline supplies is only `decode`: what to do with a\n * response that already passed every guard above.\n *\n * The classification order at the bottom is part of the contract and is deliberately\n * not simplified: a fired deadline outranks an abort the caller did not request,\n * an aborted fused signal outranks a transport failure, and an admission refusal\n * from `startProviderAttempt` is rethrown untouched so audit mode's decision is not\n * relabelled as a transport error.\n *\n * @module ai-agent-sdk/providers/transport/session\n */\n\nimport { MODEL_ERROR_CODES, ModelError } from '@alvin0/ai-agent-sdk-core'\nimport type {\n ModelFailure,\n ModelInvocationContext,\n ProviderAttemptHandle,\n ProviderRequestId,\n SafeErrorRecord,\n UsageCounters,\n} from '@alvin0/ai-agent-sdk-core'\nimport { normalizeHttpBoundaryError } from '../common/failure.ts'\nimport type { HttpTransportConnection } from './connection.ts'\nimport {\n httpErrorCode,\n parseErrorBody,\n requestIdFrom,\n retryAfterMs,\n} from './errors.ts'\nimport {\n abortError,\n cancelResponseBody,\n endpointUrl,\n raceWithSignal,\n readBoundedText,\n redactHeaders,\n rejectProviderRedirect,\n requestLogId,\n safeProviderFailure,\n} from './http.ts'\nimport { resolveTransportLimits, type ResolvedTransportLimits } from './limits.ts'\n\n/** One serialized request body, measured before anything is sent. */\nexport interface PreparedWireBody {\n /** The value handed to the diagnostic observer; never re-serialized. */\n readonly value: unknown\n /** Exact bytes sent on the wire. */\n readonly encoded: string\n /** UTF-8 length of {@link encoded}. */\n readonly bytes: number\n}\n\n/**\n * How the transport obtains the body.\n *\n * A thunk exists because the pipeline that owns serialization also owns caching it\n * across repeated `stream()` calls on one prepared call, and because building the\n * body may itself do work that must observe the fused signal — which does not exist\n * until the transport creates it.\n */\nexport type WireBodySource =\n | PreparedWireBody\n | ((signal: AbortSignal) => PreparedWireBody | Promise<PreparedWireBody>)\n\n/**\n * One exact wire request, observed immediately before dispatch.\n *\n * Structurally identical to the generation pipeline's record, and deliberately\n * declared here so the transport does not depend on a pipeline for its own shape.\n */\nexport interface WireRequestRecord {\n readonly schemaVersion: 1\n readonly type: 'provider-request'\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 /** Credentials and cookies already replaced by `[REDACTED]`. */\n readonly headers: Readonly<Record<string, string>>\n /** The exact serialized value. This may contain prompts and tool output. */\n readonly body: unknown\n readonly bodyBytes: number\n}\n\n/** Everything the shared chain needs to issue ONE request. */\nexport interface HttpTransportRequestInput {\n /** The snapshot this request is bound to; read once, never re-read mid-request. */\n readonly connection: HttpTransportConnection\n /** Provider display name used in every message this chain raises. */\n readonly displayName: string\n /** Route being served. */\n readonly provider: string\n /** Wire model id. */\n readonly model: string\n /** Path appended to {@link HttpTransportConnection.baseUrl}. */\n readonly path: string\n /**\n * Media type this pipeline requires back.\n *\n * The transport does not enforce it — the `accept` header travels on the\n * connection snapshot and the check belongs to whoever decodes — but it is carried\n * on the session so `decode` states its expectation in one place.\n */\n readonly accept: string\n readonly body: WireBodySource\n /** The caller's cancellation, fused with the deadline and our teardown. */\n readonly signal?: AbortSignal\n readonly context?: ModelInvocationContext\n /** Override status-to-code mapping for a provider with codes of its own. */\n readonly errorCode?: (status: number, detail: string) => string\n /** Best-effort diagnostic observer; never a dispatch veto. */\n readonly observeRequest?: (record: WireRequestRecord) => Promise<void> | void\n}\n\n/** Outcome vocabulary a pipeline may report for the attempt ledger. */\nexport type TransportAttemptStatus = 'success' | 'error' | 'aborted' | 'unknown'\n\n/** A response that already cleared every transport guard, plus its ledger hooks. */\nexport interface HttpTransportSession {\n /** The response; its body is still unread and is owned by the transport. */\n readonly response: Response\n readonly url: string\n readonly origin: string\n /** Fused signal: caller + request deadline + transport teardown. */\n readonly signal: AbortSignal\n /** Provider correlation id, when the response carried one. */\n readonly providerRequestId?: ProviderRequestId\n /** Media type the pipeline asked for; see {@link HttpTransportRequestInput.accept}. */\n readonly accept: string\n readonly limits: ResolvedTransportLimits\n /**\n * Record a usage report as attempt evidence.\n *\n * Evidence only: whether a report is complete enough to leave the SDK as\n * `TokenUsage` is a pipeline decision, and this hook does not make it.\n */\n readonly attemptId?: string\n reportUsage(usage: UsageCounters, final?: boolean): void\n /** Record the terminal outcome the decoded stream reported. */\n reportOutcome(status: TransportAttemptStatus, failure?: ModelFailure): void\n}\n\n/**\n * Run one request through the shared safety chain and stream `use`'s output.\n *\n * The generator shape matters: the provider attempt stays open, and the response\n * body stays owned, for as long as the consumer keeps pulling. A consumer that\n * stops early aborts the teardown controller in `finally`, which is what tears down\n * an in-flight response instead of leaking the connection.\n * @param input - the request facts, all captured from one connection snapshot.\n * @param use - decodes a guarded response; its failures are classified here.\n * @returns whatever `use` yields, unchanged.\n */\nexport async function* withTransportSession<T>(\n input: HttpTransportRequestInput,\n use: (session: HttpTransportSession) => AsyncIterable<T>,\n): AsyncGenerator<T> {\n const { connection, context, displayName, model, provider } = input\n const callerSignal = input.signal\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 limits = resolveTransportLimits(connection)\n const timeout = AbortSignal.timeout(limits.requestTimeoutMs)\n const signal = AbortSignal.any([\n consumer.signal,\n timeout,\n ...callerSignal === undefined ? [] : [callerSignal],\n ])\n\n let admissionFailure: { readonly value: unknown } | undefined\n let ownedResponse: Response | undefined\n try {\n signal.throwIfAborted()\n const preparedBody = typeof input.body === 'function'\n ? await input.body(signal)\n : input.body\n if (preparedBody.bytes > limits.maxRequestBytes) {\n throw new ModelError(\n `${displayName} request exceeds the ${limits.maxRequestBytes}-byte limit`,\n MODEL_ERROR_CODES.INVALID_REQUEST,\n )\n }\n const endpoint = endpointUrl(\n connection.baseUrl,\n input.path,\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([\n signal,\n AbortSignal.timeout(limits.requestLoggerTimeoutMs),\n ])\n await raceWithSignal(Promise.resolve(input.observeRequest?.({\n schemaVersion: 1,\n type: 'provider-request',\n id: requestLogId(),\n timestamp: new Date().toISOString(),\n provider,\n model,\n method: 'POST',\n url,\n headers: redactHeaders(headers, connection.sensitiveHeaderNames),\n body: preparedBody.value,\n bodyBytes: preparedBody.bytes,\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: ProviderRequestId | undefined\n let attemptStatus: TransportAttemptStatus = 'unknown'\n let attemptUsage: UsageCounters | undefined\n let usageFinal = true\n let attemptError: SafeErrorRecord | undefined\n try {\n signal.throwIfAborted()\n try {\n attempt = await context?.startProviderAttempt?.({\n provider,\n model,\n method: 'POST',\n origin,\n }, signal)\n } catch (error: unknown) {\n // Audit mode refused this dispatch. That decision travels out verbatim.\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: preparedBody.encoded,\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) {\n throw await httpFailure(response, origin, limits.maxErrorBodyBytes, signal, input)\n }\n\n const session: HttpTransportSession = Object.freeze({\n response,\n url,\n origin,\n signal,\n accept: input.accept,\n limits,\n ...providerRequestId === undefined ? {} : { providerRequestId },\n reportUsage(usage: UsageCounters, final = true) {\n attemptUsage = usage\n usageFinal = final\n },\n ...(attempt === undefined ? {} : { attemptId: attempt.attemptId }),\n reportOutcome(status: TransportAttemptStatus, failure?: ModelFailure) {\n attemptStatus = status\n if (failure !== undefined) attemptError = safeProviderFailure(failure)\n },\n })\n yield* use(session)\n } catch (error: unknown) {\n if (admissionFailure !== undefined && error === admissionFailure.value) throw error\n const mapped = timeout.aborted && callerSignal?.aborted !== true\n ? new ModelError(\n `${displayName} request exceeded its ${limits.requestTimeoutMs}ms time limit`,\n MODEL_ERROR_CODES.TIMEOUT,\n { cause: error },\n )\n : signal.aborted\n ? abortError(displayName, error)\n : normalizeHttpBoundaryError(\n error,\n `${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 ...usageFinal ? {} : { usageFinal: false },\n ...httpStatus === undefined ? {} : { httpStatus },\n ...providerRequestId === undefined ? {} : { providerRequestId },\n ...attemptError === undefined ? {} : { error: attemptError },\n })\n }\n } catch (error: unknown) {\n if (callerSignal?.aborted === true) throw abortError(displayName, error)\n if (timeout.aborted) {\n throw new ModelError(\n `${displayName} request exceeded its ${limits.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, `${displayName} stream failed`)\n } finally {\n consumer.abort(new Error(`${displayName} stream consumer stopped`))\n if (ownedResponse !== undefined) await cancelResponseBody(ownedResponse)\n }\n}\n\n/**\n * Turn a non-2xx response into a fully populated {@link ModelError}.\n *\n * The body is read under the same bound and the same signal as everything else,\n * and a body that cannot be read does not replace the status — the status is the\n * more reliable signal of the two anyway.\n * @param response - the non-success response.\n * @param origin - request origin, reported in the message instead of the full URL.\n * @param maxBytes - error-body bound from the resolved limits.\n * @param signal - the fused signal.\n * @param input - request facts, for the display name and code override.\n * @returns the mapped error, carrying status, `retry-after`, and request id.\n */\nasync function httpFailure(\n response: Response,\n origin: string,\n maxBytes: number,\n signal: AbortSignal,\n input: HttpTransportRequestInput,\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 ?? `${input.displayName} error (HTTP ${response.status}) from ${origin}`,\n (input.errorCode ?? httpErrorCode)(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 * The streaming pipeline's entry into the shared transport chain.\n *\n * Two properties define it, and both are about what happens while a consumer is\n * still pulling. The provider attempt stays open for the whole stream, because a\n * stream that fails halfway through is one attempt with a failure — not a success\n * followed by a mystery. And every pull is raced against the fused signal, so a\n * decoder that blocks on a provider which has stopped sending still surrenders when\n * the caller aborts, the deadline fires, or the consumer walks away.\n *\n * What `decode` sees is a response that already cleared every guard in\n * {@link withTransportSession}: bounded body, no redirect, 2xx, attempt open. What\n * it owns is the format — media type, framing, termination.\n *\n * @module ai-agent-sdk/providers/transport/stream\n */\n\nimport { withAbortSignal } from './http.ts'\nimport {\n withTransportSession,\n type HttpTransportRequestInput,\n type HttpTransportSession,\n} from './session.ts'\n\n/**\n * Send one request and stream whatever `decode` makes of the response.\n *\n * @param input - request facts captured from one connection snapshot.\n * @param decode - turns a guarded response into the pipeline's own values.\n * @returns the decoded values, with the attempt held open until iteration ends.\n */\nexport function transportStream<T>(\n input: HttpTransportRequestInput,\n decode: (session: HttpTransportSession) => AsyncIterable<T>,\n): AsyncGenerator<T> {\n return withTransportSession(\n input,\n session => withAbortSignal(decode(session), session.signal),\n )\n}\n","import type { ResolvedModelInfo } from '@alvin0/ai-agent-sdk-core'\nimport type { ProviderCatalogModel } from './http-adapter.ts'\n\n/** Context facts only: never advertises models or guesses their capabilities. */\nexport interface ModelContextPolicy {\n readonly defaultContextWindow: number\n readonly maxContextWindow?: number\n readonly standardPriceInputTokens?: number\n}\n\nexport interface ModelContextPolicyOptions {\n readonly baseUrl?: string\n readonly models?: readonly ProviderCatalogModel[]\n readonly defaultContextWindow?: number\n}\n\nexport function applyModelContextPolicy(\n info: ResolvedModelInfo,\n policy: ModelContextPolicy | undefined,\n configured?: ProviderCatalogModel,\n providerOverride?: number,\n): ResolvedModelInfo {\n const defaultContextWindow = configured?.defaultContextWindow ?? policy?.defaultContextWindow ?? info.context?.defaultContextWindow\n const knownMaximum = policy?.maxContextWindow ?? info.context?.maxContextWindow\n const maxContextWindow = knownMaximum === undefined\n ? configured?.maxContextWindow\n : Math.min(knownMaximum, configured?.maxContextWindow ?? knownMaximum)\n const standardPriceInputTokens = configured?.standardPriceInputTokens ?? policy?.standardPriceInputTokens ?? info.context?.standardPriceInputTokens\n const contextWindow = configured?.contextWindow ?? providerOverride ?? defaultContextWindow ?? info.context?.contextWindow\n for (const [name, value] of Object.entries({ contextWindow, defaultContextWindow, maxContextWindow, standardPriceInputTokens })) {\n if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {\n throw new TypeError(`${name} must be a positive safe integer`)\n }\n }\n if (maxContextWindow !== undefined && (\n (contextWindow !== undefined && contextWindow > maxContextWindow)\n || (defaultContextWindow !== undefined && defaultContextWindow > maxContextWindow)\n )) throw new RangeError('contextWindow exceeds maxContextWindow')\n if (contextWindow === undefined) return info\n return { ...info, context: {\n contextWindow,\n ...(defaultContextWindow === undefined ? {} : { defaultContextWindow }),\n ...(maxContextWindow === undefined ? {} : { maxContextWindow }),\n ...(standardPriceInputTokens === undefined ? {} : { standardPriceInputTokens }),\n ...(standardPriceInputTokens !== undefined && contextWindow > standardPriceInputTokens\n ? { pricingWarning: 'extended-context-may-cost-more' as const } : {}),\n } }\n}\n\n/** Capture configuration so later caller mutations cannot change model resolution. */\nexport function createModelContextPolicy(\n policies: Readonly<Record<string, ModelContextPolicy>>,\n models: readonly ProviderCatalogModel[] | undefined,\n providerOverride?: number,\n): (info: ResolvedModelInfo) => ResolvedModelInfo {\n const captured = structuredClone(policies)\n const configured = structuredClone(models ?? [])\n return info => applyModelContextPolicy(info,\n Object.hasOwn(captured, info.id) ? captured[info.id] : undefined,\n configured.find(model => model.id === info.id), providerOverride)\n}\n","/**\n * Generation's transport facade: the catalog helpers, plus the shared primitives\n * at the path existing callers already import.\n *\n * The pipeline-independent half moved to {@link ../transport/http} and\n * {@link ../transport/limits} when the transport layer was split out, so a second\n * pipeline could reuse it without importing the generation pipeline. What stays\n * here is what genuinely belongs to generation: turning an advisory model catalog\n * into model metadata.\n *\n * @module ai-agent-sdk/providers/base/transport\n */\n\nimport type { ModelInfo, ResolvedModelInfo } from '@alvin0/ai-agent-sdk-core'\nimport type { ProviderCatalogModel } from './http-adapter.ts'\nimport { applyModelContextPolicy } from './context-policy.ts'\n\n/** Shared HTTP primitives live in the transport; re-exported for existing callers. */\nexport {\n abortError,\n boundedResponseBody,\n cancelResponseBody,\n endpointUrl,\n raceWithSignal,\n readBoundedText,\n redactHeaders,\n rejectProviderRedirect,\n requestLogId,\n safeProviderFailure,\n withAbortSignal,\n} from '../transport/http.ts'\n/** Bound validation belongs to the transport limits module; re-exported for existing callers. */\nexport { positiveFinite, positiveInteger } from '../transport/limits.ts'\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 applyModelContextPolicy({\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?.defaultMaxTokens ?? configured?.maxTokens ?? defaultMaxTokens,\n ...(configured?.maxTokens === undefined ? {} : { maxOutputTokens: configured.maxTokens }),\n ...(configured?.reasoning === undefined ? {} : { reasoning: configured.reasoning }),\n ...(configured?.outputModalities === undefined ? {} : { outputModalities: configured.outputModalities }),\n }, undefined, configured)\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 * The risky half of that list — signal fusion, request bounds, the diagnostic\n * observer, attempt accounting, redirect refusal, status mapping, teardown — now\n * lives in {@link ../transport/session.withTransportSession} so a second pipeline\n * cannot reimplement it slightly differently. What stays in this file is what is\n * genuinely generation's: the modality guard, the catalog, the serialized-body\n * cache for one prepared call, and {@link HttpModelAdapter.decodeSse} — the SSE\n * half, unchanged, applied to a response that already cleared every guard.\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 { NativeToolName } from '@alvin0/ai-agent-sdk-core'\nimport { MODEL_ERROR_CODES, ModelError } from '@alvin0/ai-agent-sdk-core'\nimport { contentHasDocument, 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 { TokenUsage } 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 { captureTransportConnection, type HttpTransportConnection } from '../transport/connection.ts'\nimport { positiveInteger } from '../transport/limits.ts'\nimport type { HttpTransportSession, PreparedWireBody } from '../transport/session.ts'\nimport { transportStream } from '../transport/stream.ts'\nimport { httpErrorCode } from './http-errors.ts'\nimport {\n boundedResponseBody,\n catalogModelInfo,\n raceWithSignal,\n resolvedCatalogModelInfo,\n} from './transport.ts'\n\nexport { redactHeaders } from './transport.ts'\nexport {\n DEFAULT_MAX_ERROR_BODY_BYTES,\n DEFAULT_MAX_REQUEST_BYTES,\n DEFAULT_MAX_RESPONSE_BYTES,\n DEFAULT_MAX_RESPONSE_CHUNKS,\n DEFAULT_REQUEST_LOGGER_TIMEOUT_MS,\n DEFAULT_REQUEST_TIMEOUT_MS,\n} from '../transport/limits.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\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 /** Standard-price operating budget before a contextWindow override. */\n defaultContextWindow?: number\n /** Known technical ceiling; overrides cannot exceed it. */\n maxContextWindow?: number\n /** Input-token threshold for long-context pricing, when known. */\n standardPriceInputTokens?: number\n /** Per-request output cap for this model. */\n maxTokens?: number\n /** Default output budget, independently of the ceiling. Falls back to maxTokens. */\n defaultMaxTokens?: 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 generation request, captured as a single snapshot.\n *\n * The transport half — endpoint, headers, bounds, retry policy — is\n * {@link HttpTransportConnection} and is shared with every other pipeline in this\n * package. What this interface adds is the part only generation has: the SSE\n * decoding bounds and the advisory model catalog. The field set and the optionality\n * of every field are unchanged from before the split, so existing provider\n * configurations satisfy it exactly as they did.\n *\n * The catalog stays here deliberately. Embedding routes carry a catalog with\n * different semantics, and folding the two into one shape is precisely the\n * conflation this split avoids.\n */\nexport interface HttpConnection extends HttpTransportConnection {\n /** Maximum idle interval while a read is outstanding. */\n readonly streamIdleTimeoutMs: 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 /** 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\n/**\n * The serialized body of ONE prepared call, kept across repeated `stream()` calls.\n *\n * This stays with the pipeline rather than moving into the transport: the transport\n * issues one request and has no notion of a prepared call to cache against, and a\n * cache that outlived a request would be a way for one call's body to reach another\n * call's wire.\n */\ninterface PreparedWireBodyCache {\n prepared?: Promise<PreparedWireBody>\n}\n\n/** The decoding bounds the SSE pipeline adds on top of the transport's. */\ninterface ResolvedSseLimits {\n /** Maximum decoded SSE events accepted from one response. */\n readonly maxEvents: number\n /** Maximum characters accepted in one decoded SSE event. */\n readonly maxEventChars: number\n}\n\n/**\n * Resolve the SSE bounds before any transport work starts.\n *\n * Deliberately validated in the pipeline and not inside `decodeSse`: an\n * unusable bound is a configuration error, and configuration errors must not\n * arrive after a provider attempt has been opened and a request sent.\n * @param connection - the snapshot this call is bound to.\n * @returns defaulted, validated event bounds.\n */\nfunction resolveSseLimits(connection: HttpConnection): ResolvedSseLimits {\n return Object.freeze({\n maxEvents: positiveInteger(\n connection.maxSseEvents ?? DEFAULT_MAX_SSE_EVENTS,\n 'maxSseEvents',\n ),\n maxEventChars: positiveInteger(\n connection.maxSseEventChars ?? DEFAULT_MAX_SSE_EVENT_CHARS,\n 'maxSseEventChars',\n ),\n })\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 return captureTransportConnection(connection, this.baseHeaders())\n }\n\n /**\n * The generation pipeline: guard the modalities, then hand one request to the\n * shared transport chain with SSE decoding as its only pipeline-specific part.\n *\n * Still a generator, and deliberately so: the modality guard, the body\n * serialization and every transport step stay lazy until a consumer pulls, which\n * is the behaviour every existing caller of `stream()` already relies on.\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 if (options.messages.some(message => contentHasDocument(message.content))\n && model.inputModalities?.includes('document') !== true) {\n throw new ModelError(\n `${this.displayName} model \"${options.model}\" does not accept document 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 const sseLimits = resolveSseLimits(connection)\n const adapter = this\n yield* transportStream<StreamChunk>({\n connection,\n displayName: this.displayName,\n provider: options.provider,\n model: options.model,\n accept: 'text/event-stream',\n /**\n * Read by the transport AFTER the body is prepared, which is exactly where\n * the pipeline used to call it. A provider whose path computation fails\n * therefore still fails inside the transport's classification, and a\n * protocol that reports its routing decision from `endpointPath` still\n * reports it once, in the same place in the sequence, as before.\n */\n get path(): string {\n return adapter.endpointPath(request)\n },\n // The transport bounds and rejects this body; the cache that keeps it across\n // repeated `stream()` calls on one prepared call belongs to the pipeline.\n body: signal => wireBodyCache.prepared ??= this.prepareWireBody(request, signal),\n ...options.signal === undefined ? {} : { signal: options.signal },\n ...context === undefined ? {} : { context },\n errorCode: (status, detail) => this.providerErrorCode(status, detail),\n observeRequest: record => this.observeRequest(record),\n }, session => this.decodeSse(session, request, sseLimits))\n }\n\n /**\n * The SSE half: media type, bounds, idle deadline, translation, usage honesty.\n *\n * Everything this sees has already cleared the transport's guards — 2xx, no\n * redirect, attempt open, teardown owned — so what remains is only the format.\n * Abort racing is not repeated here: {@link transportStream} already iterates\n * this generator under the fused signal.\n * @param session - the guarded response and its attempt-evidence hooks.\n * @param request - the request this response answers.\n * @param sse - event bounds resolved before any transport work began.\n * @returns the provider's chunks, with incomplete usage held back.\n */\n private async * decodeSse(\n session: HttpTransportSession,\n request: ProviderRequest,\n sse: ResolvedSseLimits,\n ): AsyncGenerator<StreamChunk> {\n const response = session.response\n const mediaType = response.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase()\n if (mediaType !== session.accept) {\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 maxResponseBytes = session.limits.maxResponseBytes\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 request.connection.streamIdleTimeoutMs,\n this.displayName,\n 30_000,\n )\n const events = parseSseBounded(boundedResponseBody(\n response.body,\n maxResponseBytes,\n session.limits.maxResponseChunks,\n this.displayName,\n session.signal,\n ), idleDeadline.activity, 30_000, {\n maxEvents: sse.maxEvents,\n maxEventChars: sse.maxEventChars,\n })\n const translated = requireTerminalFinish(this.translate(events, request), this.displayName)\n for await (const chunk of idleDeadline.guard(translated)) {\n if (chunk.type === 'usage-progress') {\n session.reportUsage(chunk.usage, false)\n const validated = validateUsageCounters(chunk.usage, true)\n if (Object.keys(validated.reported).length > 0) {\n yield { type: 'usage-progress', usage: validated.reported,\n ...(session.attemptId === undefined ? {} : { attemptId: session.attemptId }) }\n }\n continue\n }\n if (chunk.type === 'usage') {\n session.reportUsage(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 const status = chunk.reason.kind === 'aborted' ? 'aborted'\n : chunk.reason.kind === 'error' ? 'error' : 'success'\n session.reportOutcome(\n status,\n chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted'\n ? chunk.reason.failure\n : undefined,\n )\n }\n yield chunk\n }\n }\n\n private async prepareWireBody(\n request: ProviderRequest,\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 return Object.freeze({ value, encoded, bytes })\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","import { mergeHeaderLayers } from './header-layers.ts'\n\n/** Capture custom endpoint headers per operation, rejecting reserved names and collisions. */\nexport function endpointHeaders(\n headers: Readonly<Record<string, string>> | (() => Readonly<Record<string, string>>) | undefined,\n defaults: Readonly<Record<string, string>> = {},\n): () => Readonly<Record<string, string>> {\n const fixedDefaults = mergeHeaderLayers([{ layer: 'endpoint', headers: defaults }]).headers\n const capture = (value: Readonly<Record<string, string>>) => mergeHeaderLayers([\n { layer: 'endpoint', headers: fixedDefaults },\n { layer: 'endpoint', headers: value },\n ]).headers\n if (typeof headers === 'function') return () => capture(headers())\n const fixed = capture(headers ?? {})\n return () => fixed\n}\n","/**\n * Embedding's half of a connection snapshot, plus the one translation from a\n * declared route catalog into `Embedding_Catalog` capabilities.\n *\n * This module sits on top of {@link HttpTransportConnection} rather than inside\n * it: the transport and the JSON pipeline know nothing about embedding\n * vocabulary, and they must not, or a second pipeline could not exist without\n * dragging the first one's catalog along. What embedding adds is a catalog with\n * its own semantics — vector widths, batch ceilings, purpose handling, and a\n * declaration about which embedding space the vectors belong to.\n *\n * The translation rule has exactly one shape and it runs in one direction: a\n * field the configuration DECLARES becomes `supported`, a field it OMITS becomes\n * `unknown` (Requirement 10.5). Nothing here manufactures a `supported` value\n * from a default, because a default is the SDK's opinion, not the route's claim,\n * and `unknown` is never a reason to reject a request.\n *\n * Two things are deliberately NOT here:\n *\n * - Cleartext HTTP handling. `EmbeddingHttpConnection` extends the transport\n * snapshot, so `allowInsecureHttp` is the same field the same `endpointUrl()`\n * already enforces for generation — a self-hosted `http://` endpoint is\n * rejected unless the caller opts in explicitly, and embedding gets that for\n * free rather than through a second copy of the rule (Requirement 15.5).\n * - The generation catalog. `models`, `defaultMaxTokens` and\n * `defaultContextWindow` stay on `HttpConnection`; folding the two catalogs\n * into one shape is the conflation Requirement 10.1 rules out.\n *\n * @module ai-agent-sdk/providers/transport/embedding-connection\n */\n\nimport {\n type EmbeddingCapability,\n type EmbeddingModelInfo,\n type EmbeddingNormalization,\n type EmbeddingPurposeHandling,\n type ResolvedEmbeddingModelInfo,\n unknownEmbeddingModel,\n} from '@alvin0/ai-agent-sdk-core/embedding'\nimport type { HttpTransportConnection } from './connection.ts'\n\n/**\n * One embedding model an HTTP route declares.\n *\n * Every capability field is optional but one: {@link compatibilityIdentity}. A\n * vector is only meaningful next to another vector from the same space, and no\n * amount of matching dimension counts establishes that. Requiring the claim in\n * the type means a self-hosted \"OpenAI-compatible\" endpoint is a tested profile\n * someone declared, not an assumption drawn from the endpoint having an\n * `/embeddings` path (Requirement 15.3).\n */\nexport interface EmbeddingCatalogModel {\n /** Wire model id, passed to the provider verbatim. */\n readonly id: string\n /** Selector label; defaults to {@link id}. */\n readonly name?: string\n /** Optional detail distinguishing similar variants. */\n readonly description?: string\n /** Selectable vector widths this route accepts. */\n readonly dimensions?: readonly number[]\n /** Width used when the caller requests none. */\n readonly defaultDimensions?: number\n /** Per-input token ceiling. Only a declared value may reject an input. */\n readonly maxInputTokens?: number\n /** Items accepted in one physical batch. */\n readonly maxBatchItems?: number\n /** Estimated tokens accepted in one physical batch. */\n readonly maxBatchTokens?: number\n /** Payload bytes accepted in one physical batch. */\n readonly maxBatchBytes?: number\n /**\n * How this route expresses purpose on the wire.\n *\n * `'unsupported'` is the positive negative claim — the route states it has no\n * mechanism, which is what OpenAI's embeddings API is — and it is distinct\n * from omitting the field, which claims nothing. Either way the adapter sends\n * the text verbatim and never invents an undocumented prefix.\n */\n readonly purposeHandling?: EmbeddingPurposeHandling | 'unsupported'\n /** Whether vectors arrive normalized. Never inferred from dimension count. */\n readonly normalization?: EmbeddingNormalization\n /**\n * The route's explicit declaration about the embedding space.\n *\n * Required, including for a self-hosted endpoint. Models sharing a declared\n * space share this string; a new model generation gets a new one even when the\n * vector width is unchanged.\n */\n readonly compatibilityIdentity: string\n}\n\n/**\n * Everything needed to issue ONE embedding request, captured as a single snapshot.\n *\n * The transport half — endpoint, headers, bounds, cleartext opt-in, retry\n * policy — is {@link HttpTransportConnection} and is shared with the generation\n * pipeline verbatim. Both `OpenAI_Embedding_Adapter` and\n * `Gemini_Embedding_Adapter` are configured through this one shape.\n */\nexport interface EmbeddingHttpConnection extends HttpTransportConnection {\n /** Advisory catalog; requests are never restricted to it. */\n readonly models: readonly EmbeddingCatalogModel[]\n}\n\n/** The `unknown` capability, shared so translations need not re-allocate it. */\nconst UNKNOWN: EmbeddingCapability<never> = Object.freeze({ state: 'unknown' })\n\n/** The `unsupported` capability, for a route's positive negative claim. */\nconst UNSUPPORTED: EmbeddingCapability<never> = Object.freeze({ state: 'unsupported' })\n\n/** Declared value becomes `supported`; omission stays `unknown`. */\nfunction declared<T>(value: T | undefined): EmbeddingCapability<T> {\n return value === undefined ? UNKNOWN : Object.freeze({ state: 'supported' as const, value })\n}\n\n/** The one place `'unsupported'` is separated from an omitted declaration. */\nfunction declaredPurpose(\n value: EmbeddingCatalogModel['purposeHandling'],\n): EmbeddingCapability<EmbeddingPurposeHandling> {\n if (value === undefined) return UNKNOWN\n return value === 'unsupported' ? UNSUPPORTED : Object.freeze({ state: 'supported', value })\n}\n\n/**\n * Translate one declared catalog entry into `Embedding_Catalog` metadata.\n *\n * `inputTypes` and `representation` come out `unknown` rather than filled in\n * from the v1 scope: the scope is already readable from the types\n * (`EmbeddingInputType` is `'text'`, `EmbeddingRepresentation` is\n * `'dense-float32'`), and stating `supported` on the route's behalf would be\n * the SDK asserting a claim the route never made.\n * @param provider - route that owns the entry.\n * @param model - the declared catalog entry.\n * @returns advisory embedding metadata for this entry.\n */\nexport function embeddingCatalogModelInfo(\n provider: string,\n model: EmbeddingCatalogModel,\n): EmbeddingModelInfo {\n return {\n provider,\n id: model.id,\n name: model.name ?? model.id,\n ...(model.description === undefined ? {} : { description: model.description }),\n inputTypes: UNKNOWN,\n representation: UNKNOWN,\n dimensions: declared(model.dimensions),\n defaultDimensions: declared(model.defaultDimensions),\n maxInputTokens: declared(model.maxInputTokens),\n maxBatchItems: declared(model.maxBatchItems),\n maxBatchTokens: declared(model.maxBatchTokens),\n maxBatchBytes: declared(model.maxBatchBytes),\n purposeHandling: declaredPurpose(model.purposeHandling),\n normalization: declared(model.normalization),\n compatibilityIdentity: declared(model.compatibilityIdentity),\n }\n}\n\n/**\n * Resolve exact embedding metadata for a model id from an advisory catalog.\n *\n * An id the catalog does not describe stays usable: the caller gets an\n * identity-only descriptor with every capability `unknown` and the provider\n * decides (Requirement 10.3). The catalog restricting the request would make\n * membership authoritative, which it is not.\n * @param provider - route being resolved.\n * @param modelId - requested model id.\n * @param models - the route's declared catalog.\n * @returns exact metadata for the id, or the identity-only descriptor.\n */\nexport function resolvedEmbeddingCatalogModelInfo(\n provider: string,\n modelId: string,\n models: readonly EmbeddingCatalogModel[],\n): ResolvedEmbeddingModelInfo {\n const configured = models.find(entry => entry.id === modelId)\n if (configured === undefined) return unknownEmbeddingModel(provider, modelId)\n return embeddingCatalogModelInfo(provider, configured)\n}\n","/**\n * The JSON pipeline's entry into the shared transport chain.\n *\n * Where the streaming pipeline keeps a provider attempt open for as long as a\n * consumer keeps pulling, this one has a single, bounded shape: read the whole body\n * under the configured byte and chunk bounds, parse it, hand the parsed value to\n * `decode`, close the attempt. There is no framing to track and no idle deadline to\n * enforce, because there is nothing to wait for between events.\n *\n * Three failures are stated rather than inferred, since each one has a\n * plausible-looking wrong answer:\n *\n * - A response whose media type is not JSON is refused with a code of its own\n * ({@link HTTP_PROVIDER_ERROR_CODES.JSON_MEDIA_TYPE_INVALID}), symmetric with the\n * SSE check. Parsing an HTML error page as if it were the provider's answer is how\n * a proxy outage becomes a mysterious schema error further up.\n * - A body past `maxResponseBytes` is a transport failure, the same as on the SSE\n * path, and is refused instead of truncated: half a JSON document is not data.\n * - A body that is not valid JSON is a protocol failure, never something to guess\n * at.\n *\n * What `decode` receives is a response that already cleared every guard in\n * {@link withTransportSession} — 2xx, no redirect, attempt open, teardown owned —\n * plus a parsed body. What it owns is the schema.\n *\n * @module ai-agent-sdk/providers/transport/json\n */\n\nimport { MODEL_ERROR_CODES, ModelError } from '@alvin0/ai-agent-sdk-core'\nimport { HTTP_PROVIDER_ERROR_CODES } from '../common/config.ts'\nimport { boundedResponseBody, raceWithSignal } from './http.ts'\nimport {\n withTransportSession,\n type HttpTransportRequestInput,\n type HttpTransportSession,\n} from './session.ts'\n\n/** Media types this pipeline accepts back from a provider. */\nexport const JSON_MEDIA_TYPES = Object.freeze(['application/json'] as const)\n\n/**\n * Send one request, read its JSON body under bound, and return `decode`'s value.\n *\n * The attempt closes as soon as the value is produced; nothing here stays open for\n * a consumer, because the whole response is already in memory by then.\n * @param input - request facts captured from one connection snapshot.\n * @param decode - turns a parsed body into the pipeline's own value.\n * @returns whatever `decode` returns.\n */\nexport async function transportJson<T>(\n input: HttpTransportRequestInput,\n decode: (session: HttpTransportSession, body: unknown) => T | Promise<T>,\n): Promise<T> {\n const decoded: { value: T }[] = []\n // `break` closes the generator, which is what runs the shared `finally`:\n // attempt accounting, consumer teardown, response-body release.\n for await (const value of withTransportSession(input, async function* (session) {\n const body = parseJsonBody(\n await readBoundedBody(session, input.displayName),\n input.displayName,\n )\n const result = await decode(session, body)\n // A value returned from `decode` is what a successful attempt looks like.\n session.reportOutcome('success')\n yield result\n })) {\n decoded.push({ value })\n break\n }\n const first = decoded[0]\n if (first === undefined) {\n throw new ModelError(\n `${input.displayName} produced no JSON response`,\n MODEL_ERROR_CODES.MALFORMED_RESPONSE,\n )\n }\n return first.value\n}\n\n/** True when a `content-type` value names one of {@link JSON_MEDIA_TYPES}. */\nexport function isJsonMediaType(contentType: string | null): boolean {\n const mediaType = contentType?.split(';', 1)[0]?.trim().toLowerCase()\n if (mediaType === undefined) return false\n return (JSON_MEDIA_TYPES as readonly string[]).includes(mediaType)\n}\n\n/**\n * Read the whole body as text, refusing anything past the configured bounds.\n *\n * The declared `content-length` is checked first so an oversized response is\n * refused before a single byte of it is buffered; the streaming bound still applies\n * afterwards, because the header is a claim and not a guarantee.\n * @param session - the guarded response and its resolved limits.\n * @param displayName - provider name used in every message raised here.\n * @returns the exact body text.\n */\nasync function readBoundedBody(\n session: HttpTransportSession,\n displayName: string,\n): Promise<string> {\n const response = session.response\n if (!isJsonMediaType(response.headers.get('content-type'))) {\n throw new ModelError(\n `${displayName} response is not ${JSON_MEDIA_TYPES.join(' or ')}`,\n HTTP_PROVIDER_ERROR_CODES.JSON_MEDIA_TYPE_INVALID,\n )\n }\n if (response.body === null) {\n throw new ModelError(\n `${displayName} returned no response body`,\n MODEL_ERROR_CODES.MALFORMED_RESPONSE,\n )\n }\n\n const maxResponseBytes = session.limits.maxResponseBytes\n const declaredLength = response.headers.get('content-length')\n if (declaredLength !== null && /^\\d+$/.test(declaredLength)\n && Number(declaredLength) > maxResponseBytes) {\n throw new ModelError(\n `${displayName} response exceeds the ${maxResponseBytes}-byte limit`,\n MODEL_ERROR_CODES.TRANSPORT,\n )\n }\n\n const reader = boundedResponseBody(\n response.body,\n maxResponseBytes,\n session.limits.maxResponseChunks,\n displayName,\n session.signal,\n ).getReader()\n const decoder = new TextDecoder()\n let text = ''\n try {\n while (true) {\n const { done, value } = await raceWithSignal(reader.read(), session.signal)\n if (done) break\n if (value === undefined) continue\n text += decoder.decode(value, { stream: true })\n }\n return text + decoder.decode()\n } finally {\n reader.releaseLock()\n }\n}\n\n/** Parse a body, turning a parse failure into a protocol error rather than a guess. */\nfunction parseJsonBody(text: string, displayName: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error: unknown) {\n throw new ModelError(\n `${displayName} response body is not valid JSON`,\n MODEL_ERROR_C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,wBAAwB,iBAAiB,cACxD,kBAAkB,SACpB;CAGF,MAAM,SAAS,oBACb,SAAS,MACT,kBACA,QAAQ,OAAO,mBACf,aACA,QAAQ,MACV,CAAC,CAAC,UAAU;CACZ,MAAM,UAAU,IAAI,YAAY;CAChC,IAAI,OAAO;CACX,IAAI;EACF,OAAO,MAAM;GACX,MAAM,EAAE,MAAM,UAAU,MAAM,eAAe,OAAO,KAAK,GAAG,QAAQ,MAAM;GAC1E,IAAI,MAAM;GACV,IAAI,UAAU,QAAW;GACzB,QAAQ,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;EAChD;EACA,OAAO,OAAO,QAAQ,OAAO;CAC/B,UAAU;EACR,OAAO,YAAY;CACrB;AACF;;AAGA,SAAS,cAAc,MAAc,aAA8B;CACjE,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,SAAS,OAAgB;EACvB,MAAM,IAAI,WACR,GAAG,YAAY,mCACf,kBAAkB,oBAClB,EAAE,OAAO,MAAM,CACjB;CACF;AACF"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "name": "alvin0 - chaulamdinhai",
5
5
  "email": "chaulamdinhai@gmail.com"
6
6
  },
7
- "version": "0.1.1",
7
+ "version": "0.1.3",
8
8
  "description": "Universal fetch, SSE, configurable provider, and provider-attempt accounting for ai-agent-sdk",
9
9
  "license": "MIT",
10
10
  "repository": {
@@ -41,10 +41,10 @@
41
41
  "eventsource-parser": "4.1.0"
42
42
  },
43
43
  "peerDependencies": {
44
- "@alvin0/ai-agent-sdk-core": "^0.1.1"
44
+ "@alvin0/ai-agent-sdk-core": "^0.1.3"
45
45
  },
46
46
  "devDependencies": {
47
- "@alvin0/ai-agent-sdk-core": "^0.1.1",
47
+ "@alvin0/ai-agent-sdk-core": "^0.1.3",
48
48
  "@arethetypeswrong/cli": "0.18.5",
49
49
  "playwright": "1.62.1",
50
50
  "publint": "0.3.24",