@skailar-ai/sdk 0.0.3 → 0.0.4

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/streaming.ts","../src/resources/chat.ts","../src/resources/models.ts","../src/resources/images.ts","../src/internal/binary.ts","../src/resources/audio.ts","../src/resources/uploads.ts","../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;;;AAsCO,SAAS,eAAe,IAAA,EAAgC;AAC7D,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,KAAS,IAAA,EAAM;AAC7C,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAW,OAAA,EAAS,MAAA,EAAU;AAAA,EAC/C;AACA,EAAA,MAAM,IAAA,GAAO,IAAA;AACb,EAAA,MAAM,GAAA,GAAM,KAAK,OAAO,CAAA;AAExB,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3B,IAAA,MAAM,OAAA,GAAU,OAAO,IAAA,CAAK,SAAS,MAAM,QAAA,GAAY,IAAA,CAAK,SAAS,CAAA,GAAe,GAAA;AACpF,IAAA,OAAO,EAAE,IAAA,EAAM,GAAA,EAAK,OAAA,EAAQ;AAAA,EAC9B;AAEA,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,IAAA,EAAM;AAC3C,IAAA,MAAM,MAAA,GAAS,GAAA;AACf,IAAA,MAAM,OACJ,OAAO,MAAA,CAAO,MAAM,CAAA,KAAM,WACrB,MAAA,CAAO,MAAM,CAAA,GACd,OAAO,OAAO,MAAM,CAAA,KAAM,QAAA,GACvB,MAAA,CAAO,MAAM,CAAA,GACd,MAAA;AACR,IAAA,MAAM,OAAA,GACJ,OAAO,MAAA,CAAO,SAAS,MAAM,QAAA,GAAY,MAAA,CAAO,SAAS,CAAA,GAAe,MAAA;AAC1E,IAAA,OAAO,EAAE,MAAM,OAAA,EAAQ;AAA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y thrown by the Skailar SDK.\n *\n * Every failure surfaces as a subclass of {@link SkailarError}, so a single\n * `catch (err) { if (err instanceof SkailarError) ... }` covers the whole SDK.\n * Transport/network failures become {@link SkailarConnectionError}; any non-2xx\n * HTTP response becomes the most specific {@link SkailarAPIError} subclass for\n * its status code.\n *\n * @packageDocumentation\n */\n\n/**\n * Normalized shape extracted from a Skailar error response body.\n *\n * The gateway has been observed to return a flat body\n * (`{ \"error\": \"invalid_api_key\", \"message\": \"...\" }`) and, inside streams, a\n * nested body (`{ \"error\": { \"type\": \"...\", \"message\": \"...\" } }`).\n * {@link parseErrorBody} collapses both into this structure.\n */\nexport interface ParsedErrorBody {\n /** Machine-readable error code, e.g. `\"invalid_api_key\"`. */\n code: string | undefined;\n /** Human-readable error message. */\n message: string | undefined;\n}\n\n/**\n * Extract a `{ code, message }` pair from an arbitrary parsed error body.\n *\n * Tolerant of three layouts: flat (`{ error: \"code\", message: \"msg\" }`), nested\n * object (`{ error: { type|code, message } }`), and OpenAI-style\n * (`{ error: { code, message } }`). Unknown shapes yield two `undefined` values\n * rather than throwing.\n *\n * @param body - The already-JSON-parsed response body (or `undefined`).\n * @returns The normalized code and message, each possibly `undefined`.\n */\nexport function parseErrorBody(body: unknown): ParsedErrorBody {\n if (typeof body !== \"object\" || body === null) {\n return { code: undefined, message: undefined };\n }\n const root = body as Record<string, unknown>;\n const err = root[\"error\"];\n\n if (typeof err === \"string\") {\n const message = typeof root[\"message\"] === \"string\" ? (root[\"message\"] as string) : err;\n return { code: err, message };\n }\n\n if (typeof err === \"object\" && err !== null) {\n const nested = err as Record<string, unknown>;\n const code =\n typeof nested[\"type\"] === \"string\"\n ? (nested[\"type\"] as string)\n : typeof nested[\"code\"] === \"string\"\n ? (nested[\"code\"] as string)\n : undefined;\n const message =\n typeof nested[\"message\"] === \"string\" ? (nested[\"message\"] as string) : undefined;\n return { code, message };\n }\n\n const topMessage = typeof root[\"message\"] === \"string\" ? (root[\"message\"] as string) : undefined;\n return { code: undefined, message: topMessage };\n}\n\n/** Fields shared by the constructors of every concrete SDK error. */\ninterface SkailarErrorOptions {\n /** Human-readable message; falls back to a per-class default. */\n message?: string | undefined;\n /** Machine-readable error code from the response body, if any. */\n code?: string | undefined;\n /** Value of the response `x-request-id` header, if present. */\n requestId?: string | undefined;\n /** The raw response body (parsed JSON or raw text) for diagnostics. */\n raw?: unknown;\n /** Underlying cause, e.g. the original network error. */\n cause?: unknown;\n}\n\n/**\n * Abstract base class for all errors thrown by the Skailar SDK.\n *\n * Not thrown directly; serves as the common `instanceof` target. The `abstract`\n * marker forbids `new SkailarError()` while still allowing subclasses to call `super`.\n */\nexport abstract class SkailarError extends Error {\n /** HTTP status code, or `null` for non-HTTP failures (e.g. network). */\n readonly status: number | null;\n /** Machine-readable error code from the body, if any. */\n readonly code: string | undefined;\n /** Correlation id from the `x-request-id` response header, if any. */\n readonly requestId: string | undefined;\n /** The raw response body captured for debugging. */\n readonly raw: unknown;\n\n /**\n * @param status - HTTP status, or `null` when not applicable.\n * @param options - Message, code, request id, raw body and cause.\n */\n protected constructor(status: number | null, options: SkailarErrorOptions = {}) {\n super(options.message ?? \"Skailar SDK error\", { cause: options.cause });\n this.name = new.target.name;\n this.status = status;\n this.code = options.code;\n this.requestId = options.requestId;\n this.raw = options.raw;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Raised when the request never produced an HTTP response: DNS failures,\n * connection resets, TLS errors, and client-side timeouts/aborts driven by the\n * configured `timeout`. Its {@link SkailarError.status} is always `null`.\n */\nexport class SkailarConnectionError extends SkailarError {\n /** @param options - Message and originating cause. */\n constructor(options: { message?: string; cause?: unknown } = {}) {\n super(null, {\n message: options.message ?? \"Failed to connect to the Skailar API\",\n cause: options.cause,\n });\n }\n}\n\n/**\n * Base class for any non-2xx HTTP response from the gateway.\n * {@link SkailarAPIError.from} is the factory that inspects the status code and\n * returns the most specific subclass.\n */\nexport class SkailarAPIError extends SkailarError {\n /**\n * @param status - The HTTP status code of the response.\n * @param options - Message, code, request id and raw body.\n */\n constructor(status: number, options: SkailarErrorOptions = {}) {\n super(status, options);\n }\n\n /**\n * Build the most specific {@link SkailarAPIError} subclass for a status code.\n *\n * @param status - The HTTP status code returned by the gateway.\n * @param parsed - The normalized `{ code, message }` from {@link parseErrorBody}.\n * @param requestId - The `x-request-id` header value, if present.\n * @param raw - The raw response body for diagnostics.\n * @param retryAfter - Seconds from a `Retry-After` header, for 429 responses.\n * @returns A {@link SkailarAuthError}, {@link SkailarBadRequestError},\n * {@link SkailarNotFoundError}, {@link SkailarRateLimitError},\n * {@link SkailarUpstreamError}, or a plain {@link SkailarAPIError}.\n */\n static from(\n status: number,\n parsed: ParsedErrorBody,\n requestId: string | undefined,\n raw: unknown,\n retryAfter?: number | undefined,\n ): SkailarAPIError {\n const options: SkailarErrorOptions = {\n message: parsed.message,\n code: parsed.code,\n requestId,\n raw,\n };\n switch (status) {\n case 401:\n return new SkailarAuthError(options);\n case 400:\n return new SkailarBadRequestError(options);\n case 404:\n return new SkailarNotFoundError(options);\n case 429:\n return new SkailarRateLimitError({ ...options, retryAfter });\n default:\n if (status >= 500) return new SkailarUpstreamError(status, options);\n return new SkailarAPIError(status, options);\n }\n }\n}\n\n/** HTTP 401 — the API key is missing, malformed, or revoked. */\nexport class SkailarAuthError extends SkailarAPIError {\n /** @param options - Error details. */\n constructor(options: SkailarErrorOptions = {}) {\n super(401, { message: \"Invalid or missing API key\", ...options });\n }\n}\n\n/** HTTP 400 — the request was malformed or failed validation. */\nexport class SkailarBadRequestError extends SkailarAPIError {\n /** @param options - Error details. */\n constructor(options: SkailarErrorOptions = {}) {\n super(400, { message: \"Bad request\", ...options });\n }\n}\n\n/** HTTP 404 — the requested resource (e.g. a model id) does not exist. */\nexport class SkailarNotFoundError extends SkailarAPIError {\n /** @param options - Error details. */\n constructor(options: SkailarErrorOptions = {}) {\n super(404, { message: \"Resource not found\", ...options });\n }\n}\n\n/**\n * HTTP 429 — the account exceeded its rate limit.\n *\n * When the gateway provides a `Retry-After` header, its value (in seconds) is\n * exposed as {@link SkailarRateLimitError.retryAfter} and honored by the\n * client's automatic retry logic.\n */\nexport class SkailarRateLimitError extends SkailarAPIError {\n /** Seconds to wait before retrying, parsed from `Retry-After`; `undefined` if absent/unparseable. */\n readonly retryAfter: number | undefined;\n\n /** @param options - Error details plus the optional `retryAfter` seconds. */\n constructor(options: SkailarErrorOptions & { retryAfter?: number | undefined } = {}) {\n super(429, { message: \"Rate limit exceeded\", ...options });\n this.retryAfter = options.retryAfter;\n }\n}\n\n/**\n * HTTP 5xx — the upstream model provider failed or timed out. The gateway\n * propagates provider 5xx failures (502/503/504) with a structured body. These\n * are transient and are retried automatically.\n */\nexport class SkailarUpstreamError extends SkailarAPIError {\n /**\n * @param status - The specific 5xx status code.\n * @param options - Error details.\n */\n constructor(status: number, options: SkailarErrorOptions = {}) {\n super(status, { message: \"Upstream provider error\", ...options });\n }\n}\n","/**\n * A dependency-free Server-Sent Events parser and the {@link ChatCompletionStream}\n * wrapper that exposes a chat completion SSE response as an abortable async iterable.\n *\n * @packageDocumentation\n */\n\nimport { SkailarAPIError, SkailarConnectionError, parseErrorBody } from \"./errors\";\nimport type { ChatCompletionChunk } from \"./types/chat\";\n\n/**\n * Incrementally decode a byte stream into SSE `data:` payload strings, in\n * arrival order, excluding the terminal `[DONE]` sentinel.\n *\n * Implements just the slice of the SSE grammar the gateway emits: UTF-8 `data:`\n * lines separated by `\\n`, events delimited by blank lines, terminated by a\n * literal `data: [DONE]`. A partial line left in the buffer across reads is\n * preserved and completed by the next chunk. Comment lines (`:` prefix) and\n * non-`data:` fields are ignored. Yielding stops at `[DONE]`; reaching\n * end-of-stream without `[DONE]` simply ends the generator.\n *\n * On any exit — normal completion, `[DONE]`, an error, or the consumer\n * abandoning the `for await` early — the reader is cancelled before its lock is\n * released, so the underlying fetch connection is torn down instead of leaving\n * bytes streaming from the network.\n *\n * @param stream - The response body as a stream of UTF-8 encoded bytes.\n * @param signal - Optional abort signal; aborting rejects the iteration.\n * @returns An async generator yielding the raw string after each `data:` field.\n * @throws {@link SkailarConnectionError} If the underlying read is aborted or fails.\n */\nexport async function* parseSSE(\n stream: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncGenerator<string, void, unknown> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n if (signal?.aborted) {\n throw new SkailarConnectionError({ message: \"Stream aborted\", cause: signal.reason });\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n let newlineIndex: number;\n while ((newlineIndex = buffer.indexOf(\"\\n\")) !== -1) {\n const rawLine = buffer.slice(0, newlineIndex);\n buffer = buffer.slice(newlineIndex + 1);\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n\n if (line === \"\" || line.startsWith(\":\")) continue;\n if (!line.startsWith(\"data:\")) continue;\n\n const data = line.slice(5).trimStart();\n if (data === \"[DONE]\") return;\n yield data;\n }\n }\n\n const tail = buffer.trim();\n if (tail.startsWith(\"data:\")) {\n const data = tail.slice(5).trimStart();\n if (data !== \"[DONE]\" && data !== \"\") yield data;\n }\n } catch (err) {\n if (err instanceof SkailarConnectionError) throw err;\n throw new SkailarConnectionError({ message: \"Stream read failed\", cause: err });\n } finally {\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n\n/**\n * An abortable async iterable of {@link ChatCompletionChunk} values, returned by\n * `chat.completions.create({ stream: true })`.\n *\n * Iterate it with `for await`; each iteration yields one decoded chunk. Mirrors\n * the ergonomics of `openai-node`'s stream, including the {@link ChatCompletionStream.controller}\n * for cancellation.\n *\n * @example\n * ```ts\n * const stream = await client.chat.completions.create({\n * model: \"gemini-2.5-flash-lite\",\n * messages: [{ role: \"user\", content: \"hi\" }],\n * stream: true,\n * });\n * for await (const chunk of stream) {\n * process.stdout.write(chunk.choices[0]?.delta?.content ?? \"\");\n * }\n * ```\n */\nexport class ChatCompletionStream implements AsyncIterable<ChatCompletionChunk> {\n /**\n * The {@link AbortController} governing the underlying HTTP request. Call\n * `stream.controller.abort()` to cancel an in-flight stream; the active\n * `for await` loop then terminates promptly.\n */\n readonly controller: AbortController;\n\n /** The raw SSE byte stream backing this iterator. */\n private readonly body: ReadableStream<Uint8Array>;\n\n /**\n * @param body - The response body stream of SSE bytes.\n * @param controller - The abort controller tied to the originating request.\n */\n constructor(body: ReadableStream<Uint8Array>, controller: AbortController) {\n this.body = body;\n this.controller = controller;\n }\n\n /**\n * Decode the SSE byte stream into typed chunks.\n *\n * Each `data:` payload is `JSON.parse`d. If a payload carries an `error` field\n * (the gateway's in-band failure signal), iteration throws the corresponding\n * {@link SkailarAPIError} instead of yielding. Malformed JSON payloads are\n * skipped defensively.\n *\n * @returns An async generator over {@link ChatCompletionChunk} values.\n * @throws {@link SkailarAPIError} When the stream delivers an in-band error event.\n * @throws {@link SkailarConnectionError} When the stream is aborted or read fails.\n */\n private async *decode(): AsyncGenerator<ChatCompletionChunk, void, unknown> {\n for await (const data of parseSSE(this.body, this.controller.signal)) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n continue;\n }\n\n if (parsed !== null && typeof parsed === \"object\" && \"error\" in parsed) {\n const { code, message } = parseErrorBody(parsed);\n throw SkailarAPIError.from(\n 500,\n { code, message: message ?? \"Streaming error\" },\n undefined,\n parsed,\n );\n }\n\n yield parsed as ChatCompletionChunk;\n }\n }\n\n /**\n * Iterate the decoded chunks. Abandoning the iteration early (a `break` or\n * `return` inside a `for await`) invokes the returned iterator's `return()`,\n * which aborts {@link ChatCompletionStream.controller} so the underlying fetch\n * request is cancelled — not merely the body reader — and then runs the\n * generator's own cleanup ({@link parseSSE}'s `finally`: reader cancel +\n * lock release). Normal completion and thrown errors are unaffected.\n *\n * @returns An async iterator over {@link ChatCompletionChunk} values.\n */\n [Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n const inner = this.decode();\n const controller = this.controller;\n return {\n next: () => inner.next(),\n async return(value?: unknown): Promise<IteratorResult<ChatCompletionChunk>> {\n controller.abort();\n if (inner.return) await inner.return(value as undefined);\n return { done: true, value: undefined };\n },\n throw: (err) => (inner.throw ? inner.throw(err) : Promise.reject(err)),\n };\n }\n}\n","/**\n * The chat resource, exposing `client.chat.completions.create(...)` with the\n * same call shape as `openai`'s chat completions.\n *\n * @packageDocumentation\n */\n\nimport type { RequestOptions, Skailar } from \"../client\";\nimport type { ChatCompletionStream } from \"../streaming\";\nimport type {\n ChatCompletion,\n ChatCompletionRequest,\n} from \"../types/chat\";\n\n/** A chat completion request that explicitly opts into streaming. */\ninterface StreamingRequest extends ChatCompletionRequest {\n stream: true;\n}\n\n/** A chat completion request that does not stream. */\ninterface NonStreamingRequest extends ChatCompletionRequest {\n stream?: false;\n}\n\n/**\n * The `completions` sub-namespace of the chat resource. Holds\n * {@link ChatCompletions.create}, whose return type is narrowed by the `stream`\n * field of the request via overloads.\n */\nexport class ChatCompletions {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Create a buffered (non-streamed) chat completion.\n *\n * @param body - The request with `stream` omitted or `false`.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns The fully-formed {@link ChatCompletion}.\n */\n create(body: NonStreamingRequest, options?: RequestOptions): Promise<ChatCompletion>;\n /**\n * Create a streamed chat completion.\n *\n * @param body - The request with `stream: true`.\n * @param options - Optional per-call signal, timeout and headers. The stream\n * is also cancellable via its `.controller`.\n * @returns A {@link ChatCompletionStream} async-iterable of chunks, exposing\n * `.controller` for cancellation.\n */\n create(body: StreamingRequest, options?: RequestOptions): Promise<ChatCompletionStream>;\n /**\n * Create a chat completion whose mode is chosen at runtime. Use this form when\n * `stream` is a non-literal `boolean` (e.g. `stream: shouldStream`), where the\n * concrete return type cannot be known at compile time; narrow the result with\n * `instanceof ChatCompletionStream` or by checking the `stream` flag yourself.\n *\n * @param body - The request with a dynamic `stream` boolean.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns Either a {@link ChatCompletion} or a {@link ChatCompletionStream}.\n */\n create(\n body: ChatCompletionRequest & { stream?: boolean },\n options?: RequestOptions,\n ): Promise<ChatCompletion | ChatCompletionStream>;\n /**\n * Implementation backing the public overloads.\n *\n * @param body - The chat completion request.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns Either a {@link ChatCompletion} or a {@link ChatCompletionStream}\n * depending on `body.stream`.\n * @throws {@link SkailarBadRequestError} On HTTP 400 (malformed request).\n * @throws {@link SkailarAuthError} On HTTP 401 (bad key).\n * @throws {@link SkailarRateLimitError} On HTTP 429 (after exhausting retries).\n * @throws {@link SkailarUpstreamError} On HTTP 5xx (after exhausting retries).\n * @throws {@link SkailarConnectionError} On network failure, timeout or abort.\n */\n create(\n body: ChatCompletionRequest,\n options?: RequestOptions,\n ): Promise<ChatCompletion> | Promise<ChatCompletionStream> {\n if (body.stream === true) {\n return this.client.request({\n method: \"POST\",\n path: \"/v1/chat/completions\",\n body,\n expect: \"stream\",\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n return this.client.request<ChatCompletion>({\n method: \"POST\",\n path: \"/v1/chat/completions\",\n body,\n expect: \"json\",\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n}\n\n/** The chat resource root, mirroring `openai`'s `client.chat`. */\nexport class ChatResource {\n /** The chat completions namespace. */\n readonly completions: ChatCompletions;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.completions = new ChatCompletions(client);\n }\n}\n","/**\n * The models resource, exposing `client.models.list()` and\n * `client.models.retrieve(id)`.\n *\n * @packageDocumentation\n */\n\nimport type { RequestOptions, Skailar } from \"../client\";\nimport type { Model, ModelList, ModelSummary } from \"../types/models\";\n\n/** Model discovery operations. */\nexport class ModelsResource {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * List every model the gateway can route to. Unwraps the\n * `{ object: \"list\", data }` envelope and returns just `data` as a plain array.\n *\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to the array of {@link ModelSummary} cards.\n */\n async list(options?: RequestOptions): Promise<ModelSummary[]> {\n const res = await this.client.request<ModelList>({\n method: \"GET\",\n path: \"/v1/models\",\n expect: \"json\",\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n return res.data;\n }\n\n /**\n * Retrieve the full detail card for a single model.\n *\n * @param id - The model identifier; may contain slashes (e.g.\n * `\"google/gemini-2.5-pro\"`), which are preserved in the path.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to the {@link Model} detail.\n * @throws {@link SkailarNotFoundError} If no model matches the id.\n */\n retrieve(id: string, options?: RequestOptions): Promise<Model> {\n const encoded = id.split(\"/\").map(encodeURIComponent).join(\"/\");\n return this.client.request<Model>({\n method: \"GET\",\n path: `/v1/models/${encoded}`,\n expect: \"json\",\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n}\n","/**\n * The images resource, exposing `client.images.generate(...)`.\n *\n * @packageDocumentation\n */\n\nimport type { RequestOptions, Skailar } from \"../client\";\nimport type {\n ImageGenerationRequest,\n ImageGenerationResponse,\n} from \"../types/images\";\n\n/** Image generation operations. */\nexport class ImagesResource {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Generate one or more images from a text prompt. Named `generate` to match\n * `openai`'s `images.generate(...)`.\n *\n * @param body - The generation request; see {@link ImageGenerationRequest}.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to the {@link ImageGenerationResponse}, whose\n * `data` entries carry either a `url` or inline `b64_json`.\n * @throws {@link SkailarBadRequestError} On HTTP 400.\n * @throws {@link SkailarRateLimitError} On HTTP 429 (after exhausting retries).\n */\n generate(\n body: ImageGenerationRequest,\n options?: RequestOptions,\n ): Promise<ImageGenerationResponse> {\n return this.client.request<ImageGenerationResponse>({\n method: \"POST\",\n path: \"/v1/images/generations\",\n body,\n expect: \"json\",\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n}\n","/**\n * Internal helpers for normalizing caller-supplied binary payloads into the\n * base64 strings the Skailar gateway expects. Runtime-agnostic across Node 18+,\n * Bun, Deno and browsers.\n *\n * @packageDocumentation\n */\n\nimport type { BinaryInput } from \"../types/audio\";\n\n/**\n * Encode a byte array as a standard (non-URL-safe) base64 string, without any\n * `data:` prefix.\n *\n * Prefers Node's `Buffer` when present (fast path on Node/Bun) and otherwise\n * falls back to `btoa` over a binary string, chunked to avoid call-stack limits\n * on large inputs in browser/Deno environments.\n *\n * @param bytes - The raw bytes to encode.\n * @returns The base64 representation.\n */\nfunction bytesToBase64(bytes: Uint8Array): string {\n const maybeBuffer = (globalThis as { Buffer?: typeof import(\"node:buffer\").Buffer }).Buffer;\n if (maybeBuffer) {\n return maybeBuffer.from(bytes).toString(\"base64\");\n }\n\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n const chunk = bytes.subarray(i, i + chunkSize);\n binary += String.fromCharCode(...chunk);\n }\n return btoa(binary);\n}\n\n/**\n * Normalize any {@link BinaryInput} into a base64 string (no `data:` prefix).\n *\n * A `string` input is assumed to be pre-encoded base64 and returned unchanged. A\n * {@link Blob} is read via its async `arrayBuffer()`; `ArrayBuffer` and\n * `Uint8Array` are encoded directly. This lets the public API accept whichever\n * representation the caller already holds.\n *\n * @remarks\n * A `string` is taken literally as already-encoded base64 and is **not**\n * validated. Passing raw text (e.g. `\"hello world\"`) is silently forwarded to\n * the gateway, which will decode it as base64 and produce corrupt bytes or a\n * `400`. Pass a {@link Uint8Array} / {@link ArrayBuffer} / {@link Blob} when you\n * hold raw bytes; reserve the `string` form for values you have already encoded.\n *\n * @param input - The payload as bytes, a buffer, a {@link Blob}, or a base64 string.\n * @returns A promise resolving to the base64 string.\n */\nexport async function toBase64(input: BinaryInput): Promise<string> {\n if (typeof input === \"string\") return input;\n if (input instanceof Uint8Array) return bytesToBase64(input);\n if (input instanceof ArrayBuffer) return bytesToBase64(new Uint8Array(input));\n if (typeof Blob !== \"undefined\" && input instanceof Blob) {\n const buffer = await input.arrayBuffer();\n return bytesToBase64(new Uint8Array(buffer));\n }\n throw new TypeError(\"Unsupported binary input; expected Uint8Array, ArrayBuffer, Blob or base64 string\");\n}\n","/**\n * The audio resource, exposing `client.audio.transcriptions.create(...)` and\n * `client.audio.speech.create(...)`.\n *\n * @packageDocumentation\n */\n\nimport type { RequestOptions, Skailar } from \"../client\";\nimport { SkailarConnectionError } from \"../errors\";\nimport { toBase64 } from \"../internal/binary\";\nimport type {\n SpeechCreateParams,\n TranscriptionCreateParams,\n TranscriptionResponse,\n} from \"../types/audio\";\n\n/** Audio transcription operations (speech-to-text, Whisper-backed). */\nexport class AudioTranscriptions {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Transcribe an audio clip to text. The supplied bytes are base64-encoded\n * client-side into the gateway's `base64` field. When `mime` is omitted and\n * `file` is a {@link Blob} carrying a `type`, that type is used; otherwise the\n * gateway default (`audio/wav`) applies.\n *\n * @param params - The audio and its MIME type; see {@link TranscriptionCreateParams}.\n * `file` may be a {@link Uint8Array}, {@link ArrayBuffer}, {@link Blob} or a\n * pre-encoded base64 string.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to the {@link TranscriptionResponse}.\n */\n async create(\n params: TranscriptionCreateParams,\n options?: RequestOptions,\n ): Promise<TranscriptionResponse> {\n const base64 = await toBase64(params.file);\n const mime =\n params.mime ??\n (typeof Blob !== \"undefined\" && params.file instanceof Blob && params.file.type\n ? (params.file.type as TranscriptionCreateParams[\"mime\"])\n : undefined);\n return this.client.request<TranscriptionResponse>({\n method: \"POST\",\n path: \"/v1/audio/transcriptions\",\n body: { base64, mime },\n expect: \"json\",\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n}\n\n/** Speech synthesis operations (text-to-speech). */\nexport class AudioSpeech {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Synthesize speech and return the raw MP3 audio stream. Unlike the JSON\n * endpoints, this returns the response body stream directly so large audio\n * payloads need not be buffered in memory.\n *\n * Pass `options.signal` to cancel the request: aborting it before the response\n * arrives rejects this call, and aborting it while the MP3 is still downloading\n * tears down the underlying connection so the body stops mid-stream.\n *\n * @param params - The text and voice; see {@link SpeechCreateParams}.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to a `ReadableStream<Uint8Array>` of\n * `audio/mpeg` bytes, suitable for piping to a file, an HTTP response, or an\n * audio element.\n * @throws {@link SkailarConnectionError} If the response unexpectedly lacks a body.\n * @throws {@link SkailarBadRequestError} On HTTP 400 (e.g. text exceeding 4000 chars).\n */\n async create(\n params: SpeechCreateParams,\n options?: RequestOptions,\n ): Promise<ReadableStream<Uint8Array>> {\n const response = await this.client.request({\n method: \"POST\",\n path: \"/v1/audio/speech\",\n body: { input: params.input, voice: params.voice },\n headers: { Accept: \"audio/mpeg\", ...options?.headers },\n expect: \"response\",\n signal: options?.signal,\n timeout: options?.timeout,\n });\n if (!response.body) {\n throw new SkailarConnectionError({ message: \"Speech response had no audio body\" });\n }\n return response.body;\n }\n}\n\n/** The audio resource root, grouping transcription and speech. */\nexport class AudioResource {\n /** Speech-to-text operations. */\n readonly transcriptions: AudioTranscriptions;\n /** Text-to-speech operations. */\n readonly speech: AudioSpeech;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.transcriptions = new AudioTranscriptions(client);\n this.speech = new AudioSpeech(client);\n }\n}\n","/**\n * The uploads resource, exposing `client.uploads.images.create(...)` and\n * `client.uploads.files.create(...)` for storing assets in Skailar storage and\n * receiving an embeddable URL.\n *\n * @packageDocumentation\n */\n\nimport type { Skailar } from \"../client\";\nimport { toBase64 } from \"../internal/binary\";\nimport type {\n FileUploadCreateParams,\n ImageUploadCreateParams,\n UploadResponse,\n} from \"../types/uploads\";\n\n/** Image upload operations (`POST /v1/uploads/images`). */\nexport class ImageUploads {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Upload an image and obtain a URL usable as vision input. `data` may be a\n * {@link Uint8Array}, {@link ArrayBuffer}, {@link Blob} or a pre-encoded base64\n * string; it is base64-encoded client-side into the gateway's `base64` field.\n *\n * @param params - The image bytes and content type; see {@link ImageUploadCreateParams}.\n * @returns A promise resolving to the {@link UploadResponse} whose `url` can be\n * embedded in a chat completion as an `image_url` content part.\n */\n async create(params: ImageUploadCreateParams): Promise<UploadResponse> {\n const base64 = await toBase64(params.data);\n return this.client.request<UploadResponse>({\n method: \"POST\",\n path: \"/v1/uploads/images\",\n body: { base64, content_type: params.contentType },\n expect: \"json\",\n });\n }\n}\n\n/** File upload operations (`POST /v1/uploads/files`). */\nexport class FileUploads {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Upload a document (`application/pdf` or `text/plain`). `data` accepts the\n * same forms as image upload and is base64-encoded client-side.\n *\n * @param params - The document bytes and content type; see {@link FileUploadCreateParams}.\n * @returns A promise resolving to the {@link UploadResponse} with the stored asset URL.\n */\n async create(params: FileUploadCreateParams): Promise<UploadResponse> {\n const base64 = await toBase64(params.data);\n return this.client.request<UploadResponse>({\n method: \"POST\",\n path: \"/v1/uploads/files\",\n body: { base64, content_type: params.contentType },\n expect: \"json\",\n });\n }\n}\n\n/** The uploads resource root, grouping image and file uploads. */\nexport class UploadsResource {\n /** Image upload operations. */\n readonly images: ImageUploads;\n /** File/document upload operations. */\n readonly files: FileUploads;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.images = new ImageUploads(client);\n this.files = new FileUploads(client);\n }\n}\n","/**\n * The {@link Skailar} client: configuration, the shared fetch dispatch pipeline\n * (timeout, retry with backoff, error mapping) and the resource namespaces hung\n * off it.\n *\n * @packageDocumentation\n */\n\nimport {\n SkailarConnectionError,\n SkailarAPIError,\n SkailarRateLimitError,\n parseErrorBody,\n} from \"./errors\";\nimport { ChatCompletionStream } from \"./streaming\";\nimport { ChatResource } from \"./resources/chat\";\nimport { ModelsResource } from \"./resources/models\";\nimport { ImagesResource } from \"./resources/images\";\nimport { AudioResource } from \"./resources/audio\";\nimport { UploadsResource } from \"./resources/uploads\";\nimport type { PingKeyResponse } from \"./types/index\";\n\n/**\n * Configuration accepted by the {@link Skailar} constructor. Every field is\n * optional; omitted fields fall back to environment variables or library\n * defaults as documented per property.\n */\nexport interface SkailarOptions {\n /**\n * Skailar API key of the form `skl_live_<43 url-safe base64 chars>`. Defaults\n * to `process.env.SKAILAR_API_KEY`; if neither is provided the constructor throws.\n *\n * @remarks\n * The format is **not** validated locally — only emptiness is checked. A\n * malformed or wrong-provider key (e.g. an OpenAI `sk-...` key passed by\n * mistake) is accepted here and rejected at the first request with a\n * {@link SkailarAuthError} (HTTP 401).\n */\n apiKey?: string;\n /**\n * Base URL of the gateway, without a trailing `/v1` (default\n * `\"https://api.skailar.com\"`). The `/v1/...` path is appended by the SDK.\n * Point this at `http://localhost:8080` for a local gateway.\n */\n baseURL?: string;\n /**\n * Per-request timeout in milliseconds (default `60000`). Applies to each\n * attempt independently; a timed-out attempt becomes a\n * {@link SkailarConnectionError} and is eligible for retry.\n */\n timeout?: number;\n /**\n * Maximum automatic retries for transient failures (default `2`). Retries\n * apply only to HTTP 429, HTTP 5xx, and connection errors; non-429 4xx\n * responses are never retried.\n */\n maxRetries?: number;\n /**\n * Custom `fetch` implementation, primarily for testing (default global\n * `fetch`). No binding is applied; pass an already-bound function if your\n * implementation requires a specific receiver.\n */\n fetch?: typeof fetch;\n /**\n * Headers merged into every request. The SDK's own `Authorization`,\n * `Content-Type` and `Accept`, plus explicit per-call headers, take precedence.\n */\n defaultHeaders?: Record<string, string>;\n}\n\n/**\n * Per-call request options accepted as the trailing argument of every resource\n * method (e.g. `chat.completions.create(body, options)`). Mirrors the\n * `openai-node` convention so the wire body stays separate from transport\n * concerns. Every field is optional and overrides the client-level default for\n * this one call.\n */\nexport interface RequestOptions {\n /**\n * Signal to cancel this call. Aborting before the response arrives rejects the\n * call with a {@link SkailarConnectionError}; for streaming/audio bodies,\n * aborting mid-transfer tears down the connection.\n */\n signal?: AbortSignal;\n /**\n * Per-call timeout in milliseconds, overriding {@link SkailarOptions.timeout}\n * for this request only.\n */\n timeout?: number;\n /** Extra headers merged into this request, overriding client defaults. */\n headers?: Record<string, string>;\n}\n\n/** Internal description of a single HTTP request to dispatch. */\ninterface InternalRequest {\n method: \"GET\" | \"POST\";\n /** Path beginning with `/v1/...`, relative to {@link SkailarOptions.baseURL}. */\n path: string;\n /** Optional JSON body; serialized with `JSON.stringify`. */\n body?: unknown;\n /** Extra headers for this request only. */\n headers?: Record<string, string>;\n /** Expected response handling: parsed JSON, raw `Response`, or SSE stream. */\n expect: \"json\" | \"response\" | \"stream\";\n /**\n * External abort signal composed with the timeout. Used for streaming, where\n * the caller-visible {@link ChatCompletionStream.controller} drives cancellation.\n */\n signal?: AbortSignal;\n /** Per-call timeout override in ms; falls back to {@link Skailar.timeout}. */\n timeout?: number;\n}\n\n/**\n * Sleep for the given duration, rejecting early if the signal aborts.\n *\n * @param ms - Milliseconds to wait.\n * @param signal - Optional signal that, when aborted, rejects the sleep.\n * @returns A promise resolving after `ms`, or rejecting on abort.\n */\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new SkailarConnectionError({ message: \"Aborted\", cause: signal.reason }));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(new SkailarConnectionError({ message: \"Aborted\", cause: signal?.reason }));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/**\n * Parse a `Retry-After` header value into seconds — the header's native unit\n * and the unit exposed on {@link SkailarRateLimitError.retryAfter}. Call sites\n * that need a millisecond delay multiply by 1000 themselves.\n *\n * @param header - The raw header value, a number of seconds or an HTTP date.\n * @returns The delay in seconds, or `undefined` if absent/unparseable.\n */\nfunction parseRetryAfter(header: string | null): number | undefined {\n if (!header) return undefined;\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return Math.max(0, seconds);\n const date = Date.parse(header);\n if (Number.isFinite(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Wrap a byte stream so `onDone` runs exactly once when it terminates — whether\n * it closes normally, errors, or is cancelled by the consumer. Used to detach\n * the external-abort listener for `response`/`stream` results whose body outlives\n * the {@link Skailar.request} call, so a long-lived caller `AbortSignal` does not\n * accumulate listeners across requests.\n *\n * @param source - The original response body stream.\n * @param onDone - Idempotent cleanup to run on terminal state.\n * @returns A stream that mirrors `source` and triggers `onDone` when finished.\n */\nfunction withCleanup(\n source: ReadableStream<Uint8Array>,\n onDone: () => void,\n): ReadableStream<Uint8Array> {\n let done = false;\n const finish = () => {\n if (done) return;\n done = true;\n onDone();\n };\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done: streamDone, value } = await reader.read();\n if (streamDone) {\n finish();\n controller.close();\n return;\n }\n controller.enqueue(value);\n } catch (err) {\n finish();\n controller.error(err);\n }\n },\n async cancel(reason) {\n finish();\n await reader.cancel(reason);\n },\n });\n}\n\n/**\n * Read the request-correlation id from a response's headers, checking the common\n * header spellings so the id is captured regardless of casing convention.\n *\n * @param headers - The response headers.\n * @returns The first present correlation id, or `undefined`.\n */\nfunction extractRequestId(headers: Headers): string | undefined {\n return (\n headers.get(\"x-request-id\") ??\n headers.get(\"x-skailar-request-id\") ??\n headers.get(\"request-id\") ??\n undefined\n );\n}\n\n/**\n * The official Skailar API client. Construct once and reuse. Resource namespaces\n * ({@link Skailar.chat}, {@link Skailar.models}, etc.) provide the\n * OpenAI-compatible and Skailar-native operations. All network access flows\n * through {@link Skailar.request}, which centralizes authentication, timeouts,\n * retries and error mapping.\n *\n * @example\n * ```ts\n * import Skailar from \"@skailar-ai/sdk\";\n * const client = new Skailar({ apiKey: \"skl_live_...\" });\n * const res = await client.chat.completions.create({\n * model: \"claude-sonnet-4-6\",\n * messages: [{ role: \"user\", content: \"Hello!\" }],\n * });\n * console.log(res.choices[0]?.message.content);\n * ```\n */\nexport class Skailar {\n /** Resolved API key sent as the bearer token. */\n readonly apiKey: string;\n /** Resolved base URL with any trailing slash removed. */\n readonly baseURL: string;\n /** Resolved per-attempt timeout in milliseconds. */\n readonly timeout: number;\n /** Resolved maximum retry count. */\n readonly maxRetries: number;\n /** Default headers merged into every request. */\n readonly defaultHeaders: Record<string, string>;\n\n /** The `fetch` implementation used for all requests. */\n private readonly fetchImpl: typeof fetch;\n\n /** Chat completions (OpenAI-compatible). */\n readonly chat: ChatResource;\n /** Model discovery. */\n readonly models: ModelsResource;\n /** Image generation. */\n readonly images: ImagesResource;\n /** Speech synthesis and transcription. */\n readonly audio: AudioResource;\n /** Direct uploads to Skailar storage. */\n readonly uploads: UploadsResource;\n\n /**\n * @param options - Client configuration; see {@link SkailarOptions}.\n * @throws If no API key is resolvable (neither `options.apiKey` nor\n * `SKAILAR_API_KEY`). A key that is present but malformed is **not** rejected\n * here; it fails at the first request with a {@link SkailarAuthError}.\n */\n constructor(options: SkailarOptions = {}) {\n const env =\n typeof process !== \"undefined\" && process.env ? process.env[\"SKAILAR_API_KEY\"] : undefined;\n const apiKey = options.apiKey ?? env;\n if (!apiKey) {\n throw new Error(\n \"Missing Skailar API key. Pass { apiKey } or set the SKAILAR_API_KEY environment variable.\",\n );\n }\n\n this.apiKey = apiKey;\n this.baseURL = (options.baseURL ?? \"https://api.skailar.com\").replace(/\\/+$/, \"\");\n this.timeout = options.timeout ?? 60_000;\n this.maxRetries = options.maxRetries ?? 2;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n\n if (typeof this.fetchImpl !== \"function\") {\n throw new Error(\"No fetch implementation available; pass { fetch } explicitly.\");\n }\n\n this.chat = new ChatResource(this);\n this.models = new ModelsResource(this);\n this.images = new ImagesResource(this);\n this.audio = new AudioResource(this);\n this.uploads = new UploadsResource(this);\n }\n\n /**\n * Verify the configured API key against `GET /v1/ping-key`.\n *\n * @param options - Optional per-call signal, timeout and headers.\n * @returns The `{ status, user_id }` payload when the key is valid.\n * @throws {@link SkailarAuthError} If the key is missing, invalid or revoked.\n */\n ping(options?: RequestOptions): Promise<PingKeyResponse> {\n return this.request<PingKeyResponse>({\n method: \"GET\",\n path: \"/v1/ping-key\",\n expect: \"json\",\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n\n /**\n * Dispatch a request expecting a JSON body, with retries.\n *\n * @typeParam T - The expected shape of the parsed JSON response.\n * @param options - The request description.\n * @returns The parsed JSON response body typed as `T`.\n */\n request<T>(options: InternalRequest & { expect: \"json\" }): Promise<T>;\n /**\n * Dispatch a request expecting the raw {@link Response}, with retries.\n *\n * @param options - The request description.\n * @returns The successful `Response`, body unread (e.g. for audio streams).\n */\n request(options: InternalRequest & { expect: \"response\" }): Promise<Response>;\n /**\n * Dispatch a streaming request, returning a chat completion stream.\n *\n * @param options - The request description with `expect: \"stream\"`.\n * @returns A {@link ChatCompletionStream} over the SSE response.\n */\n request(options: InternalRequest & { expect: \"stream\" }): Promise<ChatCompletionStream>;\n /**\n * Core dispatch implementation shared by all resources.\n *\n * Applies, per attempt: header assembly with bearer auth, a timeout-derived\n * {@link AbortSignal} composed with any caller signal, execution of\n * {@link SkailarOptions.fetch}, and error mapping. Retries HTTP 429, HTTP 5xx\n * and transient connection failures up to {@link Skailar.maxRetries}, backing\n * off with full-jitter exponential delay and honoring a server `Retry-After`\n * when present. Non-429 4xx responses fail fast.\n *\n * Transport failures are reported as {@link SkailarConnectionError} with a\n * message distinguishing three causes: an external `signal` abort\n * (non-retryable), an internal timeout once {@link Skailar.timeout} elapses\n * (retryable), and a generic network failure (retryable).\n *\n * @param options - The request description.\n * @returns The parsed JSON, raw `Response`, or {@link ChatCompletionStream}\n * depending on `options.expect`.\n */\n async request(\n options: InternalRequest,\n ): Promise<unknown> {\n const url = `${this.baseURL}${options.path}`;\n const isStream = options.expect === \"stream\";\n const timeoutMs = options.timeout ?? this.timeout;\n let attempt = 0;\n\n while (true) {\n const controller = new AbortController();\n const onExternalAbort = () => controller.abort(options.signal?.reason);\n if (options.signal) {\n if (options.signal.aborted) controller.abort(options.signal.reason);\n else options.signal.addEventListener(\"abort\", onExternalAbort);\n }\n const detachExternal = () =>\n options.signal?.removeEventListener(\"abort\", onExternalAbort);\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort(new Error(\"Request timed out\"));\n }, timeoutMs);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method: options.method,\n headers: this.buildHeaders(options),\n body: options.body === undefined ? undefined : JSON.stringify(options.body),\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n detachExternal();\n const externallyAborted = options.signal?.aborted ?? false;\n const connErr = new SkailarConnectionError({\n message: externallyAborted\n ? \"Request aborted\"\n : timedOut\n ? `Request timed out after ${timeoutMs}ms`\n : \"Network request to the Skailar API failed\",\n cause: err,\n });\n if (externallyAborted || !this.shouldRetry(attempt)) throw connErr;\n attempt += 1;\n await delay(this.backoff(attempt), options.signal);\n continue;\n }\n\n clearTimeout(timer);\n\n if (!response.ok) {\n detachExternal();\n const apiError = await this.toApiError(response);\n const retryAfterMs =\n apiError instanceof SkailarRateLimitError && apiError.retryAfter !== undefined\n ? apiError.retryAfter * 1000\n : undefined;\n if (this.isRetryableStatus(response.status) && this.shouldRetry(attempt)) {\n attempt += 1;\n await delay(retryAfterMs ?? this.backoff(attempt), options.signal);\n continue;\n }\n throw apiError;\n }\n\n if (isStream || options.expect === \"response\") {\n if (!response.body) {\n detachExternal();\n throw new SkailarConnectionError({\n message: isStream ? \"Streaming response had no body\" : \"Response had no body\",\n });\n }\n const body = withCleanup(response.body, detachExternal);\n if (isStream) return new ChatCompletionStream(body, controller);\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n\n detachExternal();\n return (await response.json()) as unknown;\n }\n }\n\n /**\n * Assemble the outgoing header set for a request, applying defaults, auth,\n * content-type and accept in precedence order.\n *\n * @param options - The request description.\n * @returns The header record to send.\n */\n private buildHeaders(options: InternalRequest): Record<string, string> {\n const headers: Record<string, string> = {\n ...this.defaultHeaders,\n Authorization: `Bearer ${this.apiKey}`,\n Accept: options.expect === \"stream\" ? \"text/event-stream\" : \"application/json\",\n };\n if (options.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n if (options.headers) Object.assign(headers, options.headers);\n return headers;\n }\n\n /**\n * Convert a non-2xx {@link Response} into the most specific\n * {@link SkailarAPIError} subclass. Reads the body once, attempting JSON first\n * and falling back to raw text, then defers classification to\n * {@link SkailarAPIError.from}.\n *\n * @param response - The failed HTTP response.\n * @returns The mapped error.\n */\n private async toApiError(response: Response): Promise<SkailarAPIError> {\n const text = await response.text().catch(() => \"\");\n let raw: unknown = text;\n try {\n raw = text ? JSON.parse(text) : undefined;\n } catch {\n raw = text;\n }\n const parsed = parseErrorBody(raw);\n const requestId = extractRequestId(response.headers);\n const retryAfter =\n response.status === 429 ? parseRetryAfter(response.headers.get(\"retry-after\")) : undefined;\n return SkailarAPIError.from(response.status, parsed, requestId, raw, retryAfter);\n }\n\n /**\n * Whether a status code is eligible for automatic retry (429 and any 5xx).\n *\n * @param status - The HTTP status code.\n * @returns `true` if retryable.\n */\n private isRetryableStatus(status: number): boolean {\n return status === 429 || status >= 500;\n }\n\n /**\n * Whether another attempt remains within the retry budget.\n *\n * @param attempt - The count of attempts already made (before increment).\n * @returns `true` if a retry is permitted.\n */\n private shouldRetry(attempt: number): boolean {\n return attempt < this.maxRetries;\n }\n\n /**\n * Compute a full-jitter exponential backoff delay: a random value in\n * `[0, min(cap, base * 2^attempt))`, capped at 8000ms. Jitter spreads retries\n * from many clients to avoid synchronized thundering-herd load on the gateway.\n *\n * @param attempt - The retry number, starting at 1 for the first retry.\n * @returns A randomized delay in milliseconds.\n */\n private backoff(attempt: number): number {\n const base = 500;\n const cap = 8000;\n const exponential = Math.min(cap, base * 2 ** attempt);\n return Math.random() * exponential;\n }\n}\n","/**\n * Public entry point of the Skailar TypeScript SDK.\n *\n * Exports {@link Skailar} as both the default and a named export, the full typed\n * error hierarchy, the {@link ChatCompletionStream} helper, and every public\n * request/response type.\n *\n * @example Default import\n * ```ts\n * import Skailar from \"@skailar-ai/sdk\";\n * const client = new Skailar({ apiKey: \"skl_live_...\" });\n * ```\n *\n * @example Named imports\n * ```ts\n * import { Skailar, SkailarError, SkailarRateLimitError } from \"@skailar-ai/sdk\";\n * ```\n *\n * @packageDocumentation\n */\n\nimport { Skailar } from \"./client\";\n\nexport { Skailar };\nexport type { SkailarOptions, RequestOptions } from \"./client\";\n\nexport default Skailar;\n\nexport {\n SkailarError,\n SkailarAPIError,\n SkailarAuthError,\n SkailarBadRequestError,\n SkailarNotFoundError,\n SkailarRateLimitError,\n SkailarUpstreamError,\n SkailarConnectionError,\n} from \"./errors\";\nexport type { ParsedErrorBody } from \"./errors\";\n\nexport { ChatCompletionStream, parseSSE } from \"./streaming\";\n\nexport type * from \"./types/index\";\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/streaming.ts","../src/resources/chat.ts","../src/resources/models.ts","../src/resources/images.ts","../src/internal/binary.ts","../src/resources/audio.ts","../src/resources/uploads.ts","../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;;;AAsCO,SAAS,eAAe,IAAA,EAAgC;AAC7D,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,KAAS,IAAA,EAAM;AAC7C,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAW,OAAA,EAAS,MAAA,EAAU;AAAA,EAC/C;AACA,EAAA,MAAM,IAAA,GAAO,IAAA;AACb,EAAA,MAAM,GAAA,GAAM,KAAK,OAAO,CAAA;AAExB,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3B,IAAA,MAAM,OAAA,GAAU,OAAO,IAAA,CAAK,SAAS,MAAM,QAAA,GAAY,IAAA,CAAK,SAAS,CAAA,GAAe,GAAA;AACpF,IAAA,OAAO,EAAE,IAAA,EAAM,GAAA,EAAK,OAAA,EAAQ;AAAA,EAC9B;AAEA,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,IAAA,EAAM;AAC3C,IAAA,MAAM,MAAA,GAAS,GAAA;AACf,IAAA,MAAM,OACJ,OAAO,MAAA,CAAO,MAAM,CAAA,KAAM,WACrB,MAAA,CAAO,MAAM,CAAA,GACd,OAAO,OAAO,MAAM,CAAA,KAAM,QAAA,GACvB,MAAA,CAAO,MAAM,CAAA,GACd,MAAA;AACR,IAAA,MAAM,OAAA,GACJ,OAAO,MAAA,CAAO,SAAS,MAAM,QAAA,GAAY,MAAA,CAAO,SAAS,CAAA,GAAe,MAAA;AAC1E,IAAA,OAAO,EAAE,MAAM,OAAA,EAAQ;AAAA,EACzB;AAEA,EAAA,MAAM,UAAA,GAAa,OAAO,IAAA,CAAK,SAAS,MAAM,QAAA,GAAY,IAAA,CAAK,SAAS,CAAA,GAAe,MAAA;AACvF,EAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAW,OAAA,EAAS,UAAA,EAAW;AAChD;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AA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,QAAQ,OAAA,EAAyB;AACvC,IAAA,MAAM,IAAA,GAAO,GAAA;AACb,IAAA,MAAM,GAAA,GAAM,GAAA;AACZ,IAAA,MAAM,cAAc,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,IAAA,GAAO,KAAK,OAAO,CAAA;AACrD,IAAA,OAAO,IAAA,CAAK,QAAO,GAAI,WAAA;AAAA,EACzB;AACF;;;ACzjBA,IAAO,aAAA,GAAQ","file":"index.cjs","sourcesContent":["/**\n * The typed error hierarchy thrown by the Skailar SDK.\n *\n * Every failure surfaces as a subclass of {@link SkailarError}, so a single\n * `catch (err) { if (err instanceof SkailarError) ... }` covers the whole SDK.\n * Transport/network failures become {@link SkailarConnectionError}; any non-2xx\n * HTTP response becomes the most specific {@link SkailarAPIError} subclass for\n * its status code.\n *\n * @packageDocumentation\n */\n\n/**\n * Normalized shape extracted from a Skailar error response body.\n *\n * The gateway has been observed to return a flat body\n * (`{ \"error\": \"invalid_api_key\", \"message\": \"...\" }`) and, inside streams, a\n * nested body (`{ \"error\": { \"type\": \"...\", \"message\": \"...\" } }`).\n * {@link parseErrorBody} collapses both into this structure.\n */\nexport interface ParsedErrorBody {\n /** Machine-readable error code, e.g. `\"invalid_api_key\"`. */\n code: string | undefined;\n /** Human-readable error message. */\n message: string | undefined;\n}\n\n/**\n * Extract a `{ code, message }` pair from an arbitrary parsed error body.\n *\n * Tolerant of three layouts: flat (`{ error: \"code\", message: \"msg\" }`), nested\n * object (`{ error: { type|code, message } }`), and OpenAI-style\n * (`{ error: { code, message } }`). Unknown shapes yield two `undefined` values\n * rather than throwing.\n *\n * @param body - The already-JSON-parsed response body (or `undefined`).\n * @returns The normalized code and message, each possibly `undefined`.\n */\nexport function parseErrorBody(body: unknown): ParsedErrorBody {\n if (typeof body !== \"object\" || body === null) {\n return { code: undefined, message: undefined };\n }\n const root = body as Record<string, unknown>;\n const err = root[\"error\"];\n\n if (typeof err === \"string\") {\n const message = typeof root[\"message\"] === \"string\" ? (root[\"message\"] as string) : err;\n return { code: err, message };\n }\n\n if (typeof err === \"object\" && err !== null) {\n const nested = err as Record<string, unknown>;\n const code =\n typeof nested[\"type\"] === \"string\"\n ? (nested[\"type\"] as string)\n : typeof nested[\"code\"] === \"string\"\n ? (nested[\"code\"] as string)\n : undefined;\n const message =\n typeof nested[\"message\"] === \"string\" ? (nested[\"message\"] as string) : undefined;\n return { code, message };\n }\n\n const topMessage = typeof root[\"message\"] === \"string\" ? (root[\"message\"] as string) : undefined;\n return { code: undefined, message: topMessage };\n}\n\n/** Fields shared by the constructors of every concrete SDK error. */\ninterface SkailarErrorOptions {\n /** Human-readable message; falls back to a per-class default. */\n message?: string | undefined;\n /** Machine-readable error code from the response body, if any. */\n code?: string | undefined;\n /** Value of the response `x-request-id` header, if present. */\n requestId?: string | undefined;\n /** The raw response body (parsed JSON or raw text) for diagnostics. */\n raw?: unknown;\n /** Underlying cause, e.g. the original network error. */\n cause?: unknown;\n}\n\n/**\n * Abstract base class for all errors thrown by the Skailar SDK.\n *\n * Not thrown directly; serves as the common `instanceof` target. The `abstract`\n * marker forbids `new SkailarError()` while still allowing subclasses to call `super`.\n */\nexport abstract class SkailarError extends Error {\n /** HTTP status code, or `null` for non-HTTP failures (e.g. network). */\n readonly status: number | null;\n /** Machine-readable error code from the body, if any. */\n readonly code: string | undefined;\n /**\n * Correlation id from the `x-request-id` response header, if any, for support.\n *\n * @remarks\n * Populated on error responses. It is **not** currently surfaced for successful\n * streaming or audio responses (which return a stream rather than a wrapper),\n * so capture it from a thrown {@link SkailarError} when filing a ticket.\n */\n readonly requestId: string | undefined;\n /** The raw response body captured for debugging. */\n readonly raw: unknown;\n\n /**\n * @param status - HTTP status, or `null` when not applicable.\n * @param options - Message, code, request id, raw body and cause.\n */\n protected constructor(status: number | null, options: SkailarErrorOptions = {}) {\n super(options.message ?? \"Skailar SDK error\", { cause: options.cause });\n this.name = new.target.name;\n this.status = status;\n this.code = options.code;\n this.requestId = options.requestId;\n this.raw = options.raw;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Raised when the request never produced an HTTP response: DNS failures,\n * connection resets, TLS errors, and client-side timeouts/aborts driven by the\n * configured `timeout`. Its {@link SkailarError.status} is always `null`.\n */\nexport class SkailarConnectionError extends SkailarError {\n /** @param options - Message and originating cause. */\n constructor(options: { message?: string; cause?: unknown } = {}) {\n super(null, {\n message: options.message ?? \"Failed to connect to the Skailar API\",\n cause: options.cause,\n });\n }\n}\n\n/**\n * Base class for any non-2xx HTTP response from the gateway.\n * {@link SkailarAPIError.from} is the factory that inspects the status code and\n * returns the most specific subclass.\n */\nexport class SkailarAPIError extends SkailarError {\n /**\n * @param status - The HTTP status code of the response.\n * @param options - Message, code, request id and raw body.\n */\n constructor(status: number, options: SkailarErrorOptions = {}) {\n super(status, options);\n }\n\n /**\n * Build the most specific {@link SkailarAPIError} subclass for a status code.\n *\n * @param status - The HTTP status code returned by the gateway.\n * @param parsed - The normalized `{ code, message }` from {@link parseErrorBody}.\n * @param requestId - The `x-request-id` header value, if present.\n * @param raw - The raw response body for diagnostics.\n * @param retryAfter - Seconds from a `Retry-After` header, for 429 responses.\n * @returns A {@link SkailarAuthError}, {@link SkailarBadRequestError},\n * {@link SkailarNotFoundError}, {@link SkailarRateLimitError},\n * {@link SkailarUpstreamError}, or a plain {@link SkailarAPIError}.\n */\n static from(\n status: number,\n parsed: ParsedErrorBody,\n requestId: string | undefined,\n raw: unknown,\n retryAfter?: number | undefined,\n ): SkailarAPIError {\n const options: SkailarErrorOptions = {\n message: parsed.message,\n code: parsed.code,\n requestId,\n raw,\n };\n switch (status) {\n case 401:\n return new SkailarAuthError(options);\n case 400:\n return new SkailarBadRequestError(options);\n case 404:\n return new SkailarNotFoundError(options);\n case 429:\n return new SkailarRateLimitError({ ...options, retryAfter });\n default:\n if (status >= 500) return new SkailarUpstreamError(status, options);\n return new SkailarAPIError(status, options);\n }\n }\n}\n\n/** HTTP 401 — the API key is missing, malformed, or revoked. */\nexport class SkailarAuthError extends SkailarAPIError {\n /** @param options - Error details. */\n constructor(options: SkailarErrorOptions = {}) {\n super(401, { message: \"Invalid or missing API key\", ...options });\n }\n}\n\n/** HTTP 400 — the request was malformed or failed validation. */\nexport class SkailarBadRequestError extends SkailarAPIError {\n /** @param options - Error details. */\n constructor(options: SkailarErrorOptions = {}) {\n super(400, { message: \"Bad request\", ...options });\n }\n}\n\n/** HTTP 404 — the requested resource (e.g. a model id) does not exist. */\nexport class SkailarNotFoundError extends SkailarAPIError {\n /** @param options - Error details. */\n constructor(options: SkailarErrorOptions = {}) {\n super(404, { message: \"Resource not found\", ...options });\n }\n}\n\n/**\n * HTTP 429 — the account exceeded its rate limit.\n *\n * When the gateway provides a `Retry-After` header, its value (in seconds) is\n * exposed as {@link SkailarRateLimitError.retryAfter} and honored by the\n * client's automatic retry logic.\n */\nexport class SkailarRateLimitError extends SkailarAPIError {\n /** Seconds to wait before retrying, parsed from `Retry-After`; `undefined` if absent/unparseable. */\n readonly retryAfter: number | undefined;\n\n /** @param options - Error details plus the optional `retryAfter` seconds. */\n constructor(options: SkailarErrorOptions & { retryAfter?: number | undefined } = {}) {\n super(429, { message: \"Rate limit exceeded\", ...options });\n this.retryAfter = options.retryAfter;\n }\n}\n\n/**\n * HTTP 5xx — the upstream model provider failed or timed out. The gateway\n * propagates provider 5xx failures (502/503/504) with a structured body. These\n * are transient and are retried automatically.\n */\nexport class SkailarUpstreamError extends SkailarAPIError {\n /**\n * @param status - The specific 5xx status code.\n * @param options - Error details.\n */\n constructor(status: number, options: SkailarErrorOptions = {}) {\n super(status, { message: \"Upstream provider error\", ...options });\n }\n}\n","/**\n * A dependency-free Server-Sent Events parser and the {@link ChatCompletionStream}\n * wrapper that exposes a chat completion SSE response as an abortable async iterable.\n *\n * @packageDocumentation\n */\n\nimport { SkailarAPIError, SkailarConnectionError, parseErrorBody } from \"./errors\";\nimport type { ChatCompletionChunk } from \"./types/chat\";\n\n/**\n * Incrementally decode a byte stream into SSE `data:` payload strings, in\n * arrival order, excluding the terminal `[DONE]` sentinel.\n *\n * Implements just the slice of the SSE grammar the gateway emits: UTF-8 `data:`\n * lines terminated by any of `\\n`, `\\r\\n` or `\\r` (per the SSE spec), events\n * delimited by blank lines, terminated by a literal `data: [DONE]`. A partial\n * line left in the buffer across reads is preserved and completed by the next\n * chunk. Comment lines (`:` prefix) and non-`data:` fields are ignored. Yielding\n * stops at `[DONE]`; reaching end-of-stream without `[DONE]` simply ends the generator.\n *\n * On any exit — normal completion, `[DONE]`, an error, or the consumer\n * abandoning the `for await` early — the reader is cancelled before its lock is\n * released, so the underlying fetch connection is torn down instead of leaving\n * bytes streaming from the network.\n *\n * @param stream - The response body as a stream of UTF-8 encoded bytes.\n * @param signal - Optional abort signal; aborting rejects the iteration.\n * @returns An async generator yielding the raw string after each `data:` field.\n * @throws {@link SkailarConnectionError} If the underlying read is aborted or fails.\n */\nexport async function* parseSSE(\n stream: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncGenerator<string, void, unknown> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n /**\n * Extract the next complete line from `buffer`, consuming its terminator.\n * Recognizes `\\n`, `\\r\\n` and a lone `\\r` (the three SSE line terminators).\n * Returns `null` when no terminated line is buffered yet — including the case\n * of a trailing lone `\\r` that might still be the start of a `\\r\\n` split\n * across reads, which is left buffered until the next chunk resolves it.\n *\n * @returns The line without its terminator, or `null` if none is complete.\n */\n function nextLine(): string | null {\n let i = -1;\n for (let j = 0; j < buffer.length; j++) {\n const c = buffer[j];\n if (c === \"\\n\" || c === \"\\r\") {\n i = j;\n break;\n }\n }\n if (i === -1) return null;\n const line = buffer.slice(0, i);\n if (buffer[i] === \"\\r\") {\n if (i === buffer.length - 1) return null; // maybe `\\r\\n` split across reads\n buffer = buffer.slice(i + (buffer[i + 1] === \"\\n\" ? 2 : 1));\n } else {\n buffer = buffer.slice(i + 1);\n }\n return line;\n }\n\n try {\n while (true) {\n if (signal?.aborted) {\n throw new SkailarConnectionError({ message: \"Stream aborted\", cause: signal.reason });\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n let line: string | null;\n while ((line = nextLine()) !== null) {\n if (line === \"\" || line.startsWith(\":\")) continue;\n if (!line.startsWith(\"data:\")) continue;\n\n const data = line.slice(5).trimStart();\n if (data === \"[DONE]\") return;\n yield data;\n }\n }\n\n const tail = buffer.replace(/[\\r\\n]+$/, \"\");\n if (tail.startsWith(\"data:\")) {\n const data = tail.slice(5).trimStart();\n if (data !== \"[DONE]\" && data !== \"\") yield data;\n }\n } catch (err) {\n if (err instanceof SkailarConnectionError) throw err;\n throw new SkailarConnectionError({ message: \"Stream read failed\", cause: err });\n } finally {\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n\n/**\n * An abortable async iterable of {@link ChatCompletionChunk} values, returned by\n * `chat.completions.create({ stream: true })`.\n *\n * Iterate it with `for await`; each iteration yields one decoded chunk. Mirrors\n * the ergonomics of `openai-node`'s stream, including the {@link ChatCompletionStream.controller}\n * for cancellation.\n *\n * @example\n * ```ts\n * const stream = await client.chat.completions.create({\n * model: \"gemini-2.5-flash-lite\",\n * messages: [{ role: \"user\", content: \"hi\" }],\n * stream: true,\n * });\n * for await (const chunk of stream) {\n * process.stdout.write(chunk.choices[0]?.delta?.content ?? \"\");\n * }\n * ```\n */\nexport class ChatCompletionStream implements AsyncIterable<ChatCompletionChunk> {\n /**\n * The {@link AbortController} governing the underlying HTTP request. Call\n * `stream.controller.abort()` to cancel an in-flight stream; the active\n * `for await` loop then terminates promptly.\n */\n readonly controller: AbortController;\n\n /** The raw SSE byte stream backing this iterator. */\n private readonly body: ReadableStream<Uint8Array>;\n\n /**\n * @param body - The response body stream of SSE bytes.\n * @param controller - The abort controller tied to the originating request.\n */\n constructor(body: ReadableStream<Uint8Array>, controller: AbortController) {\n this.body = body;\n this.controller = controller;\n }\n\n /**\n * Decode the SSE byte stream into typed chunks.\n *\n * Each `data:` payload is `JSON.parse`d. If a payload carries an `error` field\n * (the gateway's in-band failure signal), iteration throws the corresponding\n * {@link SkailarAPIError} instead of yielding. A payload that is not valid JSON\n * (e.g. a plain-text error injected by an intermediary) throws a\n * {@link SkailarConnectionError} rather than being dropped, so a malformed\n * stream cannot truncate the response silently.\n *\n * @returns An async generator over {@link ChatCompletionChunk} values.\n * @throws {@link SkailarAPIError} When the stream delivers an in-band error event.\n * @throws {@link SkailarConnectionError} When a payload is malformed, or the\n * stream is aborted or fails to read.\n */\n private async *decode(): AsyncGenerator<ChatCompletionChunk, void, unknown> {\n for await (const data of parseSSE(this.body, this.controller.signal)) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n // A non-JSON data payload (e.g. plain-text error from an intermediary) is\n // surfaced, not dropped, so a malformed stream cannot truncate silently.\n throw new SkailarConnectionError({\n message: `Malformed streaming event (not JSON): ${data.slice(0, 200)}`,\n });\n }\n\n if (parsed !== null && typeof parsed === \"object\" && \"error\" in parsed) {\n const { code, message } = parseErrorBody(parsed);\n throw SkailarAPIError.from(\n 500,\n { code, message: message ?? \"Streaming error\" },\n undefined,\n parsed,\n );\n }\n\n yield parsed as ChatCompletionChunk;\n }\n }\n\n /**\n * Iterate the decoded chunks. Abandoning the iteration early (a `break` or\n * `return` inside a `for await`) invokes the returned iterator's `return()`,\n * which aborts {@link ChatCompletionStream.controller} so the underlying fetch\n * request is cancelled — not merely the body reader — and then runs the\n * generator's own cleanup ({@link parseSSE}'s `finally`: reader cancel +\n * lock release). Normal completion and thrown errors are unaffected.\n *\n * @returns An async iterator over {@link ChatCompletionChunk} values.\n */\n [Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n const inner = this.decode();\n const controller = this.controller;\n return {\n next: () => inner.next(),\n async return(value?: unknown): Promise<IteratorResult<ChatCompletionChunk>> {\n controller.abort();\n if (inner.return) await inner.return(value as undefined);\n return { done: true, value: undefined };\n },\n throw: (err) => (inner.throw ? inner.throw(err) : Promise.reject(err)),\n };\n }\n}\n","/**\n * The chat resource, exposing `client.chat.completions.create(...)` with the\n * same call shape as `openai`'s chat completions.\n *\n * @packageDocumentation\n */\n\nimport type { RequestOptions, Skailar } from \"../client\";\nimport type { ChatCompletionStream } from \"../streaming\";\nimport type {\n ChatCompletion,\n ChatCompletionRequest,\n} from \"../types/chat\";\n\n/** A chat completion request that explicitly opts into streaming. */\ninterface StreamingRequest extends ChatCompletionRequest {\n stream: true;\n}\n\n/** A chat completion request that does not stream. */\ninterface NonStreamingRequest extends ChatCompletionRequest {\n stream?: false;\n}\n\n/**\n * The `completions` sub-namespace of the chat resource. Holds\n * {@link ChatCompletions.create}, whose return type is narrowed by the `stream`\n * field of the request via overloads.\n */\nexport class ChatCompletions {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Create a buffered (non-streamed) chat completion.\n *\n * @param body - The request with `stream` omitted or `false`.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns The fully-formed {@link ChatCompletion}.\n */\n create(body: NonStreamingRequest, options?: RequestOptions): Promise<ChatCompletion>;\n /**\n * Create a streamed chat completion.\n *\n * @param body - The request with `stream: true`.\n * @param options - Optional per-call signal, timeout and headers. The stream\n * is also cancellable via its `.controller`.\n * @returns A {@link ChatCompletionStream} async-iterable of chunks, exposing\n * `.controller` for cancellation.\n */\n create(body: StreamingRequest, options?: RequestOptions): Promise<ChatCompletionStream>;\n /**\n * Create a chat completion whose mode is chosen at runtime. Use this form when\n * `stream` is a non-literal `boolean` (e.g. `stream: shouldStream`), where the\n * concrete return type cannot be known at compile time; narrow the result with\n * `instanceof ChatCompletionStream` or by checking the `stream` flag yourself.\n *\n * @param body - The request with a dynamic `stream` boolean.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns Either a {@link ChatCompletion} or a {@link ChatCompletionStream}.\n */\n create(\n body: ChatCompletionRequest & { stream?: boolean },\n options?: RequestOptions,\n ): Promise<ChatCompletion | ChatCompletionStream>;\n /**\n * Implementation backing the public overloads.\n *\n * @param body - The chat completion request.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns Either a {@link ChatCompletion} or a {@link ChatCompletionStream}\n * depending on `body.stream`.\n * @throws {@link SkailarBadRequestError} On HTTP 400 (malformed request).\n * @throws {@link SkailarAuthError} On HTTP 401 (bad key).\n * @throws {@link SkailarRateLimitError} On HTTP 429 (after exhausting retries).\n * @throws {@link SkailarUpstreamError} On HTTP 5xx (after exhausting retries).\n * @throws {@link SkailarConnectionError} On network failure, timeout or abort.\n */\n create(\n body: ChatCompletionRequest,\n options?: RequestOptions,\n ): Promise<ChatCompletion> | Promise<ChatCompletionStream> {\n if (body.stream === true) {\n return this.client.request({\n method: \"POST\",\n path: \"/v1/chat/completions\",\n body,\n expect: \"stream\",\n // Text generation is safe to replay before the stream starts.\n idempotent: true,\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n return this.client.request<ChatCompletion>({\n method: \"POST\",\n path: \"/v1/chat/completions\",\n body,\n expect: \"json\",\n // Text generation is safe to replay.\n idempotent: true,\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n}\n\n/** The chat resource root, mirroring `openai`'s `client.chat`. */\nexport class ChatResource {\n /** The chat completions namespace. */\n readonly completions: ChatCompletions;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.completions = new ChatCompletions(client);\n }\n}\n","/**\n * The models resource, exposing `client.models.list()` and\n * `client.models.retrieve(id)`.\n *\n * @packageDocumentation\n */\n\nimport type { RequestOptions, Skailar } from \"../client\";\nimport type { Model, ModelList, ModelSummary } from \"../types/models\";\n\n/** Model discovery operations. */\nexport class ModelsResource {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * List every model the gateway can route to. Unwraps the\n * `{ object: \"list\", data }` envelope and returns just `data` as a plain array.\n *\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to the array of {@link ModelSummary} cards.\n */\n async list(options?: RequestOptions): Promise<ModelSummary[]> {\n const res = await this.client.request<ModelList>({\n method: \"GET\",\n path: \"/v1/models\",\n expect: \"json\",\n idempotent: true,\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n return res.data;\n }\n\n /**\n * Retrieve the full detail card for a single model.\n *\n * @param id - The model identifier; may contain slashes (e.g.\n * `\"google/gemini-2.5-pro\"`), which are preserved in the path.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to the {@link Model} detail.\n * @throws {@link SkailarNotFoundError} If no model matches the id.\n */\n retrieve(id: string, options?: RequestOptions): Promise<Model> {\n const encoded = id.split(\"/\").map(encodeURIComponent).join(\"/\");\n return this.client.request<Model>({\n method: \"GET\",\n path: `/v1/models/${encoded}`,\n expect: \"json\",\n idempotent: true,\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n}\n","/**\n * The images resource, exposing `client.images.generate(...)`.\n *\n * @packageDocumentation\n */\n\nimport type { RequestOptions, Skailar } from \"../client\";\nimport type {\n ImageGenerationRequest,\n ImageGenerationResponse,\n} from \"../types/images\";\n\n/** Image generation operations. */\nexport class ImagesResource {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Generate one or more images from a text prompt. Named `generate` to match\n * `openai`'s `images.generate(...)`.\n *\n * @param body - The generation request; see {@link ImageGenerationRequest}.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to the {@link ImageGenerationResponse}, whose\n * `data` entries carry either a `url` or inline `b64_json`.\n * @throws {@link SkailarBadRequestError} On HTTP 400.\n * @throws {@link SkailarRateLimitError} On HTTP 429 (after exhausting retries).\n */\n generate(\n body: ImageGenerationRequest,\n options?: RequestOptions,\n ): Promise<ImageGenerationResponse> {\n return this.client.request<ImageGenerationResponse>({\n method: \"POST\",\n path: \"/v1/images/generations\",\n body,\n expect: \"json\",\n // Billed image generation: never replay on 5xx/timeout to avoid double charges.\n idempotent: false,\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n}\n","/**\n * Internal helpers for normalizing caller-supplied binary payloads into the\n * base64 strings the Skailar gateway expects. Runtime-agnostic across Node 18+,\n * Bun, Deno and browsers.\n *\n * @packageDocumentation\n */\n\nimport type { BinaryInput } from \"../types/audio\";\n\n/**\n * Encode a byte array as a standard (non-URL-safe) base64 string, without any\n * `data:` prefix.\n *\n * Prefers Node's `Buffer` when present (fast path on Node/Bun) and otherwise\n * falls back to `btoa` over a binary string, chunked to avoid call-stack limits\n * on large inputs in browser/Deno environments.\n *\n * @remarks\n * The fast path reads `globalThis.Buffer`, a mutable global. This is a trust\n * boundary only in theory: code that can replace `globalThis.Buffer` already\n * controls the runtime, so no in-SDK validation would meaningfully help. The\n * `btoa` fallback is used in environments without `Buffer` (browsers).\n *\n * @param bytes - The raw bytes to encode.\n * @returns The base64 representation.\n */\nfunction bytesToBase64(bytes: Uint8Array): string {\n const maybeBuffer = (globalThis as { Buffer?: typeof import(\"node:buffer\").Buffer }).Buffer;\n if (maybeBuffer) {\n return maybeBuffer.from(bytes).toString(\"base64\");\n }\n\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n const chunk = bytes.subarray(i, i + chunkSize);\n binary += String.fromCharCode(...chunk);\n }\n return btoa(binary);\n}\n\n/**\n * Normalize any {@link BinaryInput} into a base64 string (no `data:` prefix).\n *\n * A `string` input is assumed to be pre-encoded base64 and returned unchanged. A\n * {@link Blob} is read via its async `arrayBuffer()`; `ArrayBuffer` and\n * `Uint8Array` are encoded directly. This lets the public API accept whichever\n * representation the caller already holds.\n *\n * @remarks\n * A `string` is taken literally as already-encoded base64 and is **not**\n * validated. Passing raw text (e.g. `\"hello world\"`) is silently forwarded to\n * the gateway, which will decode it as base64 and produce corrupt bytes or a\n * `400`. Pass a {@link Uint8Array} / {@link ArrayBuffer} / {@link Blob} when you\n * hold raw bytes; reserve the `string` form for values you have already encoded.\n *\n * @param input - The payload as bytes, a buffer, a {@link Blob}, or a base64 string.\n * @returns A promise resolving to the base64 string.\n */\nexport async function toBase64(input: BinaryInput): Promise<string> {\n if (typeof input === \"string\") return input;\n if (input instanceof Uint8Array) return bytesToBase64(input);\n if (input instanceof ArrayBuffer) return bytesToBase64(new Uint8Array(input));\n if (typeof Blob !== \"undefined\" && input instanceof Blob) {\n const buffer = await input.arrayBuffer();\n return bytesToBase64(new Uint8Array(buffer));\n }\n throw new TypeError(\"Unsupported binary input; expected Uint8Array, ArrayBuffer, Blob or base64 string\");\n}\n","/**\n * The audio resource, exposing `client.audio.transcriptions.create(...)` and\n * `client.audio.speech.create(...)`.\n *\n * @packageDocumentation\n */\n\nimport type { RequestOptions, Skailar } from \"../client\";\nimport { SkailarConnectionError } from \"../errors\";\nimport { toBase64 } from \"../internal/binary\";\nimport type {\n SpeechCreateParams,\n TranscriptionCreateParams,\n TranscriptionResponse,\n} from \"../types/audio\";\n\n/** Audio transcription operations (speech-to-text, Whisper-backed). */\nexport class AudioTranscriptions {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Transcribe an audio clip to text. The supplied bytes are base64-encoded\n * client-side into the gateway's `base64` field. When `mime` is omitted and\n * `file` is a {@link Blob} carrying a `type`, that type is used; otherwise the\n * gateway default (`audio/wav`) applies.\n *\n * @param params - The audio and its MIME type; see {@link TranscriptionCreateParams}.\n * `file` may be a {@link Uint8Array}, {@link ArrayBuffer}, {@link Blob} or a\n * pre-encoded base64 string.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to the {@link TranscriptionResponse}.\n */\n async create(\n params: TranscriptionCreateParams,\n options?: RequestOptions,\n ): Promise<TranscriptionResponse> {\n const base64 = await toBase64(params.file);\n const mime =\n params.mime ??\n (typeof Blob !== \"undefined\" && params.file instanceof Blob && params.file.type\n ? (params.file.type as TranscriptionCreateParams[\"mime\"])\n : undefined);\n return this.client.request<TranscriptionResponse>({\n method: \"POST\",\n path: \"/v1/audio/transcriptions\",\n body: { base64, mime },\n expect: \"json\",\n // Billed transcription: never replay on 5xx/timeout to avoid double charges.\n idempotent: false,\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n}\n\n/** Speech synthesis operations (text-to-speech). */\nexport class AudioSpeech {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Synthesize speech and return the raw MP3 audio stream. Unlike the JSON\n * endpoints, this returns the response body stream directly so large audio\n * payloads need not be buffered in memory.\n *\n * Pass `options.signal` to cancel the request: aborting it before the response\n * arrives rejects this call, and aborting it while the MP3 is still downloading\n * tears down the underlying connection so the body stops mid-stream.\n *\n * @param params - The text and voice; see {@link SpeechCreateParams}.\n * @param options - Optional per-call signal, timeout and headers.\n * @returns A promise resolving to a `ReadableStream<Uint8Array>` of\n * `audio/mpeg` bytes, suitable for piping to a file, an HTTP response, or an\n * audio element.\n * @throws {@link SkailarConnectionError} If the response unexpectedly lacks a body.\n * @throws {@link SkailarBadRequestError} On HTTP 400 (e.g. text exceeding 4000 chars).\n */\n async create(\n params: SpeechCreateParams,\n options?: RequestOptions,\n ): Promise<ReadableStream<Uint8Array>> {\n const response = await this.client.request({\n method: \"POST\",\n path: \"/v1/audio/speech\",\n body: { input: params.input, voice: params.voice },\n headers: { Accept: \"audio/mpeg\", ...options?.headers },\n expect: \"response\",\n // Billed speech synthesis: never replay on 5xx/timeout to avoid double charges.\n idempotent: false,\n signal: options?.signal,\n timeout: options?.timeout,\n });\n if (!response.body) {\n throw new SkailarConnectionError({ message: \"Speech response had no audio body\" });\n }\n return response.body;\n }\n}\n\n/** The audio resource root, grouping transcription and speech. */\nexport class AudioResource {\n /** Speech-to-text operations. */\n readonly transcriptions: AudioTranscriptions;\n /** Text-to-speech operations. */\n readonly speech: AudioSpeech;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.transcriptions = new AudioTranscriptions(client);\n this.speech = new AudioSpeech(client);\n }\n}\n","/**\n * The uploads resource, exposing `client.uploads.images.create(...)` and\n * `client.uploads.files.create(...)` for storing assets in Skailar storage and\n * receiving an embeddable URL.\n *\n * @packageDocumentation\n */\n\nimport type { Skailar } from \"../client\";\nimport { toBase64 } from \"../internal/binary\";\nimport type {\n FileUploadCreateParams,\n ImageUploadCreateParams,\n UploadResponse,\n} from \"../types/uploads\";\n\n/** Image upload operations (`POST /v1/uploads/images`). */\nexport class ImageUploads {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Upload an image and obtain a URL usable as vision input. `data` may be a\n * {@link Uint8Array}, {@link ArrayBuffer}, {@link Blob} or a pre-encoded base64\n * string; it is base64-encoded client-side into the gateway's `base64` field.\n *\n * @param params - The image bytes and content type; see {@link ImageUploadCreateParams}.\n * @returns A promise resolving to the {@link UploadResponse} whose `url` can be\n * embedded in a chat completion as an `image_url` content part.\n */\n async create(params: ImageUploadCreateParams): Promise<UploadResponse> {\n const base64 = await toBase64(params.data);\n return this.client.request<UploadResponse>({\n method: \"POST\",\n path: \"/v1/uploads/images\",\n body: { base64, content_type: params.contentType },\n expect: \"json\",\n // Upload creates a stored asset: never replay to avoid duplicate uploads.\n idempotent: false,\n });\n }\n}\n\n/** File upload operations (`POST /v1/uploads/files`). */\nexport class FileUploads {\n /** The owning client used to dispatch requests. */\n private readonly client: Skailar;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.client = client;\n }\n\n /**\n * Upload a document (`application/pdf` or `text/plain`). `data` accepts the\n * same forms as image upload and is base64-encoded client-side.\n *\n * @param params - The document bytes and content type; see {@link FileUploadCreateParams}.\n * @returns A promise resolving to the {@link UploadResponse} with the stored asset URL.\n */\n async create(params: FileUploadCreateParams): Promise<UploadResponse> {\n const base64 = await toBase64(params.data);\n return this.client.request<UploadResponse>({\n method: \"POST\",\n path: \"/v1/uploads/files\",\n body: { base64, content_type: params.contentType },\n expect: \"json\",\n // Upload creates a stored asset: never replay to avoid duplicate uploads.\n idempotent: false,\n });\n }\n}\n\n/** The uploads resource root, grouping image and file uploads. */\nexport class UploadsResource {\n /** Image upload operations. */\n readonly images: ImageUploads;\n /** File/document upload operations. */\n readonly files: FileUploads;\n\n /** @param client - The owning {@link Skailar} client. */\n constructor(client: Skailar) {\n this.images = new ImageUploads(client);\n this.files = new FileUploads(client);\n }\n}\n","/**\n * The {@link Skailar} client: configuration, the shared fetch dispatch pipeline\n * (timeout, retry with backoff, error mapping) and the resource namespaces hung\n * off it.\n *\n * @packageDocumentation\n */\n\nimport {\n SkailarConnectionError,\n SkailarAPIError,\n SkailarRateLimitError,\n parseErrorBody,\n} from \"./errors\";\nimport { ChatCompletionStream } from \"./streaming\";\nimport { ChatResource } from \"./resources/chat\";\nimport { ModelsResource } from \"./resources/models\";\nimport { ImagesResource } from \"./resources/images\";\nimport { AudioResource } from \"./resources/audio\";\nimport { UploadsResource } from \"./resources/uploads\";\nimport type { PingKeyResponse } from \"./types/index\";\n\n/**\n * Configuration accepted by the {@link Skailar} constructor. Every field is\n * optional; omitted fields fall back to environment variables or library\n * defaults as documented per property.\n */\nexport interface SkailarOptions {\n /**\n * Skailar API key of the form `skl_live_<43 url-safe base64 chars>`. Defaults\n * to `process.env.SKAILAR_API_KEY`; if neither is provided the constructor throws.\n *\n * @remarks\n * The format is **not** validated locally — only emptiness is checked. A\n * malformed or wrong-provider key (e.g. an OpenAI `sk-...` key passed by\n * mistake) is accepted here and rejected at the first request with a\n * {@link SkailarAuthError} (HTTP 401). Note this means such a key is **sent to\n * {@link SkailarOptions.baseURL}** before it is rejected; if you point\n * `baseURL` at a third-party host, take care not to forward a credential meant\n * for a different provider. Keep the default `baseURL` unless you control the\n * endpoint.\n */\n apiKey?: string;\n /**\n * Base URL of the gateway, without a trailing `/v1` (default\n * `\"https://api.skailar.com\"`). The `/v1/...` path is appended by the SDK.\n * Point this at `http://localhost:8080` for a local gateway.\n */\n baseURL?: string;\n /**\n * Timeout in milliseconds applied to **each attempt** (default `60000`). A\n * timed-out attempt becomes a {@link SkailarConnectionError} and, for\n * idempotent requests, is eligible for retry.\n *\n * @remarks\n * This is **per attempt, not a total deadline**. With retries enabled the\n * worst-case wall-clock for one call is roughly\n * `(maxRetries + 1) × timeout + backoff` — e.g. the defaults (60s, 2 retries)\n * can keep a call pending for ~3 minutes on a persistently slow endpoint. In\n * environments with their own hard limits (serverless/Lambda, HTTP handlers),\n * enforce an end-to-end bound by passing an `AbortSignal` (and/or a smaller\n * per-call `timeout`) in the request options, or set `maxRetries: 0`.\n */\n timeout?: number;\n /**\n * Maximum automatic retries for transient failures (default `2`). Retries\n * apply only to HTTP 429, HTTP 5xx, and connection errors; non-429 4xx\n * responses are never retried.\n */\n maxRetries?: number;\n /**\n * Custom `fetch` implementation, primarily for testing (default global\n * `fetch`). No binding is applied; pass an already-bound function if your\n * implementation requires a specific receiver.\n */\n fetch?: typeof fetch;\n /**\n * Headers merged into every request. Per-call `options.headers` override these.\n * The SDK's `Authorization` always wins and cannot be overridden; `Accept` and\n * `Content-Type` default to SDK values but may be overridden here or per call.\n */\n defaultHeaders?: Record<string, string>;\n}\n\n/**\n * Per-call request options accepted as the trailing argument of every resource\n * method (e.g. `chat.completions.create(body, options)`). Mirrors the\n * `openai-node` convention so the wire body stays separate from transport\n * concerns. Every field is optional and overrides the client-level default for\n * this one call.\n */\nexport interface RequestOptions {\n /**\n * Signal to cancel this call. Aborting before the response arrives rejects the\n * call with a {@link SkailarConnectionError}; for streaming/audio bodies,\n * aborting mid-transfer tears down the connection.\n */\n signal?: AbortSignal;\n /**\n * Per-call timeout in milliseconds, overriding {@link SkailarOptions.timeout}\n * for this request only.\n */\n timeout?: number;\n /**\n * Extra headers merged into this request, overriding client `defaultHeaders`.\n * Cannot override `Authorization` (always set by the SDK); may override `Accept`\n * and `Content-Type`.\n */\n headers?: Record<string, string>;\n}\n\n/** Internal description of a single HTTP request to dispatch. */\ninterface InternalRequest {\n method: \"GET\" | \"POST\";\n /** Path beginning with `/v1/...`, relative to {@link SkailarOptions.baseURL}. */\n path: string;\n /** Optional JSON body; serialized with `JSON.stringify`. */\n body?: unknown;\n /** Extra headers for this request only. */\n headers?: Record<string, string>;\n /** Expected response handling: parsed JSON, raw `Response`, or SSE stream. */\n expect: \"json\" | \"response\" | \"stream\";\n /**\n * External abort signal composed with the timeout. Used for streaming, where\n * the caller-visible {@link ChatCompletionStream.controller} drives cancellation.\n */\n signal?: AbortSignal;\n /** Per-call timeout override in ms; falls back to {@link Skailar.timeout}. */\n timeout?: number;\n /**\n * Whether the request is safe to replay after a 5xx, timeout or connection\n * failure — i.e. the server either did not execute it or executing it twice is\n * harmless. `GET`s and text completions are idempotent; operations with billed\n * side effects (image generation, speech, transcription, uploads) are not, and\n * must not be retried once the request may have reached the server. A `429` is\n * always retryable regardless, since it is rejected before execution.\n */\n idempotent?: boolean;\n}\n\n/**\n * Upper bound on how long a single automatic retry will wait, in milliseconds.\n * Caps a server `Retry-After`: even if the gateway (or a misbehaving proxy) asks\n * for a much longer delay, the SDK waits at most this long before retrying, so a\n * call cannot be parked for minutes or hours. The true server-requested value is\n * still exposed on {@link SkailarRateLimitError.retryAfter}.\n */\nexport const MAX_RETRY_DELAY_MS = 60_000;\n\n/**\n * Convert a server `Retry-After` value (in seconds) into a bounded retry delay in\n * milliseconds, capped at {@link MAX_RETRY_DELAY_MS}.\n *\n * @param retryAfterSeconds - The seconds requested by the server, or `undefined`.\n * @returns The capped delay in ms, or `undefined` when no value was given.\n */\nexport function capRetryDelay(retryAfterSeconds: number | undefined): number | undefined {\n if (retryAfterSeconds === undefined) return undefined;\n return Math.min(Math.max(0, retryAfterSeconds) * 1000, MAX_RETRY_DELAY_MS);\n}\n\n/**\n * Sleep for the given duration, rejecting early if the signal aborts.\n *\n * @param ms - Milliseconds to wait.\n * @param signal - Optional signal that, when aborted, rejects the sleep.\n * @returns A promise resolving after `ms`, or rejecting on abort.\n */\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new SkailarConnectionError({ message: \"Aborted\", cause: signal.reason }));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(new SkailarConnectionError({ message: \"Aborted\", cause: signal?.reason }));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/**\n * Parse a `Retry-After` header value into seconds — the header's native unit\n * and the unit exposed on {@link SkailarRateLimitError.retryAfter}. Call sites\n * that need a millisecond delay multiply by 1000 themselves.\n *\n * @param header - The raw header value, a number of seconds or an HTTP date.\n * @returns The delay in seconds, or `undefined` if absent/unparseable.\n */\nfunction parseRetryAfter(header: string | null): number | undefined {\n if (!header) return undefined;\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return Math.max(0, seconds);\n const date = Date.parse(header);\n if (Number.isFinite(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Wrap a byte stream so `onDone` runs exactly once when it terminates — whether\n * it closes normally, errors, or is cancelled by the consumer. Used to detach\n * the external-abort listener for `response`/`stream` results whose body outlives\n * the {@link Skailar.request} call, so a long-lived caller `AbortSignal` does not\n * accumulate listeners across requests.\n *\n * @param source - The original response body stream.\n * @param onDone - Idempotent cleanup to run on terminal state.\n * @returns A stream that mirrors `source` and triggers `onDone` when finished.\n */\nfunction withCleanup(\n source: ReadableStream<Uint8Array>,\n onDone: () => void,\n): ReadableStream<Uint8Array> {\n let done = false;\n const finish = () => {\n if (done) return;\n done = true;\n onDone();\n };\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done: streamDone, value } = await reader.read();\n if (streamDone) {\n finish();\n controller.close();\n return;\n }\n controller.enqueue(value);\n } catch (err) {\n finish();\n controller.error(err);\n }\n },\n async cancel(reason) {\n finish();\n await reader.cancel(reason);\n },\n });\n}\n\n/**\n * Read the request-correlation id from a response's headers, checking the common\n * header spellings so the id is captured regardless of casing convention.\n *\n * @param headers - The response headers.\n * @returns The first present correlation id, or `undefined`.\n */\nfunction extractRequestId(headers: Headers): string | undefined {\n return (\n headers.get(\"x-request-id\") ??\n headers.get(\"x-skailar-request-id\") ??\n headers.get(\"request-id\") ??\n undefined\n );\n}\n\n/**\n * The official Skailar API client. Construct once and reuse. Resource namespaces\n * ({@link Skailar.chat}, {@link Skailar.models}, etc.) provide the\n * OpenAI-compatible and Skailar-native operations. All network access flows\n * through {@link Skailar.request}, which centralizes authentication, timeouts,\n * retries and error mapping.\n *\n * @example\n * ```ts\n * import Skailar from \"@skailar-ai/sdk\";\n * const client = new Skailar({ apiKey: \"skl_live_...\" });\n * const res = await client.chat.completions.create({\n * model: \"claude-sonnet-4-6\",\n * messages: [{ role: \"user\", content: \"Hello!\" }],\n * });\n * console.log(res.choices[0]?.message.content);\n * ```\n */\nexport class Skailar {\n /** Resolved API key sent as the bearer token. */\n readonly apiKey: string;\n /** Resolved base URL with any trailing slash removed. */\n readonly baseURL: string;\n /** Resolved per-attempt timeout in milliseconds. */\n readonly timeout: number;\n /** Resolved maximum retry count. */\n readonly maxRetries: number;\n /** Default headers merged into every request. */\n readonly defaultHeaders: Record<string, string>;\n\n /** The `fetch` implementation used for all requests. */\n private readonly fetchImpl: typeof fetch;\n\n /** Chat completions (OpenAI-compatible). */\n readonly chat: ChatResource;\n /** Model discovery. */\n readonly models: ModelsResource;\n /** Image generation. */\n readonly images: ImagesResource;\n /** Speech synthesis and transcription. */\n readonly audio: AudioResource;\n /** Direct uploads to Skailar storage. */\n readonly uploads: UploadsResource;\n\n /**\n * @param options - Client configuration; see {@link SkailarOptions}.\n * @throws If no API key is resolvable (neither `options.apiKey` nor\n * `SKAILAR_API_KEY`). A key that is present but malformed is **not** rejected\n * here; it fails at the first request with a {@link SkailarAuthError}.\n */\n constructor(options: SkailarOptions = {}) {\n const env =\n typeof process !== \"undefined\" && process.env ? process.env[\"SKAILAR_API_KEY\"] : undefined;\n const apiKey = options.apiKey ?? env;\n if (!apiKey) {\n throw new Error(\n \"Missing Skailar API key. Pass { apiKey } or set the SKAILAR_API_KEY environment variable.\",\n );\n }\n\n this.apiKey = apiKey;\n this.baseURL = (options.baseURL ?? \"https://api.skailar.com\").replace(/\\/+$/, \"\");\n this.timeout = options.timeout ?? 60_000;\n this.maxRetries = options.maxRetries ?? 2;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n\n if (typeof this.fetchImpl !== \"function\") {\n throw new Error(\"No fetch implementation available; pass { fetch } explicitly.\");\n }\n\n this.chat = new ChatResource(this);\n this.models = new ModelsResource(this);\n this.images = new ImagesResource(this);\n this.audio = new AudioResource(this);\n this.uploads = new UploadsResource(this);\n }\n\n /**\n * Verify the configured API key against `GET /v1/ping-key`.\n *\n * @param options - Optional per-call signal, timeout and headers.\n * @returns The `{ status, user_id }` payload when the key is valid.\n * @throws {@link SkailarAuthError} If the key is missing, invalid or revoked.\n */\n ping(options?: RequestOptions): Promise<PingKeyResponse> {\n return this.request<PingKeyResponse>({\n method: \"GET\",\n path: \"/v1/ping-key\",\n expect: \"json\",\n idempotent: true,\n signal: options?.signal,\n timeout: options?.timeout,\n headers: options?.headers,\n });\n }\n\n /**\n * Dispatch a request expecting a JSON body, with retries.\n *\n * @typeParam T - The expected shape of the parsed JSON response.\n * @param options - The request description.\n * @returns The parsed JSON response body typed as `T`.\n */\n request<T>(options: InternalRequest & { expect: \"json\" }): Promise<T>;\n /**\n * Dispatch a request expecting the raw {@link Response}, with retries.\n *\n * @param options - The request description.\n * @returns The successful `Response`, body unread (e.g. for audio streams).\n */\n request(options: InternalRequest & { expect: \"response\" }): Promise<Response>;\n /**\n * Dispatch a streaming request, returning a chat completion stream.\n *\n * @param options - The request description with `expect: \"stream\"`.\n * @returns A {@link ChatCompletionStream} over the SSE response.\n */\n request(options: InternalRequest & { expect: \"stream\" }): Promise<ChatCompletionStream>;\n /**\n * Core dispatch implementation shared by all resources.\n *\n * Applies, per attempt: header assembly with bearer auth, a timeout-derived\n * {@link AbortSignal} composed with any caller signal, execution of\n * {@link SkailarOptions.fetch}, and error mapping. Backs off with full-jitter\n * exponential delay, honoring a server `Retry-After` when present (capped at\n * {@link MAX_RETRY_DELAY_MS} so an oversized value cannot stall the call), up\n * to {@link Skailar.maxRetries}. Non-429 4xx responses fail fast.\n *\n * Retries are scoped to avoid duplicating side effects: an HTTP `429` is always\n * retryable (rejected before execution), while a `5xx`, timeout or connection\n * failure is retried **only** when `options.idempotent` is set — because the\n * request may already have executed server-side. Requests with billed side\n * effects (image generation, speech, transcription, uploads) leave it unset and\n * are therefore never replayed once they may have reached the gateway.\n *\n * Transport failures are reported as {@link SkailarConnectionError} with a\n * message distinguishing three causes: an external `signal` abort\n * (non-retryable), an internal timeout once {@link Skailar.timeout} elapses,\n * and a generic network failure.\n *\n * @param options - The request description.\n * @returns The parsed JSON, raw `Response`, or {@link ChatCompletionStream}\n * depending on `options.expect`.\n */\n async request(\n options: InternalRequest,\n ): Promise<unknown> {\n const url = `${this.baseURL}${options.path}`;\n const isStream = options.expect === \"stream\";\n const timeoutMs = options.timeout ?? this.timeout;\n // Default to non-idempotent: never replay a request with possible side\n // effects unless the caller explicitly marked it safe.\n const idempotent = options.idempotent ?? false;\n let attempt = 0;\n\n while (true) {\n const controller = new AbortController();\n const onExternalAbort = () => controller.abort(options.signal?.reason);\n if (options.signal) {\n if (options.signal.aborted) controller.abort(options.signal.reason);\n else options.signal.addEventListener(\"abort\", onExternalAbort);\n }\n const detachExternal = () =>\n options.signal?.removeEventListener(\"abort\", onExternalAbort);\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort(new Error(\"Request timed out\"));\n }, timeoutMs);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method: options.method,\n headers: this.buildHeaders(options),\n body: options.body === undefined ? undefined : JSON.stringify(options.body),\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n detachExternal();\n const externallyAborted = options.signal?.aborted ?? false;\n const connErr = new SkailarConnectionError({\n message: externallyAborted\n ? \"Request aborted\"\n : timedOut\n ? `Request timed out after ${timeoutMs}ms`\n : \"Network request to the Skailar API failed\",\n cause: err,\n });\n // A connection failure/timeout may have reached the server mid-request,\n // so only replay it when the request is idempotent.\n if (externallyAborted || !idempotent || !this.shouldRetry(attempt)) throw connErr;\n attempt += 1;\n await delay(this.backoff(attempt), options.signal);\n continue;\n }\n\n clearTimeout(timer);\n\n if (!response.ok) {\n detachExternal();\n const apiError = await this.toApiError(response);\n const retryAfterMs =\n apiError instanceof SkailarRateLimitError\n ? capRetryDelay(apiError.retryAfter)\n : undefined;\n if (this.isRetryableStatus(response.status, idempotent) && this.shouldRetry(attempt)) {\n attempt += 1;\n await delay(retryAfterMs ?? this.backoff(attempt), options.signal);\n continue;\n }\n throw apiError;\n }\n\n if (isStream || options.expect === \"response\") {\n if (!response.body) {\n detachExternal();\n throw new SkailarConnectionError({\n message: isStream ? \"Streaming response had no body\" : \"Response had no body\",\n });\n }\n const body = withCleanup(response.body, detachExternal);\n if (isStream) return new ChatCompletionStream(body, controller);\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n\n detachExternal();\n return (await response.json()) as unknown;\n }\n }\n\n /**\n * Assemble the outgoing header set for a request.\n *\n * Precedence (later wins): client `defaultHeaders` → the SDK's default `Accept`\n * and `Content-Type` → per-call `options.headers` → `Authorization`.\n * `Authorization` is applied **last** so a caller-supplied header (including a\n * blindly proxied incoming one) can never override or drop the bearer token and\n * leak it elsewhere. `Accept`/`Content-Type` remain overridable on purpose —\n * e.g. audio speech sends `Accept: audio/mpeg`.\n *\n * @param options - The request description.\n * @returns The header record to send.\n */\n private buildHeaders(options: InternalRequest): Record<string, string> {\n const headers: Record<string, string> = {\n ...this.defaultHeaders,\n Accept: options.expect === \"stream\" ? \"text/event-stream\" : \"application/json\",\n };\n if (options.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n if (options.headers) Object.assign(headers, options.headers);\n // Drop any caller-supplied authorization (any casing) so it cannot leak or\n // be sent alongside ours; HTTP header names are case-insensitive but JS\n // object keys are not, so a lowercase key would otherwise survive.\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === \"authorization\") delete headers[key];\n }\n headers[\"Authorization\"] = `Bearer ${this.apiKey}`;\n return headers;\n }\n\n /**\n * Convert a non-2xx {@link Response} into the most specific\n * {@link SkailarAPIError} subclass. Reads the body once, attempting JSON first\n * and falling back to raw text, then defers classification to\n * {@link SkailarAPIError.from}.\n *\n * @param response - The failed HTTP response.\n * @returns The mapped error.\n */\n private async toApiError(response: Response): Promise<SkailarAPIError> {\n const text = await response.text().catch(() => \"\");\n let raw: unknown = text;\n try {\n raw = text ? JSON.parse(text) : undefined;\n } catch {\n raw = text;\n }\n const parsed = parseErrorBody(raw);\n const requestId = extractRequestId(response.headers);\n const retryAfter =\n response.status === 429 ? parseRetryAfter(response.headers.get(\"retry-after\")) : undefined;\n return SkailarAPIError.from(response.status, parsed, requestId, raw, retryAfter);\n }\n\n /**\n * Whether an HTTP error status is eligible for automatic retry.\n *\n * A `429` is always retryable: the gateway rejects it before executing the\n * request, so replaying it cannot duplicate side effects. A `5xx` may mean the\n * request already executed server-side, so it is retried only when the caller\n * marked the request idempotent.\n *\n * @param status - The HTTP status code.\n * @param idempotent - Whether replaying the request is safe.\n * @returns `true` if retryable.\n */\n private isRetryableStatus(status: number, idempotent: boolean): boolean {\n if (status === 429) return true;\n return status >= 500 && idempotent;\n }\n\n /**\n * Whether another attempt remains within the retry budget.\n *\n * @param attempt - The count of attempts already made (before increment).\n * @returns `true` if a retry is permitted.\n */\n private shouldRetry(attempt: number): boolean {\n return attempt < this.maxRetries;\n }\n\n /**\n * Compute a full-jitter exponential backoff delay: a random value in\n * `[0, min(cap, base * 2^attempt))`, capped at 8000ms. Jitter spreads retries\n * from many clients to avoid synchronized thundering-herd load on the gateway.\n *\n * @param attempt - The retry number, starting at 1 for the first retry.\n * @returns A randomized delay in milliseconds.\n */\n private backoff(attempt: number): number {\n const base = 500;\n const cap = 8000;\n const exponential = Math.min(cap, base * 2 ** attempt);\n return Math.random() * exponential;\n }\n}\n","/**\n * Public entry point of the Skailar TypeScript SDK.\n *\n * Exports {@link Skailar} as both the default and a named export, the full typed\n * error hierarchy, the {@link ChatCompletionStream} helper, and every public\n * request/response type.\n *\n * @example Default import\n * ```ts\n * import Skailar from \"@skailar-ai/sdk\";\n * const client = new Skailar({ apiKey: \"skl_live_...\" });\n * ```\n *\n * @example Named imports\n * ```ts\n * import { Skailar, SkailarError, SkailarRateLimitError } from \"@skailar-ai/sdk\";\n * ```\n *\n * @packageDocumentation\n */\n\nimport { Skailar } from \"./client\";\n\nexport { Skailar };\nexport type { SkailarOptions, RequestOptions } from \"./client\";\n\nexport default Skailar;\n\nexport {\n SkailarError,\n SkailarAPIError,\n SkailarAuthError,\n SkailarBadRequestError,\n SkailarNotFoundError,\n SkailarRateLimitError,\n SkailarUpstreamError,\n SkailarConnectionError,\n} from \"./errors\";\nexport type { ParsedErrorBody } from \"./errors\";\n\nexport { ChatCompletionStream, parseSSE } from \"./streaming\";\n\nexport type * from \"./types/index\";\n"]}
package/dist/index.d.cts CHANGED
@@ -309,11 +309,11 @@ interface ChatCompletionChunk {
309
309
  * arrival order, excluding the terminal `[DONE]` sentinel.
310
310
  *
311
311
  * Implements just the slice of the SSE grammar the gateway emits: UTF-8 `data:`
312
- * lines separated by `\n`, events delimited by blank lines, terminated by a
313
- * literal `data: [DONE]`. A partial line left in the buffer across reads is
314
- * preserved and completed by the next chunk. Comment lines (`:` prefix) and
315
- * non-`data:` fields are ignored. Yielding stops at `[DONE]`; reaching
316
- * end-of-stream without `[DONE]` simply ends the generator.
312
+ * lines terminated by any of `\n`, `\r\n` or `\r` (per the SSE spec), events
313
+ * delimited by blank lines, terminated by a literal `data: [DONE]`. A partial
314
+ * line left in the buffer across reads is preserved and completed by the next
315
+ * chunk. Comment lines (`:` prefix) and non-`data:` fields are ignored. Yielding
316
+ * stops at `[DONE]`; reaching end-of-stream without `[DONE]` simply ends the generator.
317
317
  *
318
318
  * On any exit — normal completion, `[DONE]`, an error, or the consumer
319
319
  * abandoning the `for await` early — the reader is cancelled before its lock is
@@ -365,12 +365,15 @@ declare class ChatCompletionStream implements AsyncIterable<ChatCompletionChunk>
365
365
  *
366
366
  * Each `data:` payload is `JSON.parse`d. If a payload carries an `error` field
367
367
  * (the gateway's in-band failure signal), iteration throws the corresponding
368
- * {@link SkailarAPIError} instead of yielding. Malformed JSON payloads are
369
- * skipped defensively.
368
+ * {@link SkailarAPIError} instead of yielding. A payload that is not valid JSON
369
+ * (e.g. a plain-text error injected by an intermediary) throws a
370
+ * {@link SkailarConnectionError} rather than being dropped, so a malformed
371
+ * stream cannot truncate the response silently.
370
372
  *
371
373
  * @returns An async generator over {@link ChatCompletionChunk} values.
372
374
  * @throws {@link SkailarAPIError} When the stream delivers an in-band error event.
373
- * @throws {@link SkailarConnectionError} When the stream is aborted or read fails.
375
+ * @throws {@link SkailarConnectionError} When a payload is malformed, or the
376
+ * stream is aborted or fails to read.
374
377
  */
375
378
  private decode;
376
379
  /**
@@ -890,7 +893,11 @@ interface SkailarOptions {
890
893
  * The format is **not** validated locally — only emptiness is checked. A
891
894
  * malformed or wrong-provider key (e.g. an OpenAI `sk-...` key passed by
892
895
  * mistake) is accepted here and rejected at the first request with a
893
- * {@link SkailarAuthError} (HTTP 401).
896
+ * {@link SkailarAuthError} (HTTP 401). Note this means such a key is **sent to
897
+ * {@link SkailarOptions.baseURL}** before it is rejected; if you point
898
+ * `baseURL` at a third-party host, take care not to forward a credential meant
899
+ * for a different provider. Keep the default `baseURL` unless you control the
900
+ * endpoint.
894
901
  */
895
902
  apiKey?: string;
896
903
  /**
@@ -900,9 +907,18 @@ interface SkailarOptions {
900
907
  */
901
908
  baseURL?: string;
902
909
  /**
903
- * Per-request timeout in milliseconds (default `60000`). Applies to each
904
- * attempt independently; a timed-out attempt becomes a
905
- * {@link SkailarConnectionError} and is eligible for retry.
910
+ * Timeout in milliseconds applied to **each attempt** (default `60000`). A
911
+ * timed-out attempt becomes a {@link SkailarConnectionError} and, for
912
+ * idempotent requests, is eligible for retry.
913
+ *
914
+ * @remarks
915
+ * This is **per attempt, not a total deadline**. With retries enabled the
916
+ * worst-case wall-clock for one call is roughly
917
+ * `(maxRetries + 1) × timeout + backoff` — e.g. the defaults (60s, 2 retries)
918
+ * can keep a call pending for ~3 minutes on a persistently slow endpoint. In
919
+ * environments with their own hard limits (serverless/Lambda, HTTP handlers),
920
+ * enforce an end-to-end bound by passing an `AbortSignal` (and/or a smaller
921
+ * per-call `timeout`) in the request options, or set `maxRetries: 0`.
906
922
  */
907
923
  timeout?: number;
908
924
  /**
@@ -918,8 +934,9 @@ interface SkailarOptions {
918
934
  */
919
935
  fetch?: typeof fetch;
920
936
  /**
921
- * Headers merged into every request. The SDK's own `Authorization`,
922
- * `Content-Type` and `Accept`, plus explicit per-call headers, take precedence.
937
+ * Headers merged into every request. Per-call `options.headers` override these.
938
+ * The SDK's `Authorization` always wins and cannot be overridden; `Accept` and
939
+ * `Content-Type` default to SDK values but may be overridden here or per call.
923
940
  */
924
941
  defaultHeaders?: Record<string, string>;
925
942
  }
@@ -942,7 +959,11 @@ interface RequestOptions {
942
959
  * for this request only.
943
960
  */
944
961
  timeout?: number;
945
- /** Extra headers merged into this request, overriding client defaults. */
962
+ /**
963
+ * Extra headers merged into this request, overriding client `defaultHeaders`.
964
+ * Cannot override `Authorization` (always set by the SDK); may override `Accept`
965
+ * and `Content-Type`.
966
+ */
946
967
  headers?: Record<string, string>;
947
968
  }
948
969
  /** Internal description of a single HTTP request to dispatch. */
@@ -963,6 +984,15 @@ interface InternalRequest {
963
984
  signal?: AbortSignal;
964
985
  /** Per-call timeout override in ms; falls back to {@link Skailar.timeout}. */
965
986
  timeout?: number;
987
+ /**
988
+ * Whether the request is safe to replay after a 5xx, timeout or connection
989
+ * failure — i.e. the server either did not execute it or executing it twice is
990
+ * harmless. `GET`s and text completions are idempotent; operations with billed
991
+ * side effects (image generation, speech, transcription, uploads) are not, and
992
+ * must not be retried once the request may have reached the server. A `429` is
993
+ * always retryable regardless, since it is rejected before execution.
994
+ */
995
+ idempotent?: boolean;
966
996
  }
967
997
  /**
968
998
  * The official Skailar API client. Construct once and reuse. Resource namespaces
@@ -1049,8 +1079,14 @@ declare class Skailar {
1049
1079
  expect: "stream";
1050
1080
  }): Promise<ChatCompletionStream>;
1051
1081
  /**
1052
- * Assemble the outgoing header set for a request, applying defaults, auth,
1053
- * content-type and accept in precedence order.
1082
+ * Assemble the outgoing header set for a request.
1083
+ *
1084
+ * Precedence (later wins): client `defaultHeaders` → the SDK's default `Accept`
1085
+ * and `Content-Type` → per-call `options.headers` → `Authorization`.
1086
+ * `Authorization` is applied **last** so a caller-supplied header (including a
1087
+ * blindly proxied incoming one) can never override or drop the bearer token and
1088
+ * leak it elsewhere. `Accept`/`Content-Type` remain overridable on purpose —
1089
+ * e.g. audio speech sends `Accept: audio/mpeg`.
1054
1090
  *
1055
1091
  * @param options - The request description.
1056
1092
  * @returns The header record to send.
@@ -1067,9 +1103,15 @@ declare class Skailar {
1067
1103
  */
1068
1104
  private toApiError;
1069
1105
  /**
1070
- * Whether a status code is eligible for automatic retry (429 and any 5xx).
1106
+ * Whether an HTTP error status is eligible for automatic retry.
1107
+ *
1108
+ * A `429` is always retryable: the gateway rejects it before executing the
1109
+ * request, so replaying it cannot duplicate side effects. A `5xx` may mean the
1110
+ * request already executed server-side, so it is retried only when the caller
1111
+ * marked the request idempotent.
1071
1112
  *
1072
1113
  * @param status - The HTTP status code.
1114
+ * @param idempotent - Whether replaying the request is safe.
1073
1115
  * @returns `true` if retryable.
1074
1116
  */
1075
1117
  private isRetryableStatus;
@@ -1140,7 +1182,14 @@ declare abstract class SkailarError extends Error {
1140
1182
  readonly status: number | null;
1141
1183
  /** Machine-readable error code from the body, if any. */
1142
1184
  readonly code: string | undefined;
1143
- /** Correlation id from the `x-request-id` response header, if any. */
1185
+ /**
1186
+ * Correlation id from the `x-request-id` response header, if any, for support.
1187
+ *
1188
+ * @remarks
1189
+ * Populated on error responses. It is **not** currently surfaced for successful
1190
+ * streaming or audio responses (which return a stream rather than a wrapper),
1191
+ * so capture it from a thrown {@link SkailarError} when filing a ticket.
1192
+ */
1144
1193
  readonly requestId: string | undefined;
1145
1194
  /** The raw response body captured for debugging. */
1146
1195
  readonly raw: unknown;