export declare const CANONICAL_CUSTOM_FETCH = "/**\n * Configurable fetch wrapper for Orval-generated clients.\n *\n * AUTO-GENERATED by `@xemahq/api-client-generator` \u2014 DO NOT EDIT. Every client\n * in the fleet ships this file byte-for-byte; a hand edit is erased by the next\n * regeneration and, until then, makes this one client speak to the platform\n * differently from all of its siblings.\n *\n * Canonical source: `CANONICAL_CUSTOM_FETCH` in\n * `packages/sdks/api-client-generator/src/lib/custom-fetch-template.ts`\n * (repository `xema-kernel-sdk`). Change it there.\n *\n * Regenerate, from the root of THIS repository:\n * pnpm --filter run openapi\n * pnpm --filter run client:generate\n * A mirror of this client under `xema-host-web` is not regenerated there: it\n * is written by the frontend bridge, `tooling/frontend-bridge` in the\n * xema-monorepo aggregator.\n *\n * Consumers must call `configureClient()` before using any endpoint function.\n * The baseUrl is prepended to the relative paths generated by Orval.\n *\n * By default this transport issues exactly ONE request and adds no delay of its\n * own, so a slow call is a slow server. Retrying is opt-in, and opting in\n * requires supplying an observer \u2014 see `maxRetries` / `onRetry` below.\n */\n\n/** What {@link ClientConfig.onRetry} is told before each re-attempt. */\nexport interface RetryNotice {\n /** 1-based index of the re-attempt about to be made. */\n attempt: number;\n /** The configured budget this re-attempt is spending from. */\n maxRetries: number;\n /** The response status that made the previous attempt retryable. */\n status: number;\n /** Delay before the re-attempt, in ms \u2014 from `Retry-After` when the server sent one. */\n waitMs: number;\n /** Whether {@link waitMs} came from the server's `Retry-After` header. */\n retryAfterHonoured: boolean;\n /** Absolute URL being re-requested. */\n url: string;\n /** HTTP method being re-requested. */\n method: string;\n}\n\n/**\n * Per-request context handed to the callbacks this transport awaits BEFORE it\n * sends the request.\n *\n * `signal` is the request's own `AbortSignal` (`options.signal`). It is the\n * CALLER's cancellation: a callback may use it to stop work that is private to\n * this request, but a callback serving several requests from one shared,\n * single-flight acquisition (a token refresh) must NOT abort that shared work\n * because one caller stopped \u2014 every other caller waiting on it would fail.\n * The transport stops WAITING on its own regardless, so a callback that\n * ignores the signal still cannot hold an aborted request.\n */\nexport interface ClientCallbackOptions {\n signal?: AbortSignal;\n}\n\n/** What {@link ClientConfig.onUnauthorized} is told about the 401 it answers. */\nexport interface UnauthorizedContext {\n /**\n * The token `getAuthToken` returned for the attempt the server rejected.\n * `undefined` when no `getAuthToken` produced the Authorization header\n * (a header from `getHeaders` or no credential at all): there is then no\n * client-held token to drop.\n */\n readonly rejectedToken: string | undefined;\n}\n\nexport interface ClientConfig {\n /**\n * Static base URL (e.g. 'http://localhost:3140') \u2014 no trailing slash.\n * Mutually exclusive with `baseUrlResolver`; exactly one MUST be set.\n */\n baseUrl?: string;\n /**\n * Per-request base-URL resolver. When set, the peer URL is resolved from\n * the service registry on EVERY request (boot-order-safe). Wired by\n * `configureOrvalClientResolved` from `@xemahq/platform-common`.\n */\n baseUrlResolver?: (\n options?: ClientCallbackOptions,\n ) => string | Promise;\n /**\n * Optional async callback to get an auth token. Auto-sets Authorization\n * header on every request. Receives the request's signal \u2014 see\n * {@link ClientCallbackOptions} for what it may and may not abort.\n */\n getAuthToken?: (options?: ClientCallbackOptions) => Promise;\n /** Optional callback returning headers to inject on every request. Per-call headers take precedence. */\n getHeaders?: () => Record | Promise>;\n /**\n * Optional resolver for the CORRELATION ID of the request being made \u2014 the\n * handle that ties one causal chain together across every service hop.\n *\n * WHY IT IS A CALLBACK AND NOT A VALUE. `ClientConfig` is process-global\n * (`configureClient` is called once at wiring time), and a correlation id is\n * per-request. This is invoked INSIDE the request, so a server can point it\n * at whatever carries its ambient request context and get the CURRENT id\n * rather than the one that happened to be live at boot.\n *\n * WHY THE TRANSPORT DOES NOT MINT ONE. Returning `undefined` sends no header,\n * and the receiving service's `RequestContextMiddleware` mints its own \u2014 a\n * new trace, which is honest. A transport that minted per call would produce\n * a FRESH id on every hop while looking like propagation, which is strictly\n * worse than none: every row would carry a correlation id and no two rows\n * that belong together would share one. That is the exact defect this exists\n * to fix, so the transport must not reproduce it one layer down.\n *\n * A caller-supplied `X-Correlation-Id` header always wins, and so does one\n * from `getHeaders`.\n */\n getCorrelationId?: () =>\n | string\n | undefined\n | Promise;\n /**\n * Optional callback invoked on a 401 before ONE re-attempt. Supplying it is\n * what opts this client into that re-attempt; without it a 401 comes back to\n * the caller as a `ClientError` like any other 4xx.\n *\n * It is told WHAT was rejected (see {@link UnauthorizedContext}), so a\n * callback that drops a cached credential can drop exactly that one and leave\n * a newer one, minted by a concurrent request, alone.\n */\n onUnauthorized?: (context: UnauthorizedContext) => Promise;\n /**\n * Re-attempts for a retryable status. **Defaults to 0 \u2014 no retry.**\n *\n * Setting it above 0 REQUIRES `onRetry`; `configureClient` throws otherwise.\n * See the block above `customFetch` for why the budget is opt-in and why an\n * observer is mandatory rather than advisory.\n */\n maxRetries?: number;\n /**\n * Called immediately before every re-attempt, with the reason and the delay.\n *\n * Mandatory whenever `maxRetries` is above 0. It is the difference between a\n * retry and a hidden degradation path: without it a caller cannot tell a slow\n * server from this transport sleeping between attempts.\n */\n onRetry?: (notice: RetryNotice) => void;\n}\n\n/**\n * Cross-package identity for `ClientError`.\n *\n * \u2500\u2500 THE OUTAGE THIS IS FOR \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * PRODUCTION, 2026-09-22. A session launch aborted on\n * `HTTP 503 from http://skill-registry-api\u2026/skills`. A 503 is the archetypal\n * TRANSIENT \u2014 agent-session's launch taxonomy already listed it as retryable \u2014\n * but it was classified PERMANENT and the launch was abandoned.\n *\n * The cause was this file. Every generated client package gets its OWN copy of\n * `ClientError`, so there are as many classes as there are clients (81 at the\n * time of writing), all byte-identical and all DIFFERENT OBJECTS. A consumer\n * naturally writes `err instanceof ClientError` against the one client it\n * imported \u2014 which reads as obviously correct and is silently package-local. An\n * error from any OTHER client fails it, falls past every status check, and lands\n * on whatever the default is.\n *\n * That was not the first time: biome-host had already switched to structural\n * detection for the same reason, and canopy imports TWO `ClientError` classes\n * and tests both. Three more call sites elsewhere carry the same shape.\n *\n * \u2500\u2500 WHY A BRAND AND NOT A SHARED PACKAGE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * The obvious fix is one shared runtime class every client imports. It was\n * rejected on measurement: the 81 generated clients are DEPENDENCY-FREE by\n * design (exactly one has any dependency at all), and a shared class would have\n * to be a PEER dependency to be safe \u2014 a normal dependency can be installed\n * twice under version skew, which reinstates this identical bug in a form that\n * is HARDER to see, because the classes then look like they ought to match.\n *\n * `Symbol.for` is a process-wide registry keyed by STRING, so every copy of\n * this template resolves the same symbol without importing anything. The brand\n * costs no dependency, cannot skew, and needs no new package.\n *\n * `Symbol.hasInstance` then makes plain `instanceof` mean the right thing\n * fleet-wide: an error from ANY generated client satisfies `instanceof\n * ClientError` in ANY other. A helper would have made the safe pattern\n * available; this makes the dangerous pattern impossible.\n *\n * Narrow on purpose \u2014 the brand is set only by this constructor, so an unrelated\n * error carrying a `status` is not admitted.\n */\nconst CLIENT_ERROR_BRAND: unique symbol = Symbol.for(\n 'xema.generatedClientError',\n) as never;\n\nexport class ClientError extends Error {\n constructor(\n public readonly status: number,\n public readonly url: string,\n public readonly body: unknown,\n ) {\n super(`HTTP ${status} from ${url}`);\n this.name = 'ClientError';\n // Non-enumerable: it must not appear in JSON, logs or snapshots \u2014 it is an\n // identity marker, not payload.\n Object.defineProperty(this, CLIENT_ERROR_BRAND, { value: true });\n }\n\n // `override` because the member shadows `Function.prototype[Symbol.hasInstance]`,\n // which a class constructor inherits: TypeScript 5.9+ reports TS4114 without it\n // under `noImplicitOverride`. Measured to compile on 5.5.4, 5.9.3, 6.0.3 and\n // 7.0.2 with the flag on AND off \u2014 pinned by\n // tests/custom-fetch-compiles-standalone.test.cjs.\n static override [Symbol.hasInstance](candidate: unknown): boolean {\n return (\n typeof candidate === 'object' &&\n candidate !== null &&\n CLIENT_ERROR_BRAND in candidate\n );\n }\n}\n\nlet clientConfig: ClientConfig | null = null;\n\n/**\n * THE MOUNT SCOPE \u2014 how one process can host several services without their\n * clients speaking for each other.\n *\n * `clientConfig` below is a MODULE global, and in a single-service process\n * that is correct: one writer, one configuration. Compose two services into one\n * process and both call `configureClient` on THIS SAME module instance, so the\n * second overwrites the first and every outbound call from BOTH services leaves\n * as whichever wired itself last \u2014 wrong base URL, and, because\n * `getAuthToken` is part of the config, WRONG BEARER. That is one tenant's\n * service calling a peer holding another tenant's credential, and it is silent.\n *\n * A composing host installs a hook under this well-known symbol that answers\n * one question: WHICH MOUNT is currently on the stack. Nothing else crosses.\n * `configureClient` then files the config under that mount, and\n * `getClientConfig` reads it back out under the same key.\n *\n * Three properties make this safe rather than clever:\n *\n * - The CONFIG is still built by the mount's own wiring, exactly as today.\n * The hook never supplies one. So a mount's base URL and bearer are\n * resolved FROM THE MOUNT; the scope only decides which drawer they go in.\n * A hook that RETURNED configuration would be a mount taking its identity\n * from ambient storage a neighbour can write \u2014 the inversion to refuse.\n * - The key is an OPAQUE OBJECT and the store is a `WeakMap`, so a mount's\n * configuration becomes unreachable when the host drops the mount, and no\n * client can enumerate the mounts or reach a sibling's entry.\n * - With NO hook installed \u2014 every process in the fleet today \u2014 both\n * functions behave exactly as they did before this existed.\n *\n * `Symbol.for` is the seam because a generated client must keep its\n * dependency surface at zero and a host cannot enumerate the clients a process\n * happens to load. It is the same instrument, and the same reasoning, as the\n * `ClientError` brand above.\n */\nconst XEMA_CLIENT_CONFIG_SCOPE = Symbol.for('xema.client-config-scope');\n\ntype MountScopeHook = () => object | undefined;\n\nfunction mountScopeHook(): MountScopeHook | undefined {\n const hook = (globalThis as Record)[\n XEMA_CLIENT_CONFIG_SCOPE\n ];\n return typeof hook === 'function' ? (hook as MountScopeHook) : undefined;\n}\n\nfunction currentMountKey(): object | undefined {\n return mountScopeHook()?.();\n}\n\nconst perMountConfig = new WeakMap();\n\n\nexport function configureClient(config: ClientConfig): void {\n // Fail at WIRING time, not on the request that happens to be retried. A\n // client configured to retry without an observer is the exact defect this\n // transport was rebuilt to remove, so it must not be constructible.\n if ((config.maxRetries ?? 0) > 0 && !config.onRetry) {\n throw new Error(\n 'configureClient: maxRetries above 0 requires onRetry. A retry nothing ' +\n 'reports is indistinguishable from a slow server, which is how two ' +\n 'silent re-attempts were read as a 3,312ms call.',\n );\n }\n const hook = mountScopeHook();\n if (hook !== undefined) {\n const mount = hook();\n if (mount === undefined) {\n // A composing host is installed and no member is on the stack, so this\n // configuration belongs to NO member. Filing it in the module global\n // would hand it to every member that did not configure this client \u2014\n // someone else's base URL and bearer, silently.\n throw new Error(\n 'configureClient: called in a composed process outside every member. ' +\n 'Configure the client inside the member that uses it (its providers ' +\n 'and factories already run there).',\n );\n }\n perMountConfig.set(mount, config);\n return;\n }\n clientConfig = config;\n}\n\nexport function getClientConfig(): ClientConfig {\n const mount = currentMountKey();\n if (mount !== undefined) {\n const scoped = perMountConfig.get(mount);\n if (scoped) {\n return scoped;\n }\n // A member that never configured THIS client behaves exactly like a\n // dedicated service that did not either: it is refused. It used to fall\n // through to the module global, which in a composed process can only have\n // been written by some OTHER code \u2014 so the member called peers under a\n // base URL and bearer that were never its own.\n throw new Error(\n 'Client not configured for this member. Call configureClient({ baseUrl }) ' +\n 'inside the member before using endpoint functions.',\n );\n }\n if (!clientConfig) {\n throw new Error(\n 'Client not configured. Call configureClient({ baseUrl }) before using endpoint functions.',\n );\n }\n return clientConfig;\n}\n\n/*\n * RETRYING IS OPT-IN, OBSERVED, AND NARROW. Do not widen any of the three.\n *\n * This transport used to retry up to `maxRetries` (defaulting to THREE) over\n * 429/502/503/504 AND over any thrown network error, backing off from 1000ms,\n * with no log line anywhere. Three properties were wrong:\n *\n * 1. The DEFAULT was on. ~99% of the fleet's client configurations never\n * mention `maxRetries`, so two re-attempts could add ~3s to any call with\n * nothing to distinguish that from a slow peer. Every caller that DID set\n * it set it LOWER \u2014 canopy's control plane to 1, \"so a hard outage\n * surfaces inside the turn's latency budget rather than after three\n * backoffs\"; two llm-registry callers to 1; a test to 0. Nobody ever\n * raised it. A default three separate call sites work around is not a\n * default, and `configureOrvalClientResolved` cannot express the field at\n * all, so most callers could not have opted out if they had wanted to.\n * 2. It retried AMBIGUOUS failures. 502 and 504 mean a gateway did not get a\n * timely answer from upstream \u2014 the upstream may well have APPLIED the\n * request. So did a thrown network error mid-flight. Re-sending a POST in\n * either case is a duplicate write, and no amount of logging makes that\n * safe. Only 429 and 503 state positively that the request was NOT\n * processed, so only those are retried; everything else surfaces at once.\n * 3. Nothing reported it. Now `onRetry` is mandatory whenever the budget is\n * above 0, enforced in `configureClient`.\n *\n * Also note `baseUrlResolver` is awaited ONCE, above the loop: a re-attempt\n * returns to the same resolved instance. In a registry-resolved fleet the cure\n * for an unhealthy peer is re-resolution, which lives above this file \u2014 which\n * is a further reason not to lean on retrying here.\n *\n * Retry policy a caller genuinely wants belongs in `@xemahq/managed-fetch`,\n * which has backoff, a circuit breaker, a token bucket and health reporting,\n * and reports what it did.\n *\n * Enforced fleet-wide by `check-client-transport-envelope`, which compares\n * every client's transport to this template.\n */\n\n/** The only statuses that state the request was NOT processed. See above. */\nconst RETRYABLE_STATUSES = [429, 503];\n\n/**\n * The platform's correlation header, spelled once.\n *\n * Value-identical to what `RequestContextMiddleware` reads in\n * `@xemahq/platform-common`. It is a literal here rather than an import\n * because this file has ZERO imports on purpose: it ships byte-identical into\n * browser-target clients as well as server-target ones, and a dependency on a\n * NestJS-peer package would follow it into every one of them.\n */\nconst CORRELATION_ID_HEADER = 'X-Correlation-Id';\n\n/** Backoff floor, doubling per attempt up to {@link MAX_BACKOFF_MS}. */\nconst BASE_BACKOFF_MS = 1000;\n\n/** Ceiling on a single backoff, however many attempts have elapsed. */\nconst MAX_BACKOFF_MS = 30_000;\n\n/*\n * CALLER CANCELLATION REACHES EVERY WAIT BEFORE THE REQUEST IS SENT.\n *\n * `fetch` always honoured `options.signal`, but everything this transport\n * awaits BEFORE `fetch` \u2014 base-URL resolution, the header callbacks, the auth\n * token \u2014 did not, so a caller that aborted while a token was being minted sat\n * out the mint and then, at best, had its request refused. The only way to\n * cancel that wait was a process-wide interceptor aborting every outbound\n * request, which also aborts a SHARED single-flight token refresh and so fails\n * every other caller waiting on it.\n *\n * So each pre-send wait is RACED against the signal: the caller stops waiting\n * at once, and the work it was waiting on carries on for anybody else. The\n * rejection is the signal's own reason \u2014 exactly what `fetch` rejects with \u2014\n * so a caller sees ONE abort shape whenever it aborts. An aborted request is\n * never retried. Without a signal nothing here changes.\n */\nfunction abortedReason(signal: AbortSignal): unknown {\n // `abort()` with no argument sets a DOMException reason, so this is only\n // ever `undefined` for a hand-built signal; say so rather than throw it.\n return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw abortedReason(signal);\n }\n}\n\nfunction raceAbort(\n pending: V | Promise,\n signal: AbortSignal | undefined,\n): Promise {\n const promise = Promise.resolve(pending);\n if (!signal) {\n return promise;\n }\n if (signal.aborted) {\n promise.catch(() => undefined);\n return Promise.reject(abortedReason(signal));\n }\n return new Promise((resolve, reject) => {\n const onAbort = (): void => {\n // The pending work may be shared; it carries on, and its eventual\n // rejection must not surface as an unhandled one on this side.\n promise.catch(() => undefined);\n reject(abortedReason(signal));\n };\n signal.addEventListener('abort', onAbort, { once: true });\n promise.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\ninterface BuiltHeaders {\n readonly headers: Headers;\n /** The token `getAuthToken` produced for these headers, if it did. */\n readonly authToken: string | undefined;\n}\n\nasync function buildHeaders(\n config: ClientConfig,\n callerHeaders: RequestInit['headers'],\n signal: AbortSignal | undefined,\n): Promise {\n const headers = new Headers(callerHeaders);\n\n // Global headers from config (caller-provided headers take precedence)\n if (config.getHeaders) {\n const globalHeaders = await raceAbort(config.getHeaders(), signal);\n for (const [key, value] of Object.entries(globalHeaders)) {\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n }\n }\n\n // Correlation id (caller and global headers still take precedence).\n //\n // Without this, every server-to-server hop through a generated client started\n // a NEW trace: the id is read-or-minted per hop by the receiving service's\n // RequestContextMiddleware, and nothing carried it outbound \u2014 so an audit\n // journal could record a whole causal chain and offer no way to join it back\n // together.\n //\n // Absent resolver, or a resolver that answers `undefined`: NO header. The\n // receiver mints and a new trace begins, which is the truthful outcome when\n // there is nothing to continue.\n if (config.getCorrelationId && !headers.has(CORRELATION_ID_HEADER)) {\n const correlationId = await raceAbort(config.getCorrelationId(), signal);\n if (correlationId) {\n headers.set(CORRELATION_ID_HEADER, correlationId);\n }\n }\n\n // Auth token (caller or global headers take precedence)\n let authToken: string | undefined;\n if (config.getAuthToken && !headers.has('Authorization')) {\n authToken = await raceAbort(\n config.getAuthToken(signal ? { signal } : undefined),\n signal,\n );\n headers.set('Authorization', `Bearer ${authToken}`);\n }\n\n return { headers, authToken };\n}\n\n/*\n * THE TRANSPORT RETURNS THE BODY UNCHANGED. Do not reintroduce an unwrap here.\n *\n * Xema services wrap every 2xx payload in a { data: T } envelope via the global\n * ResponseEnvelopeInterceptor (platform-common), and the generator emits types\n * that describe THAT ENVELOPE \u2014 every endpoint returns Promise\n * or Promise, never a bare inner T. Consumers read the data\n * property themselves.\n *\n * This template used to peel data, justified by a comment claiming generated\n * types describe the inner T. That stopped being true when the generator moved\n * to envelope-typed returns, and the comment outlived the fact \u2014 so the peel\n * then contradicted every type in every package it seeded. Four clients shipped\n * that way (resource-governance x3, workload-runtime-api): declared\n * *DataEnvelope, returned the already-peeled inner object, so .data read\n * undefined at runtime on every non-paginated endpoint. Paginated calls hid it,\n * because the old peel deliberately preserved an envelope carrying pagination.\n *\n * Four MORE shipped it in repositories the gate could not see \u2014 license-api and\n * license-internal-api in xema-operator, plus their host-web mirrors \u2014 because\n * the gate ran in xema-base only. That is why it now runs in every repository\n * that ships a client, and why this file is generator-owned rather than seeded.\n */\n\nexport const customFetch = async (\n url: string,\n options: RequestInit,\n): Promise => {\n const config = getClientConfig();\n const signal = options.signal ?? undefined;\n throwIfAborted(signal);\n const base = config.baseUrlResolver\n ? await raceAbort(\n config.baseUrlResolver(signal ? { signal } : undefined),\n signal,\n )\n : config.baseUrl;\n if (base === undefined) {\n throw new Error(\n 'Client not configured: set baseUrl or baseUrlResolver via configureClient().',\n );\n }\n const fullUrl = `${base}${url}`;\n const maxRetries = config.maxRetries ?? 0;\n\n // A caller that supplied its own Authorization header owns that credential.\n // `buildHeaders` lets it win, so refreshing the CLIENT-WIDE token and\n // re-sending would replay the identical failing request with the identical\n // credential: one wasted round trip, plus a global refresh nobody asked for.\n const callerSuppliedAuth = new Headers(options.headers).has('Authorization');\n\n const built = await buildHeaders(config, options.headers, signal);\n const requestInit: RequestInit = { ...options, headers: built.headers };\n\n let delay = BASE_BACKOFF_MS;\n\n for (let attempt = 0; ; attempt++) {\n const response = await fetch(fullUrl, requestInit);\n\n if (\n response.status === 401 &&\n config.onUnauthorized &&\n !callerSuppliedAuth &&\n attempt === 0\n ) {\n await raceAbort(\n config.onUnauthorized({ rejectedToken: built.authToken }),\n signal,\n );\n const refreshed = await buildHeaders(config, options.headers, signal);\n const retryResponse = await fetch(fullUrl, {\n ...options,\n headers: refreshed.headers,\n });\n const retryBody = await parseBody(retryResponse);\n if (retryResponse.status >= 400) {\n throw new ClientError(retryResponse.status, fullUrl, retryBody);\n }\n return retryBody as T;\n }\n\n if (\n !RETRYABLE_STATUSES.includes(response.status) ||\n attempt >= maxRetries\n ) {\n const body = await parseBody(response);\n if (response.status >= 400) {\n throw new ClientError(response.status, fullUrl, body);\n }\n return body as T;\n }\n\n const retryAfter = parseRetryAfter(response.headers.get('Retry-After'));\n const waitMs = retryAfter ?? addJitter(delay);\n // Non-null: `configureClient` refuses a budget above 0 without an observer,\n // and this line is unreachable unless `maxRetries` is above 0.\n (config.onRetry as (notice: RetryNotice) => void)({\n attempt: attempt + 1,\n maxRetries,\n status: response.status,\n waitMs,\n retryAfterHonoured: retryAfter !== undefined,\n url: fullUrl,\n method: options.method ?? 'GET',\n });\n await sleep(waitMs, signal);\n delay = Math.min(delay * 2, MAX_BACKOFF_MS);\n }\n};\n\n/**\n * Does this media type carry JSON?\n *\n * \u2500\u2500 THE OUTAGE THIS FIXES \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * This used to be `contentType?.includes('application/json')`, and EVERY error\n * this fleet returns failed that test. The platform's `GlobalExceptionFilter`\n * emits RFC 9457 problem documents and sets the media type explicitly \u2014\n * `.type(PROBLEM_DETAILS_CONTENT_TYPE)` before `.json()`, so it cannot be\n * overridden \u2014 and that constant is `application/problem+json`, which does NOT\n * contain the substring `application/json`: after `application/` comes\n * `problem+json`.\n *\n * So every non-2xx body fell through to `response.text()` and reached the\n * caller as an UNPARSED STRING. `ClientError.body` is typed `unknown`, so\n * nothing complained; every consumer that reads a machine-readable code off an\n * error \u2014 `error.body.code`, `error.body.details.code` \u2014 silently read\n * `undefined` instead, for every error, in every service.\n *\n * Measured in production on 2026-09-15: skill-registry-api's\n * `resolveOrNull()` absorbs `RELEASE_CHANNEL_NOT_FOUND` into `null` by exactly\n * that read. With the code unreadable the absorb never fired, a routine \"no\n * pointer on this channel\" 404 became a 500 on `GET /skills` and\n * `GET /describe-objects`, and agent-session-api's `apply_control_bundle` step\n * aborted EVERY session launch in the organisation \u2014 7,871 failed resolutions\n * an hour. A fix written for that exact page months earlier was present in the\n * running image and could not help, because the classifier it repaired was\n * being handed a string.\n *\n * \u2500\u2500 WHY THE STRUCTURED SUFFIX, NOT A SECOND SUBSTRING \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * Adding `|| includes('application/problem+json')` would fix this one media\n * type and leave the next one \u2014 `application/vnd.api+json`, and anything else\n * a service legitimately emits. RFC 6839 defines `+json` as the structured\n * syntax suffix meaning \"this is JSON\"; that is the actual rule, so it is the\n * rule implemented. Parameters are stripped first, because\n * `application/problem+json; charset=utf-8` is the same media type.\n */\nfunction isJsonMediaType(contentType: string | null): boolean {\n if (contentType === null) {\n return false;\n }\n const essence = contentType.split(';')[0]?.trim().toLowerCase() ?? '';\n return essence === 'application/json' || essence.endsWith('+json');\n}\n\n/**\n * Does this media type carry TEXT a caller reads as a string?\n *\n * The response body is decoded by its declared media type, in three classes,\n * and each class matches what the generated function's return type says for\n * the schema such a route declares:\n *\n * - JSON (`application/json` or an RFC 6839 `+json` suffix) \u2192 parsed;\n * - TEXT (`text/*` \u2014 including `text/event-stream` \u2014 `application/javascript`,\n * `application/ecmascript`, `application/xml` or an RFC 7303 `+xml`\n * suffix) \u2192 a string, which is what a `{ type: string }` schema generates;\n * - anything else \u2014 `application/octet-stream`, `application/gzip`,\n * `application/pdf`, an Office document type, any `format: binary` body \u2014\n * \u2192 a `Blob`, which is what a `format: binary` schema generates.\n *\n * Reading every non-JSON body as text, as this transport did until 2026-10-04,\n * handed a caller typed `Blob` a string: `response.text()` decodes the bytes\n * as UTF-8, so a PDF or a gzip tarball arrived corrupted under a type that\n * promised the bytes.\n *\n * A response with NO content type is read as text, so an empty body stays the\n * empty string it always was.\n */\nfunction isTextMediaType(contentType: string): boolean {\n const essence = contentType.split(';')[0]?.trim().toLowerCase() ?? '';\n return (\n essence.startsWith('text/') ||\n essence === 'application/javascript' ||\n essence === 'application/ecmascript' ||\n essence === 'application/xml' ||\n essence.endsWith('+xml')\n );\n}\n\nasync function parseBody(response: Response): Promise {\n // 204 FIRST, and deliberately \u2014 this ORDER is carried from `develop`, which\n // fixed the same defect independently and got this half right where `main`\n // did not. A 204 carries no body, so `response.json()` on one throws\n // SyntaxError; and a 204 whose headers STILL declare a JSON content type is\n // ordinary, because the framework sets the header before the handler returns\n // nothing. With the JSON branch first, a documented `undefined` becomes a\n // thrown parse error. Pinned by a case in `transport-problem-json.test.cjs`.\n if (response.status === 204) {\n return undefined;\n }\n const contentType = response.headers.get('content-type');\n if (isJsonMediaType(contentType)) {\n return response.json();\n }\n if (contentType === null || isTextMediaType(contentType)) {\n return response.text();\n }\n return response.blob();\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (!value) return undefined;\n const seconds = Number(value);\n if (!isNaN(seconds) && seconds >= 0) return seconds * 1000;\n const date = new Date(value);\n if (!isNaN(date.getTime())) return Math.max(0, date.getTime() - Date.now());\n return undefined;\n}\n\nfunction addJitter(delay: number): number {\n return delay + (Math.random() * 2 - 1) * delay * 0.25;\n}\n\n/** A retry backoff; the caller's signal ends it at once and is never retried. */\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise {\n if (!signal) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n if (signal.aborted) {\n return Promise.reject(abortedReason(signal));\n }\n return new Promise((resolve, reject) => {\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(abortedReason(signal));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport default customFetch;\n"; //# sourceMappingURL=custom-fetch-template.d.ts.map