{"version":3,"file":"index.mjs","names":["g"],"sources":["../src/api-promise.ts","../src/retry.ts","../src/errors.ts","../src/assets.ts","../src/compression.ts","../src/env.ts","../src/logging.ts","../src/questions.ts","../src/resources/models.ts","../src/runtime.ts","../src/version.ts","../src/client.ts"],"sourcesContent":["export const REQUEST_ID_HEADER = \"x-typesafe-request-id\";\n\nexport const requestIdFrom = (headers: Headers): string | undefined =>\n  headers.get(REQUEST_ID_HEADER) ?? undefined;\n\n/** Parsed data with its HTTP response and request ID. */\nexport interface WithResponse<T> {\n  /** The parsed response body. */\n  data: T;\n  /** The HTTP response, with its body consumed by parsing. */\n  response: Response;\n  /** Request ID from `x-typesafe-request-id`, or `undefined` when absent. */\n  requestId: string | undefined;\n}\n\n/**\n * A promise for the parsed result with access to the HTTP response.\n *\n * Non-2xx responses reject with an `APIError`, including through `asResponse()`.\n */\nexport class APIPromise<T> extends Promise<T> {\n  readonly #responsePromise: Promise<Response>;\n  readonly #parseResponse: (response: Response) => Promise<T>;\n  #parsed: Promise<T> | undefined;\n\n  constructor(\n    responsePromise: Promise<Response>,\n    parseResponse: (response: Response) => Promise<T>,\n  ) {\n    // The inherited promise is never used; all consumers go through `parse()`.\n    super((resolve) => resolve(undefined as T));\n    this.#responsePromise = responsePromise;\n    this.#parseResponse = parseResponse;\n  }\n\n  /**\n   * Resolves to the raw `Response` without parsing the body. SDK requests buffer the full\n   * body under the request timeout before handoff; reading it afterwards is caller-owned.\n   * The caller owns the body; don't also `await` the parsed result on the same promise.\n   */\n  asResponse(): Promise<Response> {\n    return this.#responsePromise;\n  }\n\n  /** Return the parsed result, HTTP response, and request ID. */\n  async withResponse(): Promise<WithResponse<T>> {\n    const [data, response] = await Promise.all([this.#parse(), this.#responsePromise]);\n    return { data, response, requestId: requestIdFrom(response.headers) };\n  }\n\n  /** Transform the parsed result, sharing the HTTP response and a single body parse. */\n  map<U>(fn: (data: T) => U): APIPromise<U> {\n    return new APIPromise<U>(this.#responsePromise, () => this.#parse().then(fn));\n  }\n\n  #parse(): Promise<T> {\n    this.#parsed ??= this.#responsePromise.then(this.#parseResponse);\n    return this.#parsed;\n  }\n\n  // biome-ignore lint/suspicious/noThenProperty: this is a Promise subclass; overriding then is the point\n  override then<TResult1 = T, TResult2 = never>(\n    onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n    onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n  ): Promise<TResult1 | TResult2> {\n    return this.#parse().then(onfulfilled, onrejected);\n  }\n\n  override catch<TResult = never>(\n    onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n  ): Promise<T | TResult> {\n    return this.#parse().catch(onrejected);\n  }\n\n  override finally(onfinally?: (() => void) | null): Promise<T> {\n    return this.#parse().finally(onfinally);\n  }\n}\n","/** Retry defaults, delay calculation, and cancellable waits. */\n\nimport type { RetryPolicy } from \"./types\";\n\nexport const DEFAULT_TIMEOUT_MS = 10_000;\n\nconst range = (from: number, to: number): number[] =>\n  Array.from({ length: to - from }, (_, i) => from + i);\n\n/** Default SDK retry policy. */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n  maxRetries: 2,\n  backoffInitialMs: 500,\n  backoffMaxMs: 5_000,\n  backoffJitter: 0.25,\n  /** HTTP 408, 429, and 5xx responses. */\n  httpStatuses: new Set([408, 429, ...range(500, 600)]),\n  respectRetryAfter: true,\n  /** Maximum server retry delay before falling back to backoff. */\n  maxRetryAfterMs: 60_000,\n  apiConnectionError: true,\n  apiTimeoutError: true,\n};\n\nexport const DEFAULT_MAX_RETRIES: number = DEFAULT_RETRY_POLICY.maxRetries;\n\n/** Whether the policy retries an HTTP status code. */\nexport const isRetryableStatus = (\n  status: number,\n  policy: RetryPolicy = DEFAULT_RETRY_POLICY,\n): boolean => policy.httpStatuses.has(status);\n\n/**\n * Parse `retry-after-ms` or `Retry-After` into milliseconds, preferring `retry-after-ms`.\n *\n * Return `undefined` when neither header contains a valid delay.\n */\nexport const parseRetryAfter = (headers: Headers, now: number = Date.now()): number | undefined => {\n  const ms = Number(headers.get(\"retry-after-ms\"));\n  if (headers.has(\"retry-after-ms\") && Number.isFinite(ms) && ms >= 0) return ms;\n\n  const raw = headers.get(\"retry-after\");\n  if (raw === null) return undefined;\n  const seconds = Number(raw);\n  if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1000 : undefined;\n  const date = Date.parse(raw);\n  if (!Number.isNaN(date)) return Math.max(0, date - now);\n  return undefined;\n};\n\n/**\n * Calculate the delay in milliseconds for a zero-based retry attempt.\n *\n * Use an allowed server delay; otherwise use capped exponential backoff with jitter.\n */\nexport const retryDelayMs = (\n  attempt: number,\n  headers?: Headers,\n  policy: RetryPolicy = DEFAULT_RETRY_POLICY,\n  random: () => number = Math.random,\n): number => {\n  if (policy.respectRetryAfter && headers !== undefined) {\n    const retryAfter = parseRetryAfter(headers);\n    if (retryAfter !== undefined && retryAfter <= policy.maxRetryAfterMs) return retryAfter;\n  }\n  const exponential = Math.min(policy.backoffInitialMs * 2 ** attempt, policy.backoffMaxMs);\n  return Math.round(exponential * (1 - random() * policy.backoffJitter));\n};\n\n/** Wait `ms` milliseconds, rejecting with `signal.reason` on cancellation. */\nexport const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n  new Promise((resolve, reject) => {\n    if (signal?.aborted) return reject(signal.reason);\n    const onAbort = (): void => {\n      clearTimeout(timer);\n      reject(signal?.reason);\n    };\n    const timer = setTimeout(() => {\n      signal?.removeEventListener(\"abort\", onAbort);\n      resolve();\n    }, ms);\n    signal?.addEventListener(\"abort\", onAbort, { once: true });\n  });\n","import { requestIdFrom } from \"./api-promise\";\nimport { parseRetryAfter } from \"./retry\";\n\n/** Base class for SDK errors. */\nexport class TypeSafeError extends Error {\n  constructor(message: string, options?: ErrorOptions) {\n    super(message, options);\n    this.name = new.target.name;\n  }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n  typeof value === \"object\" && value !== null;\n\n/** Extract a message from a text, error, or validation response body. */\nconst extractMessage = (body: unknown): string | undefined => {\n  if (typeof body === \"string\") return body || undefined;\n  if (!isRecord(body)) return undefined;\n  const { error, message, detail } = body;\n  if (typeof error === \"string\") return error;\n  if (isRecord(error) && typeof error.message === \"string\") return error.message;\n  if (typeof message === \"string\") return message;\n  if (typeof detail === \"string\") return detail;\n  if (isRecord(detail) && typeof detail.message === \"string\") return detail.message;\n  if (Array.isArray(detail)) return describeValidationErrors(detail);\n  return undefined;\n};\n\n/** Format validation errors as semicolon-separated `path: message` entries. */\nconst describeValidationErrors = (errors: unknown[]): string | undefined => {\n  const parts = errors.flatMap((e) => {\n    if (!isRecord(e) || typeof e.msg !== \"string\") return [];\n    const loc = Array.isArray(e.loc) ? e.loc.filter((x) => x !== \"body\").join(\".\") : \"\";\n    return [loc ? `${loc}: ${e.msg}` : e.msg];\n  });\n  return parts.length > 0 ? parts.join(\"; \") : undefined;\n};\n\nconst MAX_RAW_BODY_IN_MESSAGE = 200;\n\n/** An unsuccessful HTTP response from the API. */\nexport class APIError extends TypeSafeError {\n  /** HTTP response status code. */\n  readonly status: number;\n  /** HTTP response headers. */\n  readonly headers: Headers;\n  /** Parsed JSON, response text, or `undefined` for an empty body. */\n  readonly body: unknown;\n  /** Request ID from `x-typesafe-request-id`, or `undefined` when absent. */\n  readonly requestId: string | undefined;\n\n  constructor(status: number, body: unknown, headers: Headers, message?: string) {\n    super(message ?? APIError.describe(status, body));\n    this.status = status;\n    this.body = body;\n    this.headers = headers;\n    this.requestId = requestIdFrom(headers);\n  }\n\n  private static describe(status: number, body: unknown): string {\n    const detail = extractMessage(body);\n    if (detail) return `${status} ${detail}`;\n    if (body === undefined) return `${status} status code (no body)`;\n    const raw = typeof body === \"string\" ? body : JSON.stringify(body);\n    return `${status} ${raw.length > MAX_RAW_BODY_IN_MESSAGE ? `${raw.slice(0, MAX_RAW_BODY_IN_MESSAGE)}…` : raw}`;\n  }\n\n  /** Create the error subclass for an HTTP status code. */\n  static fromResponse(status: number, body: unknown, headers: Headers): APIError {\n    if (status === 400) return new BadRequestError(status, body, headers);\n    if (status === 401) return new AuthenticationError(status, body, headers);\n    if (status === 403) return new PermissionDeniedError(status, body, headers);\n    if (status === 404) return new NotFoundError(status, body, headers);\n    if (status === 422) return new UnprocessableEntityError(status, body, headers);\n    if (status === 429) return new RateLimitError(status, body, headers);\n    if (status >= 500) return new InternalServerError(status, body, headers);\n    return new APIError(status, body, headers);\n  }\n}\n\n/** HTTP 400: the request is invalid. */\nexport class BadRequestError extends APIError {}\n/** HTTP 401: authentication failed. */\nexport class AuthenticationError extends APIError {}\n/** HTTP 403: access is denied. */\nexport class PermissionDeniedError extends APIError {}\n/** HTTP 404: the resource was not found. */\nexport class NotFoundError extends APIError {}\n/** HTTP 422: request validation failed. */\nexport class UnprocessableEntityError extends APIError {}\n/** HTTP 429: the rate limit was exceeded. */\nexport class RateLimitError extends APIError {\n  /** Server retry delay in milliseconds, or `undefined` when absent or invalid. */\n  readonly retryAfterMs: number | undefined = parseRetryAfter(this.headers);\n}\n/** HTTP 5xx: the server failed to handle the request. */\nexport class InternalServerError extends APIError {}\n\n/** The request or response-body delivery failed (DNS, TLS, connection closed, etc.). */\nexport class APIConnectionError extends TypeSafeError {\n  constructor(message = \"Connection error.\", options?: ErrorOptions) {\n    super(message, options);\n  }\n}\n\n/** The full response did not arrive within the timeout. A kind of `APIConnectionError`. */\nexport class APITimeoutError extends APIConnectionError {\n  /** Configured timeout in milliseconds. */\n  readonly timeoutMs: number;\n\n  constructor(timeoutMs: number, options?: ErrorOptions) {\n    super(`Request timed out after ${timeoutMs}ms.`, options);\n    this.timeoutMs = timeoutMs;\n  }\n}\n\n/** The caller cancelled the request through an `AbortSignal`. */\nexport class APIUserAbortError extends TypeSafeError {\n  constructor(message = \"Request was aborted.\", options?: ErrorOptions) {\n    super(message, options);\n  }\n}\n","import { TypeSafeError } from \"./errors\";\nimport type { Asset } from \"./types\";\n\n/**\n * The file signatures that PNG (PNG spec §5.2) and JPEG (ITU T.81 SOI marker) files start\n * with, and the content type each identifies.\n */\nconst CONTENT_TYPES = [\n  [\"image/png\", [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]],\n  [\"image/jpeg\", [0xff, 0xd8, 0xff]],\n] as const;\n\n/** Matches `String(image)`: the reference an image is sent under. */\nconst REFERENCE = /<image:[0-9a-f]{32}>/g;\n\n/** Marks `Image` objects, including those created by another copy of the SDK. */\nconst IMAGE = Symbol.for(\"@typesafe-ai/sdk/image\");\n\n/** Marks `TextWithAssets` objects, including those created by another copy of the SDK. */\nconst TEXT_WITH_ASSETS = Symbol.for(\"@typesafe-ai/sdk/text-with-assets\");\n\n/** 32 random lowercase hex digits. */\nconst randomHex = (): string =>\n  Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) =>\n    byte.toString(16).padStart(2, \"0\"),\n  ).join(\"\");\n\nconst isImage = (value: object): value is Image => IMAGE in value;\n\nconst isTextWithAssets = (value: object): value is TextWithAssets => TEXT_WITH_ASSETS in value;\n\n/** `value`'s `Symbol.toStringTag`, such as `Promise`, or its `typeof` when it isn't an object. */\nconst typeName = (value: unknown): string => {\n  if (value === null) return \"null\";\n  if (typeof value !== \"object\") return typeof value;\n  return Object.prototype.toString.call(value).slice(8, -1);\n};\n\n/** A `Uint8Array` over the bytes `data` holds or views, without copying them. */\nconst toBytes = (data: ArrayBuffer | ArrayBufferView): Uint8Array => {\n  // The tag check also matches an ArrayBuffer from another realm, such as an iframe.\n  if (\n    !ArrayBuffer.isView(data) &&\n    Object.prototype.toString.call(data) !== \"[object ArrayBuffer]\"\n  ) {\n    throw new TypeSafeError(`Image data must be file bytes or a Blob; got ${typeName(data)}.`);\n  }\n  return ArrayBuffer.isView(data)\n    ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n    : new Uint8Array(data);\n};\n\n/** The content type whose signature `bytes` start with, or `application/octet-stream`. */\nconst contentTypeOf = (bytes: Uint8Array): string => {\n  for (const [contentType, signature] of CONTENT_TYPES) {\n    if (signature.every((byte, i) => bytes[i] === byte)) return contentType;\n  }\n  return \"application/octet-stream\";\n};\n\n/** A PNG or JPEG image asset, created by `image` or `Image.fromBase64`. */\nexport class Image {\n  readonly type = \"image\";\n  /** The image file bytes, or a `Blob` read when the request is sent. */\n  readonly data: Uint8Array | Blob;\n  readonly #reference = `<image:${randomHex()}>`;\n\n  /** @throws {TypeSafeError} `data` is empty or isn't file bytes or a `Blob`. */\n  constructor(data: Blob | ArrayBuffer | ArrayBufferView) {\n    this.data = data instanceof Blob ? data : toBytes(data);\n    const size = this.data instanceof Blob ? this.data.size : this.data.byteLength;\n    if (size === 0) throw new TypeSafeError(\"Image data is empty.\");\n  }\n\n  /**\n   * Create an image from base64-encoded file bytes, decoding them now.\n   *\n   * @param text - The image file bytes, base64-encoded, without a `data:` URL prefix.\n   * @throws {TypeSafeError} `text` isn't valid base64 or decodes to no bytes.\n   *\n   * @example\n   * ```ts\n   * const photo = Image.fromBase64(upload.photoBase64);\n   * ```\n   */\n  static fromBase64(text: string): Image {\n    let binary: string;\n    try {\n      binary = atob(text);\n    } catch (err) {\n      throw new TypeSafeError(\"Image data must contain valid base64 text.\", { cause: err });\n    }\n    return new Image(Uint8Array.from(binary, (char) => char.charCodeAt(0)));\n  }\n\n  /** The unique reference this image is sent under, for referencing it inside text. */\n  toString(): string {\n    return this.#reference;\n  }\n\n  /** The reference, written by `JSON.stringify` wherever the image appears in a request. */\n  toJSON(): string {\n    return this.#reference;\n  }\n}\nObject.defineProperty(Image.prototype, IMAGE, { value: true });\n\n/** Text from a `withAssets` tagged template, with the assets interpolated into it. */\nexport class TextWithAssets {\n  /** The text, with each asset replaced by its reference. */\n  readonly text: string;\n  /** The assets interpolated into the text, including those in nested `withAssets` text. */\n  readonly assets: readonly Asset[];\n\n  constructor(text: string, assets: readonly Asset[]) {\n    this.text = text;\n    this.assets = assets;\n  }\n\n  toString(): string {\n    return this.text;\n  }\n\n  /** The text, written by `JSON.stringify` wherever this value appears in a request. */\n  toJSON(): string {\n    return this.text;\n  }\n}\nObject.defineProperty(TextWithAssets.prototype, TEXT_WITH_ASSETS, { value: true });\n\n/**\n * Create an image asset for `systemOne`.\n *\n * Place the image in `state` or question content, or interpolate it into a `withAssets`\n * tagged template; either way it is sent under its own reference, `String(image)`. To\n * reference it by a name of your choice, pass it in `assets` instead.\n *\n * The image must be PNG or JPEG. The API detects the format from the file bytes and rejects\n * other formats with a `BadRequestError`. `Blob` data is read when the request is sent, and its\n * `type` is ignored. For base64 text, use `Image.fromBase64`.\n *\n * @param data - Image file bytes, or a `Blob` such as a `File`.\n * @throws {TypeSafeError} `data` is empty or isn't file bytes or a `Blob`.\n *\n * @example\n * ```ts\n * // Node: `openAsBlob` reads a file as a Blob and is exported by \"node:fs\".\n * const { answers } = await client.systemOne({\n *   state: image(await openAsBlob(\"product.png\")),\n *   questions: { damaged: noul(\"Is the product damaged?\") },\n * });\n * ```\n */\nexport const image = (data: Blob | ArrayBuffer | ArrayBufferView): Image => new Image(data);\n\n/** `text` with the assets in `values` whose references it contains, in order of appearance. */\nconst textWithAssets = (text: string, values: readonly unknown[]): TextWithAssets => {\n  const interpolated = new Map<string, Asset>();\n  collectAssets(values, interpolated, new Set());\n  const assets = new Map<string, Asset>();\n  for (const [reference] of text.matchAll(REFERENCE)) {\n    const asset = interpolated.get(reference);\n    if (asset !== undefined) assets.set(reference, asset);\n  }\n  return new TextWithAssets(text, [...assets.values()]);\n};\n\n/**\n * Tag a template literal so the assets interpolated into it are sent with the text.\n *\n * Each asset is replaced by its reference; other values are converted to strings, as in an\n * untagged template literal. To write a list of assets with a separator, use\n * `withAssets.join`.\n *\n * @example\n * ```ts\n * const { answers } = await client.systemOne({\n *   state: withAssets`Compare ${photo} with the listing.`,\n *   questions: { same: noul(withAssets`Is ${photo} the product in ${listing}?`) },\n * });\n * ```\n */\nexport const withAssets: {\n  (strings: TemplateStringsArray, ...values: readonly unknown[]): TextWithAssets;\n  /**\n   * Join `values` with `separator`, as `Array.prototype.join` does, and send the assets among\n   * them with the text. The result can be passed as content or interpolated into `withAssets`.\n   *\n   * @param separator - Written between values. Default: `\",\"`.\n   *\n   * @example\n   * ```ts\n   * const { answers } = await client.systemOne({\n   *   state: withAssets`The seller uploaded ${withAssets.join(uploads, \", \")}.`,\n   *   questions: { same: noul(\"Do the uploads show the same product?\") },\n   * });\n   * ```\n   */\n  join(values: readonly unknown[], separator?: string): TextWithAssets;\n} = Object.assign(\n  (strings: TemplateStringsArray, ...values: readonly unknown[]): TextWithAssets =>\n    textWithAssets(\n      strings.reduce((joined, piece, i) => joined + String(values[i - 1]) + piece),\n      values,\n    ),\n  {\n    join: (values: readonly unknown[], separator?: string): TextWithAssets =>\n      textWithAssets(values.join(separator), values),\n  },\n);\n\n/** Add the assets in `value`, including those in `withAssets` text, to `found` by reference. */\nconst collectAssets = (value: unknown, found: Map<string, Asset>, visited: Set<object>): void => {\n  if (typeof value !== \"object\" || value === null || visited.has(value)) return;\n  visited.add(value);\n  if (isImage(value)) found.set(String(value), value);\n  else if (isTextWithAssets(value))\n    for (const asset of value.assets) found.set(String(asset), asset);\n  else for (const item of Object.values(value)) collectAssets(item, found, visited);\n};\n\n/**\n * Serialize `payload` to JSON, writing each asset as its name in `assets`, or else as its\n * reference, and collect the assets the request sends.\n *\n * The assets are those in `assets`, then each asset whose reference appears in the JSON, in\n * order of appearance: assets placed in content, in `withAssets` text, or in `assets`.\n *\n * @throws {TypeSafeError} The JSON holds the reference of an asset not attached to the request,\n *   or doesn't contain the name of an asset in `assets`.\n */\nexport const serializeRequest = (\n  payload: object,\n  assets: Record<string, Asset> = {},\n): { json: string; assets: Record<string, Asset> | undefined } => {\n  // An asset under several names is written as the last one.\n  const names = new Map<object, string>(\n    Object.entries(assets).map(([name, asset]) => [asset, name]),\n  );\n  const known = new Map(Object.values(assets).map((asset) => [String(asset), asset]));\n  const json = JSON.stringify(\n    payload,\n    function (this: Record<string, unknown>, key: string, value: unknown): unknown {\n      // `JSON.stringify` writes NaN and infinities as `null`; send them as strings instead.\n      if (typeof value === \"number\" && !Number.isFinite(value)) return String(value);\n      // `value` is the result of `toJSON`, so the original is read from the holder.\n      const original = this[key];\n      if (typeof original !== \"object\" || original === null) return value;\n      if (isImage(original)) {\n        const name = names.get(original);\n        if (name !== undefined) return name;\n        known.set(String(original), original);\n      } else if (isTextWithAssets(original)) {\n        let text = original.text;\n        for (const asset of original.assets) {\n          const name = names.get(asset);\n          if (name === undefined) known.set(String(asset), asset);\n          else text = text.replaceAll(String(asset), name);\n        }\n        return text;\n      }\n      return value;\n    },\n  );\n  // Names are matched as they appear in the JSON, with quotes and backslashes escaped.\n  const unreferenced = Object.keys(assets).filter(\n    (name) => !json.includes(JSON.stringify(name).slice(1, -1)),\n  );\n  if (unreferenced.length > 0) {\n    throw new TypeSafeError(\n      `Assets not referenced in the request: ${unreferenced.join(\", \")}. ` +\n        \"Write each name in `assets` into `state`, question instructions, or criteria.\",\n    );\n  }\n  const sent = new Map(Object.entries(assets));\n  const missing = new Set<string>();\n  for (const [reference] of json.matchAll(REFERENCE)) {\n    if (sent.has(reference)) continue;\n    const asset = known.get(reference);\n    if (asset === undefined) missing.add(reference);\n    else sent.set(reference, asset);\n  }\n  if (missing.size > 0) {\n    throw new TypeSafeError(\n      `Image references without an attached image: ${[...missing].join(\", \")}. ` +\n        \"Tag template literals that interpolate images with `withAssets`.\",\n    );\n  }\n  return { json, assets: sent.size === 0 ? undefined : Object.fromEntries(sent) };\n};\n\n/** An image asset as sent in a `multipart/form-data` body, naming the part with its file bytes. */\nexport interface ImagePartAsset {\n  type: \"image\";\n  /** The name of the body part that holds the image file bytes. */\n  part: string;\n}\n\n/** A part of a `multipart/form-data` body. */\ninterface Part {\n  /** Written unescaped, so it must be ASCII without quotes. */\n  name: string;\n  contentType: string;\n  content: string | Uint8Array<ArrayBuffer>;\n  /** Written unescaped, so it must be ASCII without quotes. */\n  filename?: string;\n}\n\n/** A `multipart/form-data` request body (RFC 7578) whose first part is a JSON payload. */\nexport class MultipartBody {\n  /** The JSON payload, sent as the `request` part. */\n  readonly payload: unknown;\n  /** The `Content-Type` header value, including the boundary. */\n  readonly contentType: string;\n  /** The encoded body. */\n  readonly content: Blob;\n\n  constructor(payload: unknown, parts: readonly Part[]) {\n    // A random boundary, as browsers use, is practically certain not to occur in the content.\n    const boundary = randomHex();\n    const chunks: (string | Uint8Array<ArrayBuffer>)[] = [];\n    for (const { name, contentType, content, filename } of [\n      { name: \"request\", contentType: \"application/json\", content: JSON.stringify(payload) },\n      ...parts,\n    ]) {\n      const disposition =\n        filename === undefined ? `name=\"${name}\"` : `name=\"${name}\"; filename=\"${filename}\"`;\n      chunks.push(\n        `--${boundary}\\r\\nContent-Disposition: form-data; ${disposition}\\r\\n`,\n        `Content-Type: ${contentType}\\r\\n\\r\\n`,\n        content,\n        \"\\r\\n\",\n      );\n    }\n    chunks.push(`--${boundary}--\\r\\n`);\n    this.payload = payload;\n    this.contentType = `multipart/form-data; boundary=${boundary}`;\n    this.content = new Blob(chunks);\n  }\n}\n\n/** The image's file bytes, reading `Blob` data. */\nconst readImage = async (alias: string, { data }: Image): Promise<Uint8Array> => {\n  if (!(data instanceof Blob)) return data;\n  try {\n    return new Uint8Array(await data.arrayBuffer());\n  } catch (err) {\n    throw new TypeSafeError(`Asset \"${alias}\" could not be read: ${(err as Error).message}`, {\n      cause: err,\n    });\n  }\n};\n\n/** `bytes`, copied when backed by a `SharedArrayBuffer`, which `Blob` doesn't accept. */\nconst unshared = (bytes: Uint8Array): Uint8Array<ArrayBuffer> =>\n  bytes.buffer instanceof ArrayBuffer ? (bytes as Uint8Array<ArrayBuffer>) : bytes.slice();\n\n/**\n * `assets`, with each asset's file bytes copied, so writes to the caller's buffers after this\n * call don't change what is sent. `Blob` data can't change, and isn't copied.\n */\nexport const copyAssetBytes = (assets: Record<string, Asset>): Record<string, Asset> =>\n  Object.fromEntries(\n    Object.entries(assets).map(([alias, asset]) => [\n      alias,\n      asset.data instanceof Uint8Array ? new Image(asset.data.slice()) : asset,\n    ]),\n  );\n\n/**\n * A `multipart/form-data` body whose first part, `request`, is `payload` with `assets` added,\n * followed by each asset's file bytes in a part its entry names. `Blob` data is read\n * concurrently.\n *\n * @throws {TypeSafeError} A `Blob` can't be read.\n */\nexport const encodeAssets = async (\n  payload: object,\n  assets: Record<string, Asset>,\n): Promise<MultipartBody> => {\n  const read = await Promise.all(\n    Object.entries(assets).map(\n      async ([alias, asset]) => [alias, asset, await readImage(alias, asset)] as const,\n    ),\n  );\n  // The API accepts each part for only one asset, so an asset under several references is\n  // sent once per reference.\n  const parts: Part[] = [];\n  const entries: [string, ImagePartAsset][] = [];\n  for (const [alias, { type }, data] of read) {\n    const name = `asset-${parts.length}`;\n    parts.push({ name, contentType: contentTypeOf(data), content: unshared(data), filename: name });\n    entries.push([alias, { type, part: name }]);\n  }\n  return new MultipartBody({ ...payload, assets: Object.fromEntries(entries) }, parts);\n};\n","import { TypeSafeError } from \"./errors\";\nimport type { Compression } from \"./types\";\n\n/** Bodies below this many bytes fit in a single TCP segment, so they are sent uncompressed. */\nexport const MIN_COMPRESSED_BODY_BYTES = 1024;\n\ninterface Zlib {\n  zstdCompress?: (\n    data: Uint8Array,\n    callback: (err: Error | null, result: Uint8Array) => void,\n  ) => void;\n}\n\ninterface CompressionGlobals {\n  process?: { getBuiltinModule?: (id: string) => unknown };\n}\n\nconst g = globalThis as CompressionGlobals;\n\n/** `node:zlib`, read without an import so the SDK still loads where Node modules don't exist. */\nconst zlib = (): Zlib | undefined => {\n  try {\n    return g.process?.getBuiltinModule?.(\"node:zlib\") as Zlib | undefined;\n  } catch {\n    return undefined;\n  }\n};\n\nconst hasZstd = (): boolean => typeof zlib()?.zstdCompress === \"function\";\n\n/**\n * Resolve the `compression` option to the `Content-Encoding` request bodies are sent with:\n * zstd when the runtime has it, otherwise `false`.\n *\n * @throws {TypeSafeError} The value isn't a supported option, or the runtime lacks it.\n */\nexport const resolveCompression = (compression: Compression | undefined): Compression => {\n  if (compression === undefined) return hasZstd() ? \"zstd\" : false;\n  if (compression === false) return false;\n  if (compression === \"zstd\") {\n    if (!hasZstd()) {\n      throw new TypeSafeError(\n        \"zstd compression requires Node.js 22.15 or newer. Pass `compression: false` instead.\",\n      );\n    }\n    return compression;\n  }\n  throw new TypeSafeError(\n    `\\`compression\\` must be \"zstd\" or false, got ${JSON.stringify(compression)}.`,\n  );\n};\n\nconst zstd = async (body: Blob): Promise<Uint8Array<ArrayBuffer>> => {\n  const data = new Uint8Array(await body.arrayBuffer());\n  const compressed = await new Promise<Uint8Array>((resolve, reject) => {\n    zlib()?.zstdCompress?.(data, (err, result) => (err ? reject(err) : resolve(result)));\n  });\n  return new Uint8Array(compressed);\n};\n\n/** The size of a request body in bytes, with text measured as UTF-8. */\nexport const byteLength = (body: string | Blob): number =>\n  typeof body === \"string\" ? new TextEncoder().encode(body).byteLength : body.size;\n\n/** Compress a request body with zstd. */\nexport const compressBody = (body: string | Blob): Promise<Uint8Array<ArrayBuffer>> =>\n  zstd(typeof body === \"string\" ? new Blob([body]) : body);\n","/** Environment variable names for client configuration. Explicit options take precedence. */\nexport const ENV = {\n  /** Required API key; used when `apiKey` is omitted. */\n  apiKey: \"TYPESAFE_API_KEY\",\n  /** API root; defaults to `https://api.typesafe.ai`. */\n  baseURL: \"TYPESAFE_BASE_URL\",\n  /** Default model name; defaults to `jev-latest`. */\n  defaultModel: \"TYPESAFE_DEFAULT_MODEL\",\n  /** Log level; defaults to `warn`. */\n  logLevel: \"TYPESAFE_LOG_LEVEL\",\n} as const;\n\nexport type EnvVar = (typeof ENV)[keyof typeof ENV];\n\n/** Read a trimmed environment value, returning `undefined` for missing or blank values. */\nexport const readEnv = (name: EnvVar): string | undefined => {\n  if (typeof process === \"undefined\" || !process.env) return undefined;\n  return process.env[name]?.trim() || undefined;\n};\n\n/** Return the explicit value, falling back to the environment. */\nexport const fromCodeOrEnv = (fromCode: string | undefined, envVar: EnvVar): string | undefined =>\n  fromCode ?? readEnv(envVar);\n","import { TypeSafeError } from \"./errors\";\nimport type { Logger, LogLevel } from \"./types\";\n\n/** Supported log levels, from most to least verbose. */\nexport const LOG_LEVELS: readonly LogLevel[] = [\"debug\", \"info\", \"warn\", \"error\", \"off\"];\n\nexport const DEFAULT_LOG_LEVEL: LogLevel = \"warn\";\n\nconst isLogLevel = (value: string): value is LogLevel =>\n  (LOG_LEVELS as readonly string[]).includes(value);\n\n/** Validate a configured log level, throwing `TypeSafeError` for unknown values. */\nexport const parseLogLevel = (value: string, source: string): LogLevel => {\n  if (isLogLevel(value)) return value;\n  throw new TypeSafeError(\n    `Invalid log level \"${value}\" from ${source}. Expected one of: ${LOG_LEVELS.join(\", \")}.`,\n  );\n};\n\n// ---------------------------------------------------------------------------\n// Loggers\n// ---------------------------------------------------------------------------\n\nconst PREFIX = \"[typesafe-sdk]\";\n\n/** Default console logger with the `[typesafe-sdk]` prefix. */\nexport const consoleLogger: Logger = {\n  debug: (message, ...args) => console.debug(`${PREFIX} ${message}`, ...args),\n  info: (message, ...args) => console.info(`${PREFIX} ${message}`, ...args),\n  warn: (message, ...args) => console.warn(`${PREFIX} ${message}`, ...args),\n  error: (message, ...args) => console.error(`${PREFIX} ${message}`, ...args),\n};\n\nconst RANK: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3, off: 4 };\n\nconst drop = (): void => {};\n\n/** Filter logger calls to the configured level and above. */\nexport const withLevel = (sink: Logger, level: LogLevel): Logger => {\n  const enabled = (at: LogLevel): boolean => RANK[at] >= RANK[level];\n  return {\n    debug: enabled(\"debug\") ? (message, ...args) => sink.debug(message, ...args) : drop,\n    info: enabled(\"info\") ? (message, ...args) => sink.info(message, ...args) : drop,\n    warn: enabled(\"warn\") ? (message, ...args) => sink.warn(message, ...args) : drop,\n    error: enabled(\"error\") ? (message, ...args) => sink.error(message, ...args) : drop,\n  };\n};\n\n// ---------------------------------------------------------------------------\n// Redaction\n// ---------------------------------------------------------------------------\n\n/** Credential headers that retain a key suffix for identification. */\nconst KEY_HEADERS: ReadonlySet<string> = new Set([\n  \"authorization\",\n  \"proxy-authorization\",\n  \"x-api-key\",\n]);\n\n/** Headers whose values are redacted in full. */\nconst OPAQUE_HEADERS: ReadonlySet<string> = new Set([\"cookie\", \"set-cookie\"]);\n\n/** Mask a key, preserving its scheme and the last four characters of secrets longer than eight. */\nconst redactKey = (value: string): string => {\n  const [scheme, secret] = value.includes(\" \") ? value.split(/\\s+/, 2) : [undefined, value];\n  const tail = secret && secret.length > 8 ? secret.slice(-4) : \"\";\n  return `${scheme ? `${scheme} ` : \"\"}***${tail}`;\n};\n\nconst redact = (name: string, value: string): string => {\n  const lower = name.toLowerCase();\n  if (KEY_HEADERS.has(lower)) return redactKey(value);\n  if (OPAQUE_HEADERS.has(lower)) return \"***\";\n  return value;\n};\n\n/** Copy headers with known credential values redacted. */\nexport const redactHeaders = (headers: Record<string, string>): Record<string, string> =>\n  Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, redact(name, value)]));\n","import { TypeSafeError } from \"./errors\";\nimport type {\n  BoxQuestion,\n  ChoiceCriteria,\n  ChoiceQuestion,\n  EntryType,\n  NoulQuestion,\n  Questions,\n  ScoreCriteria,\n  ScoreQuestion,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Builders\n// ---------------------------------------------------------------------------\n\n/**\n * Create a yes/no question with optional descriptions for either outcome.\n *\n * @param instructions - The question as text, a JSON object or array; `null` or omitted\n * requires `criteria` to describe at least one outcome.\n * @param criteria - Descriptions of the yes and no outcomes.\n */\nexport const noul: {\n  (instructions: NonNullable<EntryType>, criteria?: NoulQuestion[\"criteria\"]): NoulQuestion;\n  (\n    instructions: EntryType | undefined,\n    criteria:\n      | { true: NonNullable<EntryType>; false?: EntryType }\n      | { true?: EntryType; false: NonNullable<EntryType> },\n  ): NoulQuestion;\n} = (instructions: EntryType = null, criteria?: NoulQuestion[\"criteria\"]): NoulQuestion => ({\n  type: \"noul\",\n  instructions,\n  criteria,\n});\n\n/**\n * Create a score question using an ordered rubric.\n *\n * @param instructions - The question as text, a JSON object or array, or `null`.\n * @param criteria - At least two descriptions indexed by score from zero; entries may be `null`.\n *   A list built at runtime, such as a `string[]`, is accepted, and `systemOne` rejects it when\n *   it has fewer than two entries.\n */\nexport const score: {\n  <const T extends ScoreCriteria>(instructions: EntryType, criteria: T): ScoreQuestion<T>;\n  <const T extends readonly EntryType[]>(\n    instructions: EntryType,\n    // A literal list's length is known, so lists of fewer than two entries match no overload.\n    criteria: T & (number extends T[\"length\"] ? unknown : never),\n  ): ScoreQuestion<readonly [T[number], T[number], ...T[number][]]>;\n} = (instructions: EntryType, criteria: readonly EntryType[]): ScoreQuestion => {\n  // `systemOne` rejects lists of fewer than two entries.\n  const rubric = criteria as ScoreCriteria;\n  if (!Array.isArray(criteria)) {\n    throw new TypeSafeError(\n      \"Score criteria must be a list of descriptions indexed by score from zero, not a map.\",\n    );\n  }\n  return { type: \"score\", instructions, criteria: rubric };\n};\n\n/**\n * Create a question that selects between named alternatives.\n *\n * @param instructions - The question as text, a JSON object or array, or `null`.\n * @param criteria - Labels mapped to descriptions, or `null` for undescribed labels.\n */\nexport const choice = <const T extends ChoiceCriteria>(\n  instructions: EntryType,\n  criteria: T,\n): ChoiceQuestion<T> => {\n  if (Array.isArray(criteria)) {\n    throw new TypeSafeError(\"Choice criteria must be a map of labels to descriptions, not a list.\");\n  }\n  return { type: \"choice\", instructions, criteria };\n};\n\n/**\n * Create a question that locates what its instructions describe in the request's image.\n * Use the `jev-preview` model for `box` questions.\n *\n * @param instructions - What to locate, as text, an asset, a JSON object or array; defaults to `null`.\n *\n * @example\n * ```ts\n * const { answers } = await client.systemOne({\n *   state: image(await openAsBlob(\"photo.jpg\")),\n *   questions: { dog: box(\"The dog\") },\n *   model: \"jev-preview\",\n * });\n * const { top, bottom, left, right } = answers.dog.box;\n * ```\n */\nexport const box = (instructions: EntryType = null): BoxQuestion => ({\n  type: \"box\",\n  instructions,\n});\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n  typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst validateChoice = (name: string, { criteria }: ChoiceQuestion): void => {\n  if (!isObject(criteria)) {\n    throw new TypeSafeError(\n      `Choice question \"${name}\" has criteria that are not a map; ` +\n        \"choice criteria must be a map of labels to descriptions.\",\n    );\n  }\n  if (Object.keys(criteria).length === 0) {\n    throw new TypeSafeError(\n      `Choice question \"${name}\" has no criteria; at least one choice is required.`,\n    );\n  }\n};\n\nconst validateNoul = (name: string, { instructions, criteria }: NoulQuestion): void => {\n  if (criteria != null && !isObject(criteria)) {\n    throw new TypeSafeError(`Noul question \"${name}\" criteria must be an object.`);\n  }\n  if (instructions == null && !Object.values(criteria ?? {}).some((value) => value != null)) {\n    throw new TypeSafeError(\n      `Noul question \"${name}\" has neither instructions nor criteria; at least one is required.`,\n    );\n  }\n};\n\n/**\n * Reject empty question sets, score questions without a list of at least two criteria, choice\n * questions without a nonempty map of criteria, and noul questions with non-object criteria or\n * with neither instructions nor a described outcome.\n */\nexport const validateQuestions = (questions: Questions): void => {\n  if (Object.keys(questions).length === 0) {\n    throw new TypeSafeError(\"At least one question is required.\");\n  }\n  for (const [name, question] of Object.entries(questions)) {\n    if (question.type === \"choice\") validateChoice(name, question);\n    if (question.type === \"noul\") validateNoul(name, question);\n    if (question.type !== \"score\") continue;\n    if (!Array.isArray(question.criteria)) {\n      throw new TypeSafeError(\n        `Score question \"${name}\" has criteria that are not a list; ` +\n          \"score criteria must be a list of descriptions indexed by score from zero.\",\n      );\n    }\n    if (question.criteria.length < 2) {\n      throw new TypeSafeError(\n        `Score question \"${name}\" has ${question.criteria.length} criteria; ` +\n          \"at least two scores are required.\",\n      );\n    }\n  }\n};\n","import type { APIPromise } from \"../api-promise\";\nimport type { Transport } from \"../client\";\nimport { TypeSafeError } from \"../errors\";\nimport type { ModelCard, RequestOptions } from \"../types\";\n\n/** Access to the Models API resource. */\nexport class Models {\n  readonly #transport: Transport;\n\n  constructor(transport: Transport) {\n    this.#transport = transport;\n  }\n\n  /** List the models available to the account. */\n  list(options: RequestOptions = {}): APIPromise<ModelCard[]> {\n    return this.#transport.request<ModelsWire>(\"GET\", \"/v1/models\", options).map(unwrapModels);\n  }\n}\n\n/** Model list response from `GET /v1/models`. */\ntype ModelsWire = { models: ModelCard[] };\n\nconst unwrapModels = (wire: ModelsWire): ModelCard[] => {\n  if (Array.isArray(wire?.models)) return wire.models;\n  throw new TypeSafeError(\n    \"Unexpected response shape from GET /v1/models; expected { models: [...] }.\",\n  );\n};\n","/** Runtime detection for browser guards and request headers. */\n\ninterface RuntimeGlobals {\n  window?: { document?: unknown };\n  navigator?: { userAgent?: string };\n  process?: { versions?: Record<string, string | undefined>; platform?: string; arch?: string };\n  Deno?: { version?: { deno?: string } };\n  Bun?: { version?: string };\n  EdgeRuntime?: unknown;\n}\n\nconst g = globalThis as RuntimeGlobals;\n\n/** Whether browser page globals are present. */\nexport const isBrowser = (): boolean =>\n  typeof g.window !== \"undefined\" &&\n  typeof g.window.document !== \"undefined\" &&\n  typeof g.navigator !== \"undefined\";\n\n/** Runtime name, version, and platform for the `X-TypeSafe-Runtime` header. */\nexport const describeRuntime = (): string => {\n  const platform =\n    g.process?.platform && g.process?.arch ? ` (${g.process.platform}; ${g.process.arch})` : \"\";\n  if (g.Bun?.version) return `bun/${g.Bun.version}${platform}`;\n  if (g.Deno?.version?.deno) return `deno/${g.Deno.version.deno}${platform}`;\n  if (g.EdgeRuntime !== undefined) return \"vercel-edge\";\n  if (g.navigator?.userAgent === \"Cloudflare-Workers\") return \"cloudflare-workers\";\n  if (g.process?.versions?.node) return `node/${g.process.versions.node}${platform}`;\n  if (isBrowser()) return \"browser\";\n  return \"unknown\";\n};\n","// Keep in sync with package.json \"version\". Checked by `npm run check:version`.\nexport const VERSION = \"0.7.0\";\n","import { APIPromise, requestIdFrom } from \"./api-promise\";\nimport { copyAssetBytes, encodeAssets, MultipartBody, serializeRequest } from \"./assets\";\nimport {\n  byteLength,\n  compressBody,\n  MIN_COMPRESSED_BODY_BYTES,\n  resolveCompression,\n} from \"./compression\";\nimport { ENV, fromCodeOrEnv, readEnv } from \"./env\";\nimport {\n  APIConnectionError,\n  APIError,\n  APITimeoutError,\n  APIUserAbortError,\n  TypeSafeError,\n} from \"./errors\";\nimport {\n  consoleLogger,\n  DEFAULT_LOG_LEVEL,\n  parseLogLevel,\n  redactHeaders,\n  withLevel,\n} from \"./logging\";\nimport { validateQuestions } from \"./questions\";\nimport { Models } from \"./resources/models\";\nimport {\n  DEFAULT_RETRY_POLICY,\n  DEFAULT_TIMEOUT_MS,\n  isRetryableStatus,\n  retryDelayMs,\n  sleep,\n} from \"./retry\";\nimport { describeRuntime, isBrowser } from \"./runtime\";\nimport type {\n  Compression,\n  Fetch,\n  Logger,\n  LogLevel,\n  Questions,\n  RequestOptions,\n  RetryPolicy,\n  SystemOneRequest,\n  SystemOneResult,\n  TypeSafeClientConfig,\n} from \"./types\";\nimport { VERSION } from \"./version\";\n\nexport const DEFAULT_BASE_URL = \"https://api.typesafe.ai\";\nexport const DEFAULT_MODEL = \"jev-latest\";\n\n// ---------------------------------------------------------------------------\n// Construction-time checks\n// ---------------------------------------------------------------------------\n\nconst missingApiKey = (): never => {\n  throw new TypeSafeError(\n    `No API key was provided. Pass \\`apiKey\\` to the TypeSafeClient constructor or set the ${ENV.apiKey} environment variable.`,\n  );\n};\n\nconst missingFetch = (): never => {\n  throw new TypeSafeError(\n    \"No global `fetch` is available in this runtime. Pass a `fetch` implementation to the TypeSafeClient constructor.\",\n  );\n};\n\nconst refuseBrowser = (): never => {\n  throw new TypeSafeError(\n    \"TypeSafeClient is running in a browser, which would expose your API key to anyone using the page. \" +\n      \"Call the API from a server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.\",\n  );\n};\n\n/** Call global `fetch` with its required receiver in browsers. */\nconst defaultFetch: Fetch = (input, init) => globalThis.fetch(input, init);\n\nconst assertNonNegativeInteger = (name: string, value: number): number => {\n  if (!Number.isInteger(value) || value < 0) {\n    throw new TypeSafeError(`\\`${name}\\` must be a non-negative integer, got ${String(value)}.`);\n  }\n  return value;\n};\n\nconst assertPositiveMs = (name: string, value: number): number => {\n  if (!Number.isFinite(value) || value <= 0) {\n    throw new TypeSafeError(\n      `\\`${name}\\` must be a positive number of milliseconds, got ${String(value)}.`,\n    );\n  }\n  return value;\n};\n\nconst assertNonNegativeMs = (name: string, value: number): number => {\n  if (!Number.isFinite(value) || value < 0) {\n    throw new TypeSafeError(\n      `\\`${name}\\` must be a non-negative number of milliseconds, got ${String(value)}.`,\n    );\n  }\n  return value;\n};\n\nconst assertFraction = (name: string, value: number): number => {\n  if (!Number.isFinite(value) || value < 0 || value > 1) {\n    throw new TypeSafeError(`\\`${name}\\` must be between 0 and 1, got ${String(value)}.`);\n  }\n  return value;\n};\n\nconst assertStatusSet = (name: string, statuses: ReadonlySet<number>): ReadonlySet<number> => {\n  for (const status of statuses) {\n    if (!Number.isInteger(status) || status < 100 || status > 999) {\n      throw new TypeSafeError(`\\`${name}\\` must contain HTTP status codes, got ${String(status)}.`);\n    }\n  }\n  return statuses;\n};\n\n/** Merge and validate retry overrides, copying the status set to isolate later mutations. */\nconst resolveRetryPolicy = (\n  base: RetryPolicy,\n  overrides: Partial<RetryPolicy> | undefined,\n): RetryPolicy => {\n  const o = overrides ?? {};\n  return {\n    maxRetries:\n      o.maxRetries === undefined\n        ? base.maxRetries\n        : assertNonNegativeInteger(\"retry.maxRetries\", o.maxRetries),\n    backoffInitialMs:\n      o.backoffInitialMs === undefined\n        ? base.backoffInitialMs\n        : assertNonNegativeMs(\"retry.backoffInitialMs\", o.backoffInitialMs),\n    backoffMaxMs:\n      o.backoffMaxMs === undefined\n        ? base.backoffMaxMs\n        : assertNonNegativeMs(\"retry.backoffMaxMs\", o.backoffMaxMs),\n    backoffJitter:\n      o.backoffJitter === undefined\n        ? base.backoffJitter\n        : assertFraction(\"retry.backoffJitter\", o.backoffJitter),\n    httpStatuses: new Set(\n      o.httpStatuses === undefined\n        ? base.httpStatuses\n        : assertStatusSet(\"retry.httpStatuses\", o.httpStatuses),\n    ),\n    respectRetryAfter: o.respectRetryAfter ?? base.respectRetryAfter,\n    maxRetryAfterMs:\n      o.maxRetryAfterMs === undefined\n        ? base.maxRetryAfterMs\n        : assertNonNegativeMs(\"retry.maxRetryAfterMs\", o.maxRetryAfterMs),\n    apiConnectionError: o.apiConnectionError ?? base.apiConnectionError,\n    apiTimeoutError: o.apiTimeoutError ?? base.apiTimeoutError,\n  };\n};\n\n/** Whether the policy retries a connection error or timeout. */\nconst isRetryableError = (err: unknown, policy: RetryPolicy): boolean => {\n  if (err instanceof APITimeoutError) return policy.apiTimeoutError;\n  if (err instanceof APIConnectionError) return policy.apiConnectionError;\n  return false;\n};\n\n/** Resolve and validate the log level from configuration or the environment. */\nconst resolveLogLevel = (fromCode: LogLevel | undefined): LogLevel => {\n  if (fromCode !== undefined) return parseLogLevel(fromCode, \"the `logLevel` option\");\n  const fromEnv = readEnv(ENV.logLevel);\n  if (fromEnv !== undefined) return parseLogLevel(fromEnv, ENV.logLevel);\n  return DEFAULT_LOG_LEVEL;\n};\n\nconst stripTrailingSlashes = (url: string): string => url.replace(/\\/+$/, \"\");\n\n/** Last value wins regardless of casing; undefined removes a protected header. */\nconst mergeHeaders = (\n  ...sources: Readonly<Record<string, string | undefined>>[]\n): Record<string, string> => {\n  const entries = new Map<string, [string, string]>();\n  for (const source of sources) {\n    for (const [name, value] of Object.entries(source)) {\n      if (value === undefined) entries.delete(name.toLowerCase());\n      else entries.set(name.toLowerCase(), [name, value]);\n    }\n  }\n  return Object.fromEntries(entries.values());\n};\n\n/** Drain a clone so the original response retains its metadata and a readable, buffered body. */\nconst bufferResponse = async (response: Response, signal: AbortSignal): Promise<void> => {\n  const reader = response.clone().body?.getReader();\n  if (!reader) return;\n  // Node.js 22's fetch cancels an unlocked response body on abort and leaves the rejection\n  // unhandled, so the original body is locked while the clone is read.\n  const original = response.body?.getReader();\n  const cancel = (): void => {\n    // Cancel both tee branches without waiting for an underlying source to acknowledge it.\n    void reader.cancel(signal.reason).catch(() => {});\n    void original?.cancel(signal.reason).catch(() => {});\n  };\n  signal.addEventListener(\"abort\", cancel, { once: true });\n  try {\n    if (signal.aborted) cancel();\n    signal.throwIfAborted();\n    while (!(await reader.read()).done) {\n      signal.throwIfAborted();\n    }\n    signal.throwIfAborted();\n  } finally {\n    signal.removeEventListener(\"abort\", cancel);\n    reader.releaseLock();\n    original?.releaseLock();\n  }\n};\n\n/**\n * Call `start` and settle with its result, or reject with the signal's reason when the signal\n * aborts first. `start` isn't called if the signal has already aborted.\n */\nconst untilAborted = <T>(start: () => Promise<T>, signal: AbortSignal | undefined): Promise<T> => {\n  if (signal === undefined) return start();\n  return new Promise((resolve, reject) => {\n    if (signal.aborted) return reject(signal.reason);\n    const onAbort = (): void => reject(signal.reason);\n    signal.addEventListener(\"abort\", onAbort, { once: true });\n    start().then(\n      (value) => {\n        signal.removeEventListener(\"abort\", onAbort);\n        resolve(value);\n      },\n      (err: unknown) => {\n        signal.removeEventListener(\"abort\", onAbort);\n        reject(err);\n      },\n    );\n  });\n};\n\n// ---------------------------------------------------------------------------\n// Client\n// ---------------------------------------------------------------------------\n\ntype Method = \"GET\" | \"POST\";\n\n/**\n * Per-call transport options with an optional JSON body or `MultipartBody`, or a function called\n * at send time that returns a promise for one.\n */\nexport interface RawRequestOptions extends RequestOptions {\n  body?: unknown;\n}\n\n/** Internal transport interface used by API resources. */\nexport interface Transport {\n  request<T>(method: \"GET\" | \"POST\", path: string, options?: RawRequestOptions): APIPromise<T>;\n  readonly defaultModel: string;\n}\n\ninterface ResolvedRequest {\n  method: Method;\n  path: string;\n  body: unknown;\n  headers: Record<string, string>;\n  signal: AbortSignal | undefined;\n  timeout: number;\n  retry: RetryPolicy;\n}\n\n/** Runtime description cached for the process lifetime. */\nconst RUNTIME = describeRuntime();\n\n/** An `APIPromise` rejected with `err`, for failures found before a request is sent. */\nconst rejectedAPIPromise = <T>(err: unknown): APIPromise<T> => {\n  const response = Promise.reject(err);\n  return new APIPromise<T>(response, () => response as Promise<T>);\n};\n\n/** Client for the TypeSafe AI API. */\nexport class TypeSafeClient {\n  /** API key excluded from serialization and public properties. */\n  readonly #apiKey: string;\n  /** API root with trailing slashes removed. */\n  readonly baseURL: string;\n  /** Model used when a request omits `model`. */\n  readonly defaultModel: string;\n  /** Configured log verbosity. */\n  readonly logLevel: LogLevel;\n  /** The configured logger, filtered to `logLevel`. */\n  readonly logger: Logger;\n  /** Retry settings with constructor overrides applied. */\n  readonly retry: RetryPolicy;\n  /** Timeout per attempt in milliseconds. */\n  readonly timeout: number;\n  /** Additional headers sent with each request. */\n  readonly defaultHeaders: Readonly<Record<string, string>>;\n  /** Request body compression, or `false` when bodies are sent uncompressed. */\n  readonly compression: Compression;\n  /** HTTP fetch implementation. */\n  readonly fetch: Fetch;\n\n  /** The models available to the account. */\n  readonly models: Models;\n\n  #requestCount = 0;\n\n  /**\n   * Create a client for the TypeSafe AI API.\n   *\n   * Explicit options take precedence over environment variables, then SDK defaults.\n   * Empty or whitespace-only environment values are ignored.\n   *\n   * @throws {TypeSafeError} The API key is missing, configuration is invalid, the runtime is\n   *   unsupported, or the runtime lacks the requested compression.\n   */\n  constructor(config: TypeSafeClientConfig = {}) {\n    if (isBrowser() && !config.dangerouslyAllowBrowser) refuseBrowser();\n\n    this.#apiKey = fromCodeOrEnv(config.apiKey, ENV.apiKey) ?? missingApiKey();\n    this.baseURL = stripTrailingSlashes(\n      fromCodeOrEnv(config.baseURL, ENV.baseURL) ?? DEFAULT_BASE_URL,\n    );\n    this.defaultModel = fromCodeOrEnv(config.defaultModel, ENV.defaultModel) ?? DEFAULT_MODEL;\n    this.logLevel = resolveLogLevel(config.logLevel);\n    this.logger = withLevel(config.logger ?? consoleLogger, this.logLevel);\n    this.retry = resolveRetryPolicy(DEFAULT_RETRY_POLICY, config.retry);\n    this.timeout = assertPositiveMs(\"timeout\", config.timeout ?? DEFAULT_TIMEOUT_MS);\n    this.defaultHeaders = { ...config.defaultHeaders };\n    this.compression = resolveCompression(config.compression);\n\n    if (config.fetch === undefined && typeof globalThis.fetch !== \"function\") missingFetch();\n    this.fetch = config.fetch ?? defaultFetch;\n\n    const transport: Transport = {\n      request: (method, path, options) => this.#request(method, path, options),\n      defaultModel: this.defaultModel,\n    };\n    this.models = new Models(transport);\n  }\n\n  /**\n   * Answer named questions about text, structured state, or assets.\n   *\n   * @param request - State, questions, an optional model override, and optional assets.\n   *   Assets in `state`, question content, or `withAssets` text are sent under their references.\n   * @param options - Per-call timeout, retry, headers, and cancellation settings.\n   * @returns Answers typed by question name and criteria, with model and token usage. Every\n   *   failure below rejects the returned promise; the call itself doesn't throw.\n   * @throws {TypeSafeError} State is `null` or omitted, questions are empty, score criteria are not\n   *   a list of at least two entries, choice criteria are not a nonempty map, a noul question has\n   *   neither instructions nor a described outcome, a string holds the reference of an asset not\n   *   attached to the request, a name in `assets` doesn't appear in the request, or a `Blob`\n   *   asset can't be read.\n   * @throws {APIError} The server returns a non-2xx response after retries.\n   * @throws {APIConnectionError} The request cannot connect or times out after retries.\n   * @throws {APIUserAbortError} The caller aborts the request.\n   *\n   * @example\n   * ```ts\n   * const { answers } = await client.systemOne({\n   *   state: \"I was charged twice. Please help.\",\n   *   questions: { billing: noul(\"Is this about billing?\") },\n   * });\n   * console.log(answers.billing.noul);\n   * ```\n   */\n  systemOne<const Q extends Questions>(\n    request: SystemOneRequest<Q>,\n    options: RequestOptions = {},\n  ): APIPromise<SystemOneResult<Q>> {\n    let body: unknown;\n    try {\n      if (request.state == null) throw new TypeSafeError(\"State is required.\");\n      validateQuestions(request.questions);\n      const { assets, ...rest } = request;\n      // Serialized now, so changes to the request after this call don't change what is sent.\n      const { json, assets: sent } = serializeRequest(\n        { ...rest, model: request.model ?? this.defaultModel },\n        assets,\n      );\n      const payload: object = JSON.parse(json);\n      const copied = sent === undefined ? undefined : copyAssetBytes(sent);\n      body = copied === undefined ? payload : () => encodeAssets(payload, copied);\n    } catch (err) {\n      return rejectedAPIPromise(err);\n    }\n\n    return this.#request<SystemOneResult<Q>>(\"POST\", \"/v1/systemone\", {\n      ...options,\n      body,\n    });\n  }\n\n  /** Send a request and parse its response body. */\n  #request<T>(method: Method, path: string, options: RawRequestOptions = {}): APIPromise<T> {\n    let resolved: ResolvedRequest;\n    try {\n      resolved = {\n        method,\n        path,\n        body: options.body,\n        headers: mergeHeaders(this.defaultHeaders, options.headers ?? {}),\n        signal: options.signal,\n        timeout:\n          options.timeout === undefined\n            ? this.timeout\n            : assertPositiveMs(\"timeout\", options.timeout),\n        retry: resolveRetryPolicy(this.retry, options.retry),\n      };\n    } catch (err) {\n      return rejectedAPIPromise(err);\n    }\n    // Numbered so concurrent requests, and the attempts within one, can be told apart in the logs.\n    const tag = `#${++this.#requestCount} ${method} ${path}`;\n\n    return new APIPromise<T>(this.fetchWithRetries(tag, resolved), async (res) => {\n      const parsed = await parseBody(res);\n      this.logger.debug(`${tag} <- body`, parsed);\n      return parsed as T;\n    });\n  }\n\n  /** Retry eligible failures, logging attempt summaries at `info` and headers and bodies at `debug`. */\n  private async fetchWithRetries(tag: string, req: ResolvedRequest): Promise<Response> {\n    const url = `${this.baseURL}${req.path}`;\n    let resolved = req.body;\n    if (typeof resolved === \"function\") {\n      try {\n        resolved = await untilAborted(resolved as () => Promise<unknown>, req.signal);\n      } catch (err) {\n        if (!req.signal?.aborted) throw err;\n        this.logger.info(`${tag} aborted by caller while reading assets`);\n        throw new APIUserAbortError(undefined, { cause: err });\n      }\n    }\n    const multipart = resolved instanceof MultipartBody ? resolved : undefined;\n    const payload = multipart === undefined ? resolved : multipart.payload;\n    const encoded =\n      multipart?.content ?? (payload === undefined ? undefined : JSON.stringify(payload));\n    const encoding =\n      encoded === undefined || byteLength(encoded) < MIN_COMPRESSED_BODY_BYTES\n        ? false\n        : this.compression;\n    // Compressed once and sent as-is on every attempt; the logs show the uncompressed payload.\n    let body: string | Blob | Uint8Array<ArrayBuffer> | undefined = encoded;\n    if (encoded !== undefined && encoding !== false) {\n      try {\n        body = await untilAborted(() => compressBody(encoded), req.signal);\n      } catch (err) {\n        if (!req.signal?.aborted) throw err;\n        this.logger.info(`${tag} aborted by caller while compressing the body`);\n        throw new APIUserAbortError(undefined, { cause: err });\n      }\n    }\n    // User-supplied headers go first so they can't clobber auth, the content type, or the encoding.\n    const headers = mergeHeaders(req.headers, {\n      Authorization: `Bearer ${this.#apiKey}`,\n      Accept: \"application/json\",\n      \"User-Agent\": `typesafe-sdk/${VERSION}`,\n      \"X-TypeSafe-SDK\": `typesafe-sdk/${VERSION}`,\n      \"X-TypeSafe-Runtime\": RUNTIME,\n      \"Content-Type\":\n        multipart?.contentType ?? (body === undefined ? undefined : \"application/json\"),\n      \"Content-Encoding\": encoding === false ? undefined : encoding,\n      \"X-TypeSafe-Retry-Count\": undefined,\n    });\n\n    for (let attempt = 0; ; attempt++) {\n      const retriesLeft = req.retry.maxRetries - attempt;\n      const attemptHeaders =\n        attempt === 0 ? headers : { ...headers, \"X-TypeSafe-Retry-Count\": String(attempt) };\n      this.logger.debug(`${tag} -> ${url}`, {\n        headers: redactHeaders(attemptHeaders),\n        body: payload,\n      });\n\n      const started = Date.now();\n      let res: Response;\n      try {\n        res = await this.attempt(\n          tag,\n          url,\n          { method: req.method, headers: attemptHeaders, body },\n          req,\n        );\n      } catch (err) {\n        if (err instanceof APIUserAbortError || retriesLeft <= 0) throw err;\n        if (!isRetryableError(err, req.retry)) throw err;\n        await this.backOff(tag, attempt, retriesLeft, (err as Error).message, undefined, req);\n        continue;\n      }\n\n      const requestId = requestIdFrom(res.headers);\n      this.logger.info(\n        `${tag} <- ${res.status} in ${Date.now() - started}ms${requestId ? ` (request ${requestId})` : \"\"}`,\n      );\n      if (res.ok) return res;\n\n      const errorBody = await parseBody(res);\n      this.logger.debug(`${tag} <- error body`, errorBody);\n      const error = APIError.fromResponse(res.status, errorBody, res.headers);\n      if (retriesLeft <= 0 || !isRetryableStatus(res.status, req.retry)) throw error;\n      await this.backOff(tag, attempt, retriesLeft, `${res.status}`, res.headers, req);\n    }\n  }\n\n  /**\n   * One HTTP round trip, including body delivery, with a timeout. The caller's signal and our\n   * timer both abort the same controller; we check which fired to choose the error class.\n   */\n  private async attempt(\n    tag: string,\n    url: string,\n    init: {\n      method: Method;\n      headers: Record<string, string>;\n      body: string | Blob | Uint8Array<ArrayBuffer> | undefined;\n    },\n    { signal, timeout }: ResolvedRequest,\n  ): Promise<Response> {\n    const controller = new AbortController();\n    const abortFromCaller = (): void => controller.abort(signal?.reason);\n    if (signal?.aborted) abortFromCaller();\n    signal?.addEventListener(\"abort\", abortFromCaller, { once: true });\n\n    let timedOut = false;\n    const timer = setTimeout(() => {\n      timedOut = true;\n      controller.abort();\n    }, timeout);\n\n    const started = Date.now();\n    const elapsed = (): string => `${Date.now() - started}ms`;\n    try {\n      const response = await this.fetch(url, { ...init, signal: controller.signal });\n      await bufferResponse(response, controller.signal);\n      return response;\n    } catch (err) {\n      if (signal?.aborted) {\n        this.logger.info(`${tag} aborted by caller after ${elapsed()}`);\n        throw new APIUserAbortError(undefined, { cause: err });\n      }\n      if (timedOut) {\n        this.logger.info(`${tag} timed out after ${elapsed()}`);\n        throw new APITimeoutError(timeout, { cause: err });\n      }\n      this.logger.info(`${tag} connection error after ${elapsed()}`, err);\n      throw new APIConnectionError(\n        err instanceof Error ? `Connection error: ${err.message}` : undefined,\n        { cause: err },\n      );\n    } finally {\n      clearTimeout(timer);\n      signal?.removeEventListener(\"abort\", abortFromCaller);\n    }\n  }\n\n  /** Wait before retrying; caller cancellation throws `APIUserAbortError`. */\n  private async backOff(\n    tag: string,\n    attempt: number,\n    retriesLeft: number,\n    reason: string,\n    headers: Headers | undefined,\n    { retry, signal }: ResolvedRequest,\n  ): Promise<void> {\n    const delay = retryDelayMs(attempt, headers, retry);\n    const nth = attempt + 1;\n    const total = attempt + retriesLeft;\n    this.logger.info(`${tag} retrying in ${delay}ms (retry ${nth}/${total}) after ${reason}`);\n    try {\n      await sleep(delay, signal);\n    } catch (err) {\n      this.logger.info(`${tag} aborted by caller while waiting to retry`);\n      throw new APIUserAbortError(undefined, { cause: err });\n    }\n  }\n}\n\nconst parseBody = async (res: Response): Promise<unknown> => {\n  const text = await res.text();\n  if (text.length === 0) return undefined;\n  const contentType = res.headers.get(\"content-type\") ?? \"\";\n  if (contentType.includes(\"application/json\")) {\n    try {\n      return JSON.parse(text);\n    } catch {\n      return text;\n    }\n  }\n  // Be lenient: servers and proxies don't always set content-type.\n  try {\n    return JSON.parse(text);\n  } catch {\n    return text;\n  }\n};\n"],"mappings":"AAEA,MAAa,iBAAiB,YAC5B,QAAQ,IAAA,uBAAqB,KAAK,KAAA;;;;;;AAiBpC,IAAa,aAAb,MAAa,mBAAsB,QAAW;CAC5C;CACA;CACA;CAEA,YACE,iBACA,eACA;EAEA,OAAO,YAAY,QAAQ,KAAA,CAAc,CAAC;EAC1C,KAAK,mBAAmB;EACxB,KAAK,iBAAiB;CACxB;;;;;;CAOA,aAAgC;EAC9B,OAAO,KAAK;CACd;;CAGA,MAAM,eAAyC;EAC7C,MAAM,CAAC,MAAM,YAAY,MAAM,QAAQ,IAAI,CAAC,KAAK,OAAO,GAAG,KAAK,gBAAgB,CAAC;EACjF,OAAO;GAAE;GAAM;GAAU,WAAW,cAAc,SAAS,OAAO;EAAE;CACtE;;CAGA,IAAO,IAAmC;EACxC,OAAO,IAAI,WAAc,KAAK,wBAAwB,KAAK,OAAO,CAAC,CAAC,KAAK,EAAE,CAAC;CAC9E;CAEA,SAAqB;EACnB,KAAK,YAAY,KAAK,iBAAiB,KAAK,KAAK,cAAc;EAC/D,OAAO,KAAK;CACd;CAGA,KACE,aACA,YAC8B;EAC9B,OAAO,KAAK,OAAO,CAAC,CAAC,KAAK,aAAa,UAAU;CACnD;CAEA,MACE,YACsB;EACtB,OAAO,KAAK,OAAO,CAAC,CAAC,MAAM,UAAU;CACvC;CAEA,QAAiB,WAA6C;E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