Commit 61982a61c5b for nodejs

commit 61982a61c5b0e954db2d037ef65b60b642a51683
Author: Node.js GitHub Bot <github-bot@iojs.org>
Date:   Sun Dec 6 12:23:17 2026 -0500

    deps: update undici to 8.14.1

    PR-URL: https://github.com/nodejs/node/pull/68014
    Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
    Reviewed-By: Colin Ihrig <cjihrig@gmail.com>

diff --git a/deps/undici/src/README.md b/deps/undici/src/README.md
index e5af5f7ec8b..8d0be890e21 100644
--- a/deps/undici/src/README.md
+++ b/deps/undici/src/README.md
@@ -795,7 +795,6 @@ and `undici.Agent`) which will enable the family autoselection algorithm when es
 * [__Carlos Fuentes__](https://github.com/metcoder95), <https://www.npmjs.com/~metcoder95>
 * [__Ethan Arrowood__](https://github.com/Ethan-Arrowood), <https://www.npmjs.com/~ethan_arrowood>
 * [__Matteo Collina__](https://github.com/mcollina), <https://www.npmjs.com/~matteo.collina>
-* [__Matthew Aitken__](https://github.com/KhafraDev), <https://www.npmjs.com/~khaf>
 * [__Mert Can Altin__](https://github.com/mertcanaltin), <https://www.npmjs.com/~mertcanaltin>
 * [__Robert Nagy__](https://github.com/ronag), <https://www.npmjs.com/~ronag>
 * [__Trivikram Kamat__](https://github.com/trivikr), <https://www.npmjs.com/~trivikr>
@@ -804,13 +803,13 @@ and `undici.Agent`) which will enable the family autoselection algorithm when es
 ## Past Collaborators
 * [__Szymon Marczak__](https://github.com/szmarczak), <https://www.npmjs.com/~szmarczak>
 * [__Tomas Della Vedova__](https://github.com/delvedor), <https://www.npmjs.com/~delvedor>
+* [__Matthew Aitken__](https://github.com/KhafraDev), <https://www.npmjs.com/~khaf>

 ### Releasers

 * [__Ethan Arrowood__](https://github.com/ethan-arrowood), <https://www.npmjs.com/~ethan_arrowood>
 * [__Matteo Collina__](https://github.com/mcollina), <https://www.npmjs.com/~matteo.collina>
 * [__Robert Nagy__](https://github.com/ronag), <https://www.npmjs.com/~ronag>
-* [__Matthew Aitken__](https://github.com/KhafraDev), <https://www.npmjs.com/~khaf>

 ## Long Term Support

diff --git a/deps/undici/src/docs/docs/api/Client.md b/deps/undici/src/docs/docs/api/Client.md
index 36f6a4f2465..0b0ce3c59fd 100644
--- a/deps/undici/src/docs/docs/api/Client.md
+++ b/deps/undici/src/docs/docs/api/Client.md
@@ -73,8 +73,10 @@ added: v1.0.0
   * `maxResponseSize` {number|null} The maximum length of a response body, in
     bytes. Set to `-1` to disable it. **Default:** `-1`.
   * `maxRequestsPerClient` {number|null} The maximum number of requests to send
-    over a single connection before the socket is reset. Use `0` to disable this
-    limit. **Default:** `null`.
+    over a single connection. For HTTP/2, once this limit is reached, the client
+    lets existing streams finish and closes the session before sending queued
+    requests on a new connection. Use `0` to disable this limit. **Default:**
+    `null`.
   * `localAddress` {string|null} The local IP address the socket should connect
     from. **Default:** `null`.
   * `pipelining` {number|null} The number of concurrent requests sent over the
@@ -113,7 +115,7 @@ added: v1.0.0
     higher priority through ALPN negotiation. **Default:** `true`.
   * `useH2c` {boolean} _Deprecated: use h2Options.useH2c instead_ Enforces h2c (HTTP/2 cleartext) for non-HTTPS
   connections. **Default:** `false`.
-  * `maxConcurrentStreams` {number} _Deprecated: use h2Options.useH2c instead_ The maximum number of concurrent HTTP/2
+  * `maxConcurrentStreams` {number} _Deprecated: use h2Options.maxConcurrentStreams instead_ The maximum number of concurrent HTTP/2
     streams for a single session. Once h2 is negotiated this — not `pipelining`,
     which is HTTP/1.1 only — is the ceiling used to dispatch in-flight requests.
     The server's `SETTINGS_MAX_CONCURRENT_STREAMS` can lower this limit, but
diff --git a/deps/undici/src/docs/docs/api/Dispatcher.md b/deps/undici/src/docs/docs/api/Dispatcher.md
index b278f328ce1..c8689d4f36d 100644
--- a/deps/undici/src/docs/docs/api/Dispatcher.md
+++ b/deps/undici/src/docs/docs/api/Dispatcher.md
@@ -243,6 +243,12 @@ added: v4.0.0
   * `expectContinue` {boolean} For HTTP/2, appends the `expect: 100-continue`
     header and halts the request body until a `100 Continue` is received from the
     remote server. **Default:** `false`.
+  * `servername` {string} The TLS server name (SNI) to use for this request on
+    `https:` origins. **Default:** the hostname of the `host` header, if any
+    (IP addresses are not used). A client reconnects when the server name of the
+    next queued request differs from the one of its current connection, and
+    waits for any running requests to finish first. Set this to share one
+    connection across requests with different `host` headers.
 * `handler` {Object} A set of callbacks invoked over the request lifecycle.
   * `onRequestStart` {Function} Invoked before the request is dispatched on the
     socket. May be invoked multiple times when the request is retried.
diff --git a/deps/undici/src/docs/docs/api/EnvHttpProxyAgent.md b/deps/undici/src/docs/docs/api/EnvHttpProxyAgent.md
index f14b8760964..e3e251f3db2 100644
--- a/deps/undici/src/docs/docs/api/EnvHttpProxyAgent.md
+++ b/deps/undici/src/docs/docs/api/EnvHttpProxyAgent.md
@@ -66,6 +66,15 @@ Creates a new `EnvHttpProxyAgent`. Any options other than `httpProxy`,
 not affect any request until it is registered as a dispatcher, either globally
 with `setGlobalDispatcher()` or per-request through the `dispatcher` option.

+The TLS options for the connection to the target server, given as `requestTls`
+or as a `connect` object, apply on every route: direct (no proxy configured),
+hosts matching `noProxy`, and proxied through an HTTP, HTTPS, or SOCKS5 proxy.
+When both are set they are merged key by key, and keys set in `connect` take
+precedence over `requestTls` on every route. `proxyTls` applies only to the connection to the
+proxy server, and the target TLS options are never applied to it. When `connect`
+is a function it is used as-is on direct routes, where `requestTls` is then not
+applied, and it is not used on proxied routes.
+
 ```mjs
 import { EnvHttpProxyAgent } from 'undici'

diff --git a/deps/undici/src/docs/docs/api/Fetch.md b/deps/undici/src/docs/docs/api/Fetch.md
index 86bc8d70c20..6ceb64e2608 100644
--- a/deps/undici/src/docs/docs/api/Fetch.md
+++ b/deps/undici/src/docs/docs/api/Fetch.md
@@ -97,6 +97,119 @@ const response = await fetch('https://example.com', {
 })
 ```

+### Composition and interceptors
+
+undici's [`Dispatcher.compose()`][] composes a chain of interceptors over the
+dispatcher's `dispatch()` method, returning a new dispatcher. Passing that
+composed dispatcher to `fetch()` via `init.dispatcher` is the supported way
+to add retry, cache, custom redirect handling, header dumping, or any
+user-defined behaviour around a `fetch()` call — without changing the
+WHATWG `fetch()` surface itself.
+
+The following recipes cover the most common questions about `fetch()`
+behaviour. Each one builds a dispatcher once and reuses it for every call.
+
+#### Automatic retry
+
+Retry transient network errors and 5xx responses, without manual loops:
+
+```mjs
+import { fetch, Agent, interceptors } from 'undici'
+
+const dispatcher = new Agent().compose(interceptors.retry({
+  maxRetries: 3,
+  minTimeout: 500,
+  maxTimeout: 5_000,
+  timeoutFactor: 2,
+  // Methods allowed to retry; the default list excludes POST and PATCH
+  // to avoid replaying non-idempotent side effects.
+  methods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE', 'QUERY'],
+  statusCodes: [500, 502, 503, 504, 429],
+  errorCodes: ['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN',
+    'ENETUNREACH', 'EHOSTDOWN', 'EHOSTUNREACH', 'EPIPE', 'UND_ERR_SOCKET']
+}))
+
+const response = await fetch('https://example.com/api', { dispatcher })
+```
+
+See [`RetryHandler`][] for the full option reference.
+
+#### HTTP caching
+
+Serve responses from an in-memory or SQLite cache store, honouring
+`Cache-Control` and `Vary`:
+
+```mjs
+import { fetch, Agent, interceptors, cacheStores } from 'undici'
+
+const dispatcher = new Agent().compose(interceptors.cache({
+  store: new cacheStores.MemoryCacheStore(),
+  methods: ['GET', 'HEAD']
+}))
+
+const response = await fetch('https://example.com/api', { dispatcher })
+```
+
+See [CacheStore][] for store options.
+
+#### Custom redirect handling
+
+Follow redirects a limited number of times, with optional header-stripping on
+cross-origin hops:
+
+```mjs
+import { fetch, Agent, interceptors } from 'undici'
+
+const dispatcher = new Agent().compose(interceptors.redirect({
+  maxRedirections: 5,
+  stripHeadersOnCrossOriginRedirect: ['authorization', 'cookie']
+}))
+
+const response = await fetch('https://example.com/old-path', { dispatcher })
+```
+
+#### Response error enrichment
+
+Surface a `ResponseError` (with status + headers + body preview) instead of a
+raw `Response` when the server returns 4xx/5xx:
+
+```mjs
+import { fetch, Agent, interceptors } from 'undici'
+
+const dispatcher = new Agent().compose(interceptors.responseError({
+  // Max response body bytes buffered into the thrown ResponseError.
+  maxSize: 128 * 1024
+}))
+
+try {
+  await fetch('https://example.com/missing', { dispatcher })
+} catch (err) {
+  // err is a ResponseError with err.statusCode, err.headers, err.body
+}
+```
+
+#### Chaining multiple interceptors
+
+`compose()` accepts an array; the order matters — the LAST interceptor in the
+array runs FIRST on the outbound request:
+
+```mjs
+import { fetch, Agent, interceptors } from 'undici'
+
+const dispatcher = new Agent().compose([
+  interceptors.retry({ maxRetries: 2 }),
+  interceptors.redirect({ maxRedirections: 5 }),
+  interceptors.cache({ store: new cacheStores.MemoryCacheStore() })
+])
+
+// On the way out: cache → redirect → retry → network.
+// On the way back: network → retry → redirect → cache.
+const response = await fetch('https://example.com/api', { dispatcher })
+```
+
+See [`Dispatcher.compose()`][] for the full composition semantics, and
+[Interceptors][] for the complete list of built-in interceptors.
+
 ## Class: `FormData`

 <!-- YAML
@@ -713,9 +826,13 @@ added: v1.0.0
 * Type: {boolean} `true` once the body has been read.

 [@fastify/busboy]: https://www.npmjs.com/package/@fastify/busboy
+[`Dispatcher.compose()`]: ./Dispatcher.md#dispatchercomposeinterceptors-interceptor
+[CacheStore]: ./CacheStore.md
+[Interceptors]: ./Interceptors.md
 [MDN Fetch documentation]: https://developer.mozilla.org/en-US/docs/Web/API/fetch
 [MDN `FormData` documentation]: https://developer.mozilla.org/en-US/docs/Web/API/FormData
 [MDN `Headers` documentation]: https://developer.mozilla.org/en-US/docs/Web/API/Headers
 [MDN `Request` documentation]: https://developer.mozilla.org/en-US/docs/Web/API/Request
 [MDN `Response` documentation]: https://developer.mozilla.org/en-US/docs/Web/API/Response
+[`RetryHandler`]: ./RetryHandler.md
 [WHATWG Fetch Standard]: https://fetch.spec.whatwg.org/
diff --git a/deps/undici/src/docs/docs/api/H2CClient.md b/deps/undici/src/docs/docs/api/H2CClient.md
index 9f218b92cdf..a899d7337b0 100644
--- a/deps/undici/src/docs/docs/api/H2CClient.md
+++ b/deps/undici/src/docs/docs/api/H2CClient.md
@@ -83,7 +83,7 @@ added: v7.7.0
     **Default:** `600e3`.
   * `keepAliveTimeoutThreshold` {number} A number of milliseconds subtracted from
     server _keep-alive_ hints when overriding `keepAliveTimeout`, to account for
-    timing inaccuracies such as transport latency. **Default:** `1e3`.
+    timing inaccuracies such as transport latency. **Default:** `2e3`.
   * `socketPath` {string} An IPC endpoint, either a Unix domain socket or a
     Windows named pipe. **Default:** `null`.
   * `strictContentLength` {boolean} If `true`, an error is thrown when the
@@ -95,8 +95,9 @@ added: v7.7.0
     a custom connector function. The `allowH2` option may not be set here.
     **Default:** `null`.
   * `maxRequestsPerClient` {number} The maximum number of requests to send over
-    a single connection before it is reset. Use `0` to disable this limit.
-    **Default:** `null`.
+    a single connection. Once this limit is reached, the client lets existing
+    streams finish and closes the session before sending queued requests on a
+    new connection. Use `0` to disable this limit. **Default:** `null`.
   * `localAddress` {string} The local IP address the socket should connect from.
   * `maxResponseSize` {number} The maximum allowed response body size in bytes.
     Use `-1` to disable. **Default:** `-1`.
diff --git a/deps/undici/src/docs/docs/api/Interceptors.md b/deps/undici/src/docs/docs/api/Interceptors.md
index 1ac3592e3de..3cc577ce3a1 100644
--- a/deps/undici/src/docs/docs/api/Interceptors.md
+++ b/deps/undici/src/docs/docs/api/Interceptors.md
@@ -288,12 +288,14 @@ dual-stack (IPv4 + IPv6) and custom lookup/storage implementations.
 **Parameters**

 * `opts` {Object} (optional)
-  * `maxTTL` {number} Maximum number of milliseconds a DNS record is cached,
-    regardless of the TTL returned by the resolver. **Default:** `0`
-    (use the TTL from the DNS record).
-  * `maxItems` {number} Maximum number of origins to cache simultaneously.
-    Oldest entries are evicted when the limit is reached. **Default:**
-    `Infinity`.
+  * `maxTTL` {number} Maximum number of milliseconds a DNS record is cached.
+    A record that `lookup` returns with a shorter TTL keeps its own TTL. A
+    record without a TTL, which includes every record from the default
+    lookup, is cached for `maxTTL`. **Default:** `10000` (10 seconds).
+  * `maxItems` {number} Maximum number of hostnames to cache at the same
+    time. When the cache is full, cached hostnames stay until their records
+    expire, and other hostnames are not looked up or cached: their requests
+    are resolved as if the interceptor were not used. **Default:** `Infinity`.
   * `dualStack` {boolean} When `true`, both IPv4 (`A`) and IPv6 (`AAAA`)
     records are looked up and the interceptor picks between them based on
     `affinity`. **Default:** `true`.
@@ -435,8 +437,12 @@ const agent = new Agent().compose(

 ## Composing multiple interceptors

-Interceptors are applied in the order they appear in the `compose()` call.
-The first interceptor in the array wraps the outermost layer.
+Each interceptor passed to `compose()` wraps the dispatcher built from the
+interceptors before it. The last interceptor in the array is therefore the
+outermost layer: it is the first to see a request and the last to see its
+response. The first interceptor is the innermost one, closest to the
+underlying dispatcher. See [`Dispatcher.compose()`](./Dispatcher.md) for the
+order-sensitive built-in interceptors.

 ```js
 import { Agent, interceptors } from 'undici'
@@ -450,10 +456,12 @@ const agent = new Agent().compose([
 ])
 ```

-In the example above the request flow is:
+In the example above a request passes through the interceptors from last to
+first:

-1. **dns** — resolves and caches the target IP
-2. **retry** — retries the dispatch on transient failures
-3. **redirect** — follows any 3xx redirects
-4. **decompress** — decompresses the response body
-5. **responseError** — converts 4xx/5xx into thrown errors
+1. **responseError** — converts 4xx/5xx into thrown errors
+2. **decompress** — decompresses the response body
+3. **redirect** — follows any 3xx redirects, sending each hop through the
+   interceptors below it
+4. **retry** — retries the dispatch of each hop on transient failures
+5. **dns** — resolves and caches the IP of each hop's origin
diff --git a/deps/undici/src/lib/api/api-request.js b/deps/undici/src/lib/api/api-request.js
index 73782a0f2d3..6913541a03f 100644
--- a/deps/undici/src/lib/api/api-request.js
+++ b/deps/undici/src/lib/api/api-request.js
@@ -202,7 +202,9 @@ class RequestHandler extends AsyncResource {
       this.res = null
       // Ensure all queued handlers are invoked before destroying res.
       queueMicrotask(() => {
-        util.destroy(res.on('error', noop), err)
+        if (!util.isDestroyed(res)) {
+          util.destroy(res.on('error', noop), err)
+        }
       })
     }

diff --git a/deps/undici/src/lib/api/api-stream.js b/deps/undici/src/lib/api/api-stream.js
index a5e1b3ef472..cf558ee878d 100644
--- a/deps/undici/src/lib/api/api-stream.js
+++ b/deps/undici/src/lib/api/api-stream.js
@@ -104,6 +104,9 @@ class StreamHandler extends AsyncResource {
     this.trailers = null
     this.body = body
     this.onInfo = onInfo || null
+    // Set once the factory's writable is tracked: from then on its lifecycle
+    // owns the callback, which must not be invoked from onResponseError.
+    this.responseStarted = false

     if (util.isStream(body)) {
       body.on('error', (err) => {
@@ -173,13 +176,17 @@ class StreamHandler extends AsyncResource {
       }

       this.callback = null
-      this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
+      if (callback) {
+        this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
+      }

       if (err) {
         abort(err)
       }
     })

+    this.responseStarted = true
+
     res.on('drain', () => controller.resume())

     this.res = res
@@ -231,7 +238,7 @@ class StreamHandler extends AsyncResource {
     if (res) {
       this.res = null
       util.destroy(res, err)
-    } else if (callback) {
+    } else if (callback && !this.responseStarted) {
       this.callback = null
       queueMicrotask(() => {
         this.runInAsyncScope(callback, null, err, { opaque })
diff --git a/deps/undici/src/lib/api/readable.js b/deps/undici/src/lib/api/readable.js
index cfdcc13a552..78394706ff3 100644
--- a/deps/undici/src/lib/api/readable.js
+++ b/deps/undici/src/lib/api/readable.js
@@ -83,12 +83,18 @@ class BodyReadable extends Readable {
    * @returns {void}
    */
   _destroy (err, callback) {
-    if (!err && !this._readableState.endEmitted) {
+    const synthesized = !err && !this._readableState.endEmitted
+    if (synthesized) {
       err = new RequestAbortedError()
     }

     if (err) {
-      this[kAbort]()
+      this[kAbort](err)
+    }
+
+    if (synthesized && this.listenerCount('error') === 0) {
+      // Errorless destroy() must not throw when no 'error' listener is attached.
+      this.once('error', noop)
     }

     // Workaround for Node "bug". If the stream is destroyed in same
@@ -156,10 +162,16 @@ class BodyReadable extends Readable {
   push (chunk) {
     if (chunk) {
       this[kBytesRead] += chunk.length
-      if (this[kConsume]) {
+      if (this[kConsume]?.started) {
         consumePush(this[kConsume], chunk)
         return this[kReading] ? super.push(chunk) : true
       }
+      // consume() was called but consumeStart() hasn't run yet: keep routing
+      // the chunk through the normal push path so it flows through the
+      // decoder and lands in the readable buffer in order; consumeStart()
+      // drains it from there. Bypassing super.push() here would deliver raw
+      // bytes ahead of already-buffered content and desynchronize the
+      // decoder (see the setEncoding() tests).
     }

     return super.push(chunk)
@@ -379,6 +391,7 @@ function isUnusable (bodyReadable) {
  * @property {((err: Error) => void)} reject
  * @property {number} length
  * @property {Buffer[]} body
+ * @property {boolean} started
  */

 /**
@@ -388,8 +401,6 @@ function isUnusable (bodyReadable) {
  * @returns {Promise<ConsumeReturnType<T>>}
  */
 function consume (stream, type) {
-  assert(!stream[kConsume])
-
   return new Promise((resolve, reject) => {
     if (isUnusable(stream)) {
       const rState = stream._readableState
@@ -403,15 +414,17 @@ function consume (stream, type) {
         reject(rState.errored ?? new TypeError('unusable'))
       }
     } else {
+      stream[kConsume] = {
+        type,
+        stream,
+        resolve,
+        reject,
+        length: 0,
+        body: [],
+        started: false
+      }
       queueMicrotask(() => {
-        stream[kConsume] = {
-          type,
-          stream,
-          resolve,
-          reject,
-          length: 0,
-          body: []
-        }
+        stream[kConsume].started = true

         stream
           .on('error', function (err) {
diff --git a/deps/undici/src/lib/cache/memory-cache-store.js b/deps/undici/src/lib/cache/memory-cache-store.js
index 7aeba57fe46..a81e6f19cb9 100644
--- a/deps/undici/src/lib/cache/memory-cache-store.js
+++ b/deps/undici/src/lib/cache/memory-cache-store.js
@@ -2,7 +2,7 @@

 const { Writable } = require('node:stream')
 const { EventEmitter } = require('node:events')
-const { assertCacheKey, assertCacheValue } = require('../util/cache.js')
+const { assertCacheKey, assertCacheValue, createBodyChunkCoalescer } = require('../util/cache.js')

 /**
  * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey
@@ -134,6 +134,7 @@ class MemoryCacheStore extends EventEmitter {

     const store = this
     const entry = { ...key, ...val, body: [], size: 0 }
+    const coalescer = createBodyChunkCoalescer(entry.body)

     return new Writable({
       write (chunk, encoding, callback) {
@@ -146,12 +147,14 @@ class MemoryCacheStore extends EventEmitter {
         if (entry.size > store.#maxEntrySize) {
           this.destroy()
         } else {
-          entry.body.push(chunk)
+          coalescer.push(chunk)
         }

         callback(null)
       },
       final (callback) {
+        coalescer.flush()
+
         let entries = store.#entries.get(topLevelKey)
         if (entries) {
           store.#entries.delete(topLevelKey)
diff --git a/deps/undici/src/lib/cache/sqlite-cache-store.js b/deps/undici/src/lib/cache/sqlite-cache-store.js
index 1024cb6a791..7fb69881abb 100644
--- a/deps/undici/src/lib/cache/sqlite-cache-store.js
+++ b/deps/undici/src/lib/cache/sqlite-cache-store.js
@@ -1,7 +1,7 @@
 'use strict'

 const { Writable } = require('node:stream')
-const { assertCacheKey, assertCacheValue } = require('../util/cache.js')
+const { assertCacheKey, assertCacheValue, createBodyChunkCoalescer } = require('../util/cache.js')
 const { zstdCompressSync, zstdDecompressSync } = require('node:zlib')

 let DatabaseSync
@@ -375,6 +375,7 @@ module.exports = class SqliteCacheStore {
      * @type {Buffer[] | null}
      */
     const body = []
+    const coalescer = createBodyChunkCoalescer(body)
     const store = this

     return new Writable({
@@ -383,7 +384,7 @@ module.exports = class SqliteCacheStore {
         size += chunk.byteLength

         if (size <= store.#maxEntrySize) {
-          body.push(chunk)
+          coalescer.push(chunk)
         } else {
           this.destroy()
         }
@@ -391,6 +392,7 @@ module.exports = class SqliteCacheStore {
         callback()
       },
       final (callback) {
+        coalescer.flush()
         store.set(key, { ...value, body })
         callback()
       }
diff --git a/deps/undici/src/lib/core/symbols.js b/deps/undici/src/lib/core/symbols.js
index 842669bc6d7..083b4550a6d 100644
--- a/deps/undici/src/lib/core/symbols.js
+++ b/deps/undici/src/lib/core/symbols.js
@@ -34,6 +34,7 @@ module.exports = {
   kQueued: Symbol('queued'),
   kFree: Symbol('free'),
   kConnected: Symbol('connected'),
+  kHasConnectedClient: Symbol('has connected client'),
   kClosed: Symbol('closed'),
   kNeedDrain: Symbol('need drain'),
   kReset: Symbol('reset'),
diff --git a/deps/undici/src/lib/core/util.js b/deps/undici/src/lib/core/util.js
index 43ea414ab76..487c8be6db3 100644
--- a/deps/undici/src/lib/core/util.js
+++ b/deps/undici/src/lib/core/util.js
@@ -32,7 +32,10 @@ function noop () {}
  * @returns {*}
  */
 function wrapRequestBody (body) {
-  if (isStream(body)) {
+  if (body instanceof BodyAsyncIterable || Array.isArray(body)) {
+    // Already tracked by an outer handler, or replayable as is.
+    return body
+  } else if (isStream(body)) {
     // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
     // so that it can be dispatched again?
     // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
diff --git a/deps/undici/src/lib/dispatcher/agent.js b/deps/undici/src/lib/dispatcher/agent.js
index a73ba2e0541..5e4cab1327b 100644
--- a/deps/undici/src/lib/dispatcher/agent.js
+++ b/deps/undici/src/lib/dispatcher/agent.js
@@ -1,7 +1,7 @@
 'use strict'

 const { InvalidArgumentError, MaxOriginsReachedError } = require('../core/errors')
-const { kBusy, kClients, kConnected, kRunning, kPending, kClose, kDestroy, kDispatch, kUrl } = require('../core/symbols')
+const { kBusy, kClients, kHasConnectedClient, kRunning, kPending, kClose, kDestroy, kDispatch, kUrl } = require('../core/symbols')
 const DispatcherBase = require('./dispatcher-base')
 const Pool = require('./pool')
 const Client = require('./client')
@@ -106,7 +106,7 @@ class Agent extends DispatcherBase {
         // no connected clients and is not busy, but it still has pending work.
         // Closing it here lets the replacement Client finish those requests
         // and then destroys that new connection with ClientDestroyedError.
-        if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
+        if (dispatcher[kHasConnectedClient] || dispatcher[kBusy]) {
           return
         }

diff --git a/deps/undici/src/lib/dispatcher/client-h1.js b/deps/undici/src/lib/dispatcher/client-h1.js
index fe53d118081..51954b19805 100644
--- a/deps/undici/src/lib/dispatcher/client-h1.js
+++ b/deps/undici/src/lib/dispatcher/client-h1.js
@@ -680,13 +680,10 @@ class Parser {
       this.contentLength = -1
     }

+    // Keep the headers timeout running until a final response arrives.
     if (this.statusCode >= 200) {
       const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout]
       this.setTimeout(bodyTimeout, TIMEOUT_BODY)
-    } else if (this.timeout) {
-      if (this.timeout.refresh) {
-        this.timeout.refresh()
-      }
     }

     if (request.method === 'CONNECT') {
diff --git a/deps/undici/src/lib/dispatcher/client-h2.js b/deps/undici/src/lib/dispatcher/client-h2.js
index e70b5deb9eb..9ee63afb46a 100644
--- a/deps/undici/src/lib/dispatcher/client-h2.js
+++ b/deps/undici/src/lib/dispatcher/client-h2.js
@@ -42,7 +42,9 @@ const {
   kHTTP2Stream,
   kHTTP2SessionState,
   kHTTP2Options,
-  kMaxResponseSize
+  kMaxResponseSize,
+  kMaxRequests,
+  kCounter
 } = require('../core/symbols.js')
 const { channels } = require('../core/diagnostics.js')

@@ -221,6 +223,35 @@ function registerGoAwayRefusal (request) {
   return attempts <= MAX_GOAWAY_REPLAY_ATTEMPTS
 }

+// Requests the session held back without opening a stream: the peer allows no
+// streams (SETTINGS_MAX_CONCURRENT_STREAMS = 0), or an extended CONNECT waits
+// for the peer's SETTINGS. No stream means no stream timeout and no GOAWAY
+// refusal ever applies to them, and the no-streams timeout belongs to the
+// session. A connection that goes away in that state refused all of them, so
+// count it against their replay budget. Otherwise a peer that keeps doing so
+// turns one request into an unbounded reconnect loop.
+function refuseHeldRequests (client, err) {
+  const queue = client[kQueue]
+  const failed = []
+  let j = client[kPendingIdx]
+
+  for (let i = client[kPendingIdx]; i < queue.length; i++) {
+    const request = queue[i]
+
+    if (request != null && !registerGoAwayRefusal(request)) {
+      failed.push(request)
+    } else {
+      queue[j++] = request
+    }
+  }
+
+  queue.length = j
+
+  for (let i = 0; i < failed.length; i++) {
+    util.errorRequest(client, failed[i], err)
+  }
+}
+
 function closeStream (stream, code = NGHTTP2_REFUSED_STREAM) {
   if (stream != null && !stream.destroyed && !stream.closed) {
     try {
@@ -296,6 +327,8 @@ function connectH2 (client, socket) {
     // Armed while a PING checks whether the peer is still there after a
     // stream timed out. See probeHttp2Session.
     probeTimeout: null,
+    // Stop opening streams once this session reaches its request limit.
+    retiring: false,
     // Sockets start out ref'd. Session ref/unref proxies to the socket, so a
     // single cached flag lets us skip redundant uv ref/unref calls, provided
     // every ref/unref of the session or its socket goes through
@@ -389,6 +422,10 @@ function connectH2 (client, socket) {
      * @returns {boolean}
     */
     busy (request) {
+      if (session[kHTTP2SessionState].retiring) {
+        return true
+      }
+
       // Before SETTINGS, the client takes one request at a time from a Pool,
       // and only dispatches alongside a running request when a REFUSED_STREAM
       // from a lower peer limit can still be retried.
@@ -456,6 +493,8 @@ function resumeH2 (client) {
   const session = client[kHTTP2Session]

   if (socket?.destroyed === false) {
+    const { retiring } = session[kHTTP2SessionState]
+
     // After an upgrade the queue is empty but its stream is still in use, so never unref while a stream is open.
     if (session[kOpenStreams] === 0 && client[kSize] === 0) {
       unrefH2Session(session)
@@ -469,7 +508,7 @@ function resumeH2 (client) {
       clearHttp2IdleTimeout(session)
     }

-    if (client[kMaxConcurrentStreams] === 0 && client[kRunning] === 0 && client[kPending] > 0) {
+    if (!retiring && client[kMaxConcurrentStreams] === 0 && client[kRunning] === 0 && client[kPending] > 0) {
       setNoStreamsTimeout(session)
     } else {
       clearNoStreamsTimeout(session)
@@ -757,6 +796,7 @@ function onHttp2SessionGoAway (errorCode, lastStreamID) {

   const err = getGoAwayError(this, errorCode)
   const client = this[kClient]
+  const held = client[kRunning] === 0 && !this[kHTTP2SessionState]?.retiring
   const previousPendingIdx = client[kPendingIdx]
   const pendingIdx = getGoAwayPendingIdx(client, lastStreamID)
   const retriableRequests = []
@@ -816,6 +856,10 @@ function onHttp2SessionGoAway (errorCode, lastStreamID) {
     this.close()
   }

+  if (held) {
+    refuseHeldRequests(client, err)
+  }
+
   client.emit('disconnect', client[kUrl], [client], err)

   client[kResume]()
@@ -879,10 +923,17 @@ function onHttp2SocketClose () {

   session.destroy(err)

+  // Requests waiting for local rotation were not refused by the peer.
+  const held = !session[kHTTP2SessionState].retiring && client[kRunning] === 0
+
   client[kPendingIdx] = client[kRunningIdx]

   assert(client[kRunning] === 0)

+  if (held) {
+    refuseHeldRequests(client, err)
+  }
+
   client.emit('disconnect', client[kUrl], [client], err)

   client[kResume]()
@@ -899,7 +950,7 @@ function onHttp2SocketError (err) {
 }

 function onHttp2SocketEnd () {
-  util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
+  util.destroy(this, this[kError] ?? new SocketError('other side closed', util.getSocketInfo(this)))
 }

 function onSocketClose () {
@@ -914,6 +965,18 @@ function closeStreamSession (stream) {

   stream[kHTTP2Session] = null
   session[kOpenStreams] -= 1
+
+  if (
+    session[kOpenStreams] === 0 &&
+    session[kHTTP2SessionState].retiring &&
+    client[kHTTP2Session] === session &&
+    !session[kReceivedGoAway] && !session.closed && !session.destroyed
+  ) {
+    // Close gracefully: a response can end before its native stream closes.
+    session[kSocket][kError] ??= new InformationalError('max requests per client reached')
+    session.close()
+  }
+
   // A session that received GOAWAY does not need to stay ref'd for queued requests.
   if (session[kOpenStreams] === 0 && (client[kSize] === 0 || session[kReceivedGoAway])) {
     unrefH2Session(session)
@@ -1127,7 +1190,12 @@ function finalizeRequest (state, resetPendingIdx = false) {

 function openStream (client, request, session, abort, headers, options) {
   try {
-    return session.request(headers, options)
+    const stream = session.request(headers, options)
+    const socket = session[kSocket]
+    if (socket[kMaxRequests] && ++socket[kCounter] >= socket[kMaxRequests]) {
+      session[kHTTP2SessionState].retiring = true
+    }
+    return stream
   } catch (err) {
     // A GOAWAY'd session rejects new streams, same as an invalid session:
     // reset and requeue on a fresh connection rather than the destroy + abort
diff --git a/deps/undici/src/lib/dispatcher/dispatcher-base.js b/deps/undici/src/lib/dispatcher/dispatcher-base.js
index 7261fd17a90..86d22ea6a43 100644
--- a/deps/undici/src/lib/dispatcher/dispatcher-base.js
+++ b/deps/undici/src/lib/dispatcher/dispatcher-base.js
@@ -7,7 +7,7 @@ const {
   ClientClosedError,
   InvalidArgumentError
 } = require('../core/errors')
-const { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require('../core/symbols')
+const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kConnected, kHasConnectedClient } = require('../core/symbols')
 const { defaultWebSocketMaxFragments, defaultWebSocketMaxPayloadSize } = require('../core/constants')

 const kOnDestroyed = Symbol('onDestroyed')
@@ -66,6 +66,15 @@ class DispatcherBase extends Dispatcher {
     return this[kClosed]
   }

+  /**
+   * Whether at least one client is connected. Dispatchers that hold more than
+   * one client can answer this without counting all of them.
+   * @returns {boolean}
+   */
+  get [kHasConnectedClient] () {
+    return this[kConnected] > 0
+  }
+
   close (callback) {
     if (callback === undefined) {
       return new Promise((resolve, reject) => {
diff --git a/deps/undici/src/lib/dispatcher/env-http-proxy-agent.js b/deps/undici/src/lib/dispatcher/env-http-proxy-agent.js
index 7fe52dcc7cb..7bcb75f1515 100644
--- a/deps/undici/src/lib/dispatcher/env-http-proxy-agent.js
+++ b/deps/undici/src/lib/dispatcher/env-http-proxy-agent.js
@@ -21,18 +21,36 @@ class EnvHttpProxyAgent extends DispatcherBase {

     const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts

-    this[kNoProxyAgent] = new Agent(agentOpts)
+    // The environment picks the route (direct, NO_PROXY or proxied), so the
+    // TLS options for the target must apply on every route, merged the same
+    // way: field by field, `connect` over `requestTls` over `tls`. The direct
+    // Agent reads them from `connect` and `tls`, a ProxyAgent from
+    // `requestTls`. A `connect` function is a custom connector: it is used
+    // as-is on direct routes and cannot be applied to the target of a proxy.
+    const { connect, tls, requestTls } = agentOpts
+    const connectOpts = typeof connect === 'function' ? undefined : connect
+    const tlsOpts = typeof tls === 'object' ? tls : undefined
+
+    this[kNoProxyAgent] = new Agent(
+      requestTls && typeof connect !== 'function'
+        ? { ...agentOpts, connect: { ...requestTls, ...connect } }
+        : agentOpts
+    )
+
+    const proxyOpts = connectOpts || tlsOpts
+      ? { ...agentOpts, requestTls: { ...tlsOpts, ...requestTls, ...connectOpts } }
+      : agentOpts

     const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY
     if (HTTP_PROXY) {
-      this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY })
+      this[kHttpProxyAgent] = new ProxyAgent({ ...proxyOpts, uri: HTTP_PROXY })
     } else {
       this[kHttpProxyAgent] = this[kNoProxyAgent]
     }

     const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY
     if (HTTPS_PROXY) {
-      this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY })
+      this[kHttpsProxyAgent] = new ProxyAgent({ ...proxyOpts, uri: HTTPS_PROXY })
     } else {
       this[kHttpsProxyAgent] = this[kHttpProxyAgent]
     }
diff --git a/deps/undici/src/lib/dispatcher/pool-base.js b/deps/undici/src/lib/dispatcher/pool-base.js
index 5453fd29c33..f6ca12deb3a 100644
--- a/deps/undici/src/lib/dispatcher/pool-base.js
+++ b/deps/undici/src/lib/dispatcher/pool-base.js
@@ -4,7 +4,7 @@ const { AsyncResource } = require('node:async_hooks')
 const { PoolStats } = require('../util/stats.js')
 const DispatcherBase = require('./dispatcher-base')
 const FixedQueue = require('./fixed-queue')
-const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require('../core/symbols')
+const { kConnected, kHasConnectedClient, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require('../core/symbols')
 const { createAbortedController } = require('../core/request')

 const kClients = Symbol('clients')
@@ -215,6 +215,17 @@ class PoolBase extends DispatcherBase {
     return this[kNeedDrain]
   }

+  // A pool can hold one client per open response, so stop at the first
+  // connected client instead of counting all of them.
+  get [kHasConnectedClient] () {
+    for (let i = 0; i < this[kClients].length; i++) {
+      if (this[kClients][i][kConnected]) {
+        return true
+      }
+    }
+    return false
+  }
+
   get [kConnected] () {
     let ret = 0
     for (const { [kConnected]: connected } of this[kClients]) {
diff --git a/deps/undici/src/lib/dispatcher/proxy-agent.js b/deps/undici/src/lib/dispatcher/proxy-agent.js
index d90ff5930c1..f3bb00ba0ba 100644
--- a/deps/undici/src/lib/dispatcher/proxy-agent.js
+++ b/deps/undici/src/lib/dispatcher/proxy-agent.js
@@ -128,7 +128,10 @@ class ProxyAgent extends DispatcherBase {
     this[kProxy] = { uri: href, protocol }
     this[kRequestTls] = opts.requestTls
     this[kProxyTls] = opts.proxyTls
-    this[kProxyHeaders] = opts.headers || {}
+    // Copy the caller's headers: proxy-authorization is added below, and it
+    // must not leak into an object the caller shares with other agents (such
+    // as the HTTP and HTTPS proxies of an EnvHttpProxyAgent) or requests.
+    this[kProxyHeaders] = { ...opts.headers }
     this[kTunnelProxy] = proxyTunnel

     if (opts.auth && opts.token) {
diff --git a/deps/undici/src/lib/dispatcher/retry-agent.js b/deps/undici/src/lib/dispatcher/retry-agent.js
index e0374f80c2d..7feefae2f75 100644
--- a/deps/undici/src/lib/dispatcher/retry-agent.js
+++ b/deps/undici/src/lib/dispatcher/retry-agent.js
@@ -23,7 +23,10 @@ class RetryAgent extends Dispatcher {
       dispatch: this.#agent.dispatch.bind(this.#agent),
       handler
     })
-    return this.#agent.dispatch(opts, retry)
+    // Send the body the handler tracks, so it can tell when a body that
+    // cannot be replayed was consumed by this first attempt.
+    const { body } = retry.opts
+    return this.#agent.dispatch(body === opts.body ? opts : { ...opts, body }, retry)
   }

   // WebSocket and EventSource read their receive limits from the dispatcher
diff --git a/deps/undici/src/lib/dispatcher/socks5-proxy-agent.js b/deps/undici/src/lib/dispatcher/socks5-proxy-agent.js
index 1a511c6c923..a59a93d3eec 100644
--- a/deps/undici/src/lib/dispatcher/socks5-proxy-agent.js
+++ b/deps/undici/src/lib/dispatcher/socks5-proxy-agent.js
@@ -7,7 +7,7 @@ const DispatcherBase = require('./dispatcher-base')
 const { ConnectTimeoutError, InvalidArgumentError } = require('../core/errors')
 const { Socks5Client, STATES } = require('../core/socks5-client')
 const { stripIPv6Brackets } = require('../core/socks5-utils')
-const { kBusy, kConnected, kDispatch, kClose, kDestroy } = require('../core/symbols')
+const { kBusy, kHasConnectedClient, kDispatch, kClose, kDestroy } = require('../core/symbols')
 const Pool = require('./pool')
 const buildConnector = require('../core/connect')
 const { setupConnectTimeout, getServerName } = require('../core/util')
@@ -299,7 +299,7 @@ class Socks5ProxyAgent extends DispatcherBase {
         this[kPools].set(originKey, pool)

         const closePoolIfUnused = () => {
-          if (this[kPools].get(originKey) !== pool || pool[kConnected] > 0 || pool[kBusy]) {
+          if (this[kPools].get(originKey) !== pool || pool[kHasConnectedClient] || pool[kBusy]) {
             return
           }

diff --git a/deps/undici/src/lib/handler/cache-handler.js b/deps/undici/src/lib/handler/cache-handler.js
index d139853ec59..f134905cef1 100644
--- a/deps/undici/src/lib/handler/cache-handler.js
+++ b/deps/undici/src/lib/handler/cache-handler.js
@@ -5,10 +5,15 @@ const { kRedirectCacheControl } = require('../core/symbols')
 const {
   parseCacheControlHeader,
   hasInvalidCacheControlDirective,
+  revalidationResponseChangesVary,
+  revalidationTargetMatchesCacheKey,
   parseVaryHeader,
   hasVaryStar,
   isInvalidOrWildcardVaryHeader,
-  isEtagUsable
+  isEtagUsable,
+  trimOWS,
+  revalidationEtagMatchesCachedValue,
+  revalidationResponseAddsVary
 } = require('../util/cache')

 /**
@@ -102,10 +107,6 @@ const MAX_RESPONSE_AGE = 2147483647000
 // validator present); each successful revalidation re-stores the entry.
 const REVALIDATION_ONLY_RETENTION = 86400000 // 24 hours

-function trimOWS (value) {
-  return value.replace(/^[\t ]+|[\t ]+$/g, '')
-}
-
 function arrayIncludes (array, value) {
   for (let i = 0; i < array.length; i++) {
     if (array[i] === value) {
@@ -267,16 +268,26 @@ class CacheHandler {
   #history

   /**
-   * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts
+   * Called when a validating (304) response does not identify the same
+   * representation as the cached value, so the cached body must not be reused
+   * or freshened. Lets a background revalidation discard the stale body and
+   * re-fetch unconditionally.
+   * @type {((cacheKey: import('../../types/cache-interceptor.d.ts').default.CacheKey) => void) | undefined}
+   */
+  #onInvalidRevalidation
+
+  /**
+   * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions & { onInvalidRevalidation?: (cacheKey: import('../../types/cache-interceptor.d.ts').default.CacheKey) => void }} opts
    * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
    * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
    */
-  constructor ({ store, type, cacheByDefault }, cacheKey, handler) {
+  constructor ({ store, type, cacheByDefault, onInvalidRevalidation }, cacheKey, handler) {
     this.#store = store
     this.#cacheType = type
     this.#cacheByDefault = cacheByDefault
     this.#cacheKey = cacheKey
     this.#handler = handler
+    this.#onInvalidRevalidation = onInvalidRevalidation
   }

   onRequestStart (controller, context) {
@@ -572,6 +583,42 @@ class CacheHandler {
           return
         }

+        // A 304 only freshens the stored response it validates (RFC 9111
+        // §4.3.4). One produced by a redirect target, one carrying a different
+        // ETag, or one that changes the fields the response varies on does
+        // not: drop the stored entry rather than re-store its body under the
+        // 304's metadata.
+        //
+        // When the 304 came from the cached URL itself but names another
+        // representation (a different ETag, or a Vary field the stored
+        // response did not vary on), a background revalidation re-fetches
+        // unconditionally, mirroring the synchronous path.
+        const targetMatches = revalidationTargetMatchesCacheKey(this.#cacheKey, this.#history)
+        const refetch = targetMatches && (
+          !revalidationEtagMatchesCachedValue(cachedValue, resHeaders) ||
+          revalidationResponseAddsVary(cachedValue, varyDirectives)
+        )
+        if (
+          !targetMatches ||
+          refetch ||
+          revalidationResponseChangesVary(cachedValue, varyDirectives)
+        ) {
+          // The cached body fetched from the store will not be reused; destroy
+          // it so an async or remote store does not leak the underlying reader.
+          // In the SWR path the stream serving the stale response is a separate
+          // stream owned by sendCachedValue and is intentionally left untouched.
+          if (util.isStream(cachedValue.body)) {
+            cachedValue.body.on('error', noop).destroy()
+          }
+          deleteCachedValue(this.#store, this.#cacheKey)
+          downstreamOnHeaders()
+          finish304()
+          if (refetch) {
+            this.#onInvalidRevalidation?.(this.#cacheKey)
+          }
+          return
+        }
+
         // Re-use the cached value: statuscode, statusmessage, headers and body
         value.statusCode = cachedValue.statusCode
         value.statusMessage = cachedValue.statusMessage
@@ -1018,7 +1065,7 @@ function getAge (ageHeader) {
     return MAX_RESPONSE_AGE
   }

-  const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, ''))
+  const age = BigInt(trimOWS(ageValue))
   if (age >= BigInt(MAX_RESPONSE_AGE / 1000)) {
     return MAX_RESPONSE_AGE
   }
diff --git a/deps/undici/src/lib/handler/redirect-handler.js b/deps/undici/src/lib/handler/redirect-handler.js
index a1459cc32c1..950c8dd0d75 100644
--- a/deps/undici/src/lib/handler/redirect-handler.js
+++ b/deps/undici/src/lib/handler/redirect-handler.js
@@ -16,7 +16,13 @@ class RedirectHandler {
     }

     const dispatch = dispatcher.dispatch.bind(dispatcher)
-    return (opts, originalHandler) => dispatch(opts, new RedirectHandler(dispatch, maxRedirections, opts, originalHandler))
+    return (opts, originalHandler) => {
+      const handler = new RedirectHandler(dispatch, maxRedirections, opts, originalHandler)
+      // Send the body the handler tracks, so it can tell when a body that
+      // cannot be replayed was consumed by this first hop.
+      const { body } = handler.opts
+      return dispatch(body === opts.body ? opts : { ...opts, body }, handler)
+    }
   }

   constructor (dispatch, maxRedirections, opts, handler) {
@@ -115,8 +121,12 @@ class RedirectHandler {
       ? this.opts.origin
       : this.opts[kRequestOrigin]

-    if (requestOrigin) {
-      this.history.push(new URL(this.opts.path, requestOrigin))
+    const requestUrl = requestOrigin
+      ? buildRequestUrl(requestOrigin, this.opts.path)
+      : undefined
+
+    if (requestUrl) {
+      this.history.push(requestUrl)
     }

     if (!this.location) {
@@ -133,10 +143,7 @@ class RedirectHandler {
       receivedAt: Date.now()
     })

-    const baseUrl = requestOrigin
-      ? new URL(this.opts.path, requestOrigin)
-      : undefined
-    const { origin, pathname, search } = util.parseURL(new URL(this.location, baseUrl))
+    const { origin, pathname, search } = util.parseURL(new URL(this.location, requestUrl))
     const path = search ? `${pathname}${search}` : pathname

     // Check for redirect loops by seeing if we've already visited this URL in our history
@@ -152,8 +159,17 @@ class RedirectHandler {
     // Remove headers referring to the original URL.
     // By default it is Host only. A 303 or a 301/302 POST-to-GET redirect also removes all Content-* headers.
     // https://tools.ietf.org/html/rfc7231#section-6.4
-    this.opts.headers = cleanRequestHeaders(this.opts.headers, removeContentHeaders, requestOrigin !== origin, this.stripHeadersOnRedirect, this.stripHeadersOnCrossOriginRedirect)
+    // requestOrigin may be a URL object or a non-canonical string, while origin
+    // is always URL.origin, so compare normalized origins.
+    const crossOrigin = !requestOrigin || new URL(requestOrigin).origin !== origin
+    this.opts.headers = cleanRequestHeaders(this.opts.headers, removeContentHeaders, crossOrigin, this.stripHeadersOnRedirect, this.stripHeadersOnCrossOriginRedirect)
     this.opts.path = path
+    if (crossOrigin && this.opts.servername != null) {
+      // A TLS servername chosen for the original host must not be used to
+      // verify the certificate of another origin. Let the next request derive
+      // it from the new host instead.
+      this.opts.servername = null
+    }
     this.opts.origin = origin
     this.opts[kRequestOrigin] = origin
     this.opts.query = null
@@ -204,6 +220,18 @@ class RedirectHandler {
   }
 }

+// The URL a request was actually sent to. `new URL(path, origin)` is not
+// equivalent: a path such as `//other.example/x` is parsed as a
+// protocol-relative URL and replaces the origin's host, so a hop to one origin
+// would be recorded as a hop to another.
+function buildRequestUrl (origin, path) {
+  const base = new URL(origin)
+  if (typeof path === 'string' && path[0] === '/') {
+    return new URL(`${base.origin}${path}`)
+  }
+  return new URL(path, base)
+}
+
 // https://tools.ietf.org/html/rfc7231#section-6.4.4
 function shouldRemoveHeader (header, removeContent, unknownOrigin, stripHeaders, stripHeadersOnCrossOrigin) {
   const name = util.headerNameToString(header)
diff --git a/deps/undici/src/lib/handler/retry-handler.js b/deps/undici/src/lib/handler/retry-handler.js
index d251a7b1c2a..41b8739edc7 100644
--- a/deps/undici/src/lib/handler/retry-handler.js
+++ b/deps/undici/src/lib/handler/retry-handler.js
@@ -316,6 +316,17 @@ class RetryHandler {
   }

   static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
+    // A malformed (undefined/null/non-object) error must not crash the process
+    // (an unhandled 'error' event on the Client), nor trigger an endless retry
+    // (a falsy error is treated by shouldRetry as "retry"). Normalize it to a
+    // terminal error so it is surfaced downstream instead of throwing while
+    // destructuring below.
+    if (typeof err !== 'object' || err === null) {
+      // `||` (not `??`) so any falsy value (undefined, null, false, 0, '') is
+      // replaced by a terminal error rather than retrying forever.
+      cb(err || new RequestAbortedError())
+      return
+    }
     const { statusCode, code, headers } = err
     const { method, retryOptions } = opts
     const {
@@ -678,7 +689,7 @@ function isReplacedHeader (key, etag) {
 function buildResumeHeaders (headers, range, etag) {
   if (Array.isArray(headers) || (headers && typeof headers === 'object' && hasSafeIterator(headers))) {
     const ret = []
-    if (Array.isArray(headers)) {
+    if (Array.isArray(headers) && (headers.length === 0 || !Array.isArray(headers[0]))) {
       for (let i = 0; i < headers.length; i += 2) {
         if (!isReplacedHeader(headers[i], etag)) {
           ret.push(headers[i], headers[i + 1])
diff --git a/deps/undici/src/lib/interceptor/cache.js b/deps/undici/src/lib/interceptor/cache.js
index eb71c531c57..0ac8af4901c 100644
--- a/deps/undici/src/lib/interceptor/cache.js
+++ b/deps/undici/src/lib/interceptor/cache.js
@@ -12,10 +12,13 @@ const {
   getInterceptorOrigin,
   makeCacheKey,
   normalizeHeaders,
+  revalidationResponseAddsVary,
+  revalidationTargetMatchesCacheKey,
   parseCacheControlHeader,
   isInvalidOrWildcardVaryHeader,
   parseVaryHeader,
-  isEtagUsable
+  trimOWS,
+  revalidationEtagMatchesCachedValue
 } = require('../util/cache.js')
 const { AbortError } = require('../core/errors.js')
 const { kQueuedAbort } = require('../core/symbols.js')
@@ -41,10 +44,6 @@ function assertCacheOrigins (origins, name) {

 const nop = () => {}

-function trimOWS (value) {
-  return value.replace(/^[\t ]+|[\t ]+$/g, '')
-}
-
 function arrayIncludes (array, value) {
   for (let i = 0; i < array.length; i++) {
     if (array[i] === value) {
@@ -79,6 +78,44 @@ function hasPragmaNoCache (headers) {
   return false
 }

+const defaultPorts = { 'http:': '80', 'https:': '443' }
+
+/**
+ * The cache key is built from the origin, but an explicit Host header is what
+ * the server sees as the target authority. Only requests without one, or with
+ * one naming the origin's own host, may use the cache.
+ * @param {Record<string, string | string[]>} headers normalized request headers
+ * @param {string | URL} origin
+ * @returns {boolean}
+ */
+function hostHeaderMatchesOrigin (headers, origin) {
+  if (!Object.hasOwn(headers, 'host')) {
+    return true
+  }
+
+  const host = headers.host
+  if (typeof host !== 'string') {
+    return false
+  }
+
+  let url
+  try {
+    url = new URL(origin)
+  } catch {
+    return false
+  }
+
+  const value = host.toLowerCase()
+  if (value === url.host) {
+    return true
+  }
+
+  // new URL() drops the default port, so `host:80` names the same authority.
+  return url.port === '' &&
+    defaultPorts[url.protocol] !== undefined &&
+    value === `${url.host}:${defaultPorts[url.protocol]}`
+}
+
 /**
  * @typedef {(options: import('../../types/dispatcher.d.ts').default.DispatchOptions, handler: import('../../types/dispatcher.d.ts').default.DispatchHandler) => void} DispatchFn
  */
@@ -150,25 +187,6 @@ function revalidationResponseUpdatesCacheControl (headers) {
   return headers['cache-control'] !== undefined
 }

-/**
- * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result
- * @param {Record<string, string | string[] | null> | undefined} varyDirectives
- * @returns {boolean}
- */
-function revalidationResponseAddsVary (result, varyDirectives) {
-  if (!varyDirectives) {
-    return false
-  }
-
-  for (const key in varyDirectives) {
-    if (result.vary == null || !Object.hasOwn(result.vary, key)) {
-      return true
-    }
-  }
-
-  return false
-}
-
 function deleteCachedValue (store, cacheKey) {
   try {
     store.delete(cacheKey)?.catch?.(nop)
@@ -205,47 +223,6 @@ function makeRevalidationHeaders (opts, result) {
   return headers
 }

-function revalidationTargetMatchesCacheKey (cacheKey, context) {
-  const history = context?.history
-  if (!Array.isArray(history) || history.length === 0) {
-    return true
-  }
-
-  try {
-    const cachedUrl = new URL(cacheKey.path, cacheKey.origin)
-    const responseUrl = history[history.length - 1]
-    return responseUrl.origin === cachedUrl.origin &&
-      responseUrl.pathname === cachedUrl.pathname &&
-      responseUrl.search === cachedUrl.search
-  } catch {
-    return false
-  }
-}
-
-function revalidationEtagMatchesCachedValue (result, headers) {
-  if (!Object.hasOwn(headers, 'etag')) {
-    return true
-  }
-
-  const responseEtag = headers.etag
-  const cachedEtag = result.etag
-  if (
-    typeof responseEtag !== 'string' ||
-    typeof cachedEtag !== 'string' ||
-    !isEtagUsable(responseEtag) ||
-    !isEtagUsable(cachedEtag)
-  ) {
-    return false
-  }
-
-  if (!responseEtag.startsWith('W/')) {
-    return responseEtag === cachedEtag
-  }
-
-  const cachedOpaqueTag = cachedEtag.startsWith('W/') ? cachedEtag.slice(2) : cachedEtag
-  return responseEtag.slice(2) === cachedOpaqueTag
-}
-
 /**
  * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result
  * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} cacheControlDirectives
@@ -539,6 +516,33 @@ function handleResult (
       queueMicrotask(() => {
         const headers = makeRevalidationHeaders(opts, result)

+        // Silent handler that just updates the cache
+        const updateCacheOnly = {
+          onRequestStart () {},
+          onRequestUpgrade () {},
+          onResponseStart () {},
+          onResponseData () {},
+          onResponseEnd () {},
+          onResponseError () {}
+        }
+
+        // If the background 304 does not identify the same representation as
+        // the cached body (a mismatched ETag, or a newly added Vary field), the
+        // cached body must not be freshened or replayed. Discard it and
+        // re-fetch unconditionally so the cache reflects the origin's current
+        // representation instead of binding the old body to a foreign
+        // validator.
+        const backgroundRefetch = () => {
+          // Do not destroy result.body here. In the stale-while-revalidate
+          // path it is the stream already being delivered to the caller by
+          // sendCachedValue, which owns its lifecycle; destroying it would
+          // truncate the in-flight stale response. (The synchronous refetch
+          // below can destroy its result.body because there it is never served.)
+          deleteCachedValue(globalOpts.store, cacheKey)
+          // Like the revalidation, the re-fetch is not the caller's request.
+          dispatch({ ...opts, [kQueuedAbort]: undefined }, new CacheHandler(globalOpts, cacheKey, updateCacheOnly))
+        }
+
         // Background revalidation - update cache if we get new data
         dispatch(
           {
@@ -548,15 +552,11 @@ function handleResult (
             // caller must not cancel it while it waits for a connection.
             [kQueuedAbort]: undefined
           },
-          new CacheHandler(globalOpts, cacheKey, {
-            // Silent handler that just updates the cache
-            onRequestStart () {},
-            onRequestUpgrade () {},
-            onResponseStart () {},
-            onResponseData () {},
-            onResponseEnd () {},
-            onResponseError () {}
-          })
+          new CacheHandler(
+            { ...globalOpts, onInvalidRevalidation: backgroundRefetch },
+            cacheKey,
+            updateCacheOnly
+          )
         )
       })

@@ -592,7 +592,7 @@ function handleResult (
           if (success) {
             if (statusCode === 304) {
               if (
-                !revalidationTargetMatchesCacheKey(cacheKey, context) ||
+                !revalidationTargetMatchesCacheKey(cacheKey, context?.history) ||
                 !revalidationEtagMatchesCachedValue(result, headers) ||
                 revalidationResponseDisallowsCachedReuse(globalOpts.type, headers)
               ) {
@@ -717,6 +717,16 @@ module.exports = (opts = {}) => {
         return dispatch(opts, handler)
       }

+      // A Host header naming another authority targets a different URI than
+      // the cache key describes: neither look up, store nor invalidate.
+      if (!hostHeaderMatchesOrigin(opts.headers, requestOrigin)) {
+        if (reqCacheControl?.['only-if-cached'] && arrayIncludes(util.safeHTTPMethods, opts.method)) {
+          // Nothing is cached for this target, so answer like any other miss.
+          return handleUncachedResponse(dispatch, globalOpts, undefined, handler, opts, reqCacheControl)
+        }
+        return dispatch(opts, handler)
+      }
+
       /**
        * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
        */
diff --git a/deps/undici/src/lib/interceptor/dump.js b/deps/undici/src/lib/interceptor/dump.js
index 09b57f2163f..ded1cc2ac0a 100644
--- a/deps/undici/src/lib/interceptor/dump.js
+++ b/deps/undici/src/lib/interceptor/dump.js
@@ -51,7 +51,7 @@ class DumpHandler extends DecoratorHandler {
   }

   onResponseError (controller, err) {
-    super.onResponseError(controller, this.aborted === true ? this.reason : err)
+    super.onResponseError(controller, this.aborted === true ? (this.reason ?? err ?? new RequestAbortedError()) : err)
   }

   onResponseData (controller, chunk) {
@@ -72,7 +72,7 @@ class DumpHandler extends DecoratorHandler {

   onResponseEnd (controller, trailers) {
     if (this.aborted === true) {
-      super.onResponseError(controller, this.reason)
+      super.onResponseError(controller, this.reason ?? new RequestAbortedError())
       return
     }

diff --git a/deps/undici/src/lib/interceptor/redirect.js b/deps/undici/src/lib/interceptor/redirect.js
index d772100be9a..b3ef7263245 100644
--- a/deps/undici/src/lib/interceptor/redirect.js
+++ b/deps/undici/src/lib/interceptor/redirect.js
@@ -14,6 +14,9 @@ function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections, t

       const dispatchOpts = { ...rest, throwOnMaxRedirect, stripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect } // Stop sub dispatcher from also redirecting.
       const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler)
+      // Send the body the handler tracks, so it can tell when a body that
+      // cannot be replayed was consumed by this first hop.
+      dispatchOpts.body = redirectHandler.opts.body
       return dispatch(dispatchOpts, redirectHandler)
     }
   }
diff --git a/deps/undici/src/lib/interceptor/retry.js b/deps/undici/src/lib/interceptor/retry.js
index 1c16fd845a9..c1cbc6e607f 100644
--- a/deps/undici/src/lib/interceptor/retry.js
+++ b/deps/undici/src/lib/interceptor/retry.js
@@ -4,16 +4,17 @@ const RetryHandler = require('../handler/retry-handler')
 module.exports = globalOpts => {
   return dispatch => {
     return function retryInterceptor (opts, handler) {
-      return dispatch(
-        opts,
-        new RetryHandler(
-          { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
-          {
-            handler,
-            dispatch
-          }
-        )
+      const retryHandler = new RetryHandler(
+        { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
+        {
+          handler,
+          dispatch
+        }
       )
+      // Send the body the handler tracks, so it can tell when a body that
+      // cannot be replayed was consumed by this first attempt.
+      const { body } = retryHandler.opts
+      return dispatch(body === opts.body ? opts : { ...opts, body }, retryHandler)
     }
   }
 }
diff --git a/deps/undici/src/lib/util/cache.js b/deps/undici/src/lib/util/cache.js
index 9aabf188d55..439e97a20d7 100644
--- a/deps/undici/src/lib/util/cache.js
+++ b/deps/undici/src/lib/util/cache.js
@@ -15,8 +15,19 @@ const MAX_DELTA_SECONDS = 2147483647
 const RESTRICTIVE_DIRECTIVE_NAMES = ['no-store', 'private', 'no-cache']
 const kInvalidCacheControlDirectives = Symbol('invalid cache-control directives')

+// Optional whitespace (OWS) trimming per RFC 9110 §5.6.3. These run on
+// server-controlled header values, so they must stay linear: regexes such as
+// /[\t ]+$/ backtrack quadratically on a long internal whitespace run.
+function isOWS (code) {
+  return code === 0x20 || code === 0x09
+}
+
 function trimOWS (value) {
-  return value.replace(/^[\t ]+|[\t ]+$/g, '')
+  let start = 0
+  let end = value.length
+  while (start < end && isOWS(value.charCodeAt(start))) start++
+  while (end > start && isOWS(value.charCodeAt(end - 1))) end--
+  return start === 0 && end === value.length ? value : value.substring(start, end)
 }

 function arrayIncludes (array, value) {
@@ -30,11 +41,15 @@ function arrayIncludes (array, value) {
 }

 function trimOWSStart (value) {
-  return value.replace(/^[\t ]+/, '')
+  let start = 0
+  while (start < value.length && isOWS(value.charCodeAt(start))) start++
+  return start === 0 ? value : value.substring(start)
 }

 function trimOWSEnd (value) {
-  return value.replace(/[\t ]+$/, '')
+  let end = value.length
+  while (end > 0 && isOWS(value.charCodeAt(end - 1))) end--
+  return end === value.length ? value : value.substring(0, end)
 }

 function findUnescapedQuote (value, start) {
@@ -350,6 +365,59 @@ function assertCacheValue (value) {
   }
 }

+// Small body chunks are coalesced into bounded buffers before a cache store retains
+// them. A response body delivered as many tiny chunks (e.g. a single-byte HTTP/1.1
+// chunk per frame) would otherwise retain one `Buffer` object per chunk: the per-chunk
+// object overhead vastly exceeds the byte length counted against the store limits and
+// can exhaust the heap while those limits are still satisfied (GHSA-8GC2-Q8WW-GHWG).
+const COALESCE_THRESHOLD = 64 * 1024 // 64 KiB
+const COALESCE_MAX_CHUNKS = 1024
+
+/**
+ * Collects body chunks into `body`, coalescing small chunks so that the number of
+ * retained buffers is bounded by byte size, not chunk count. `flush()` must be
+ * called once the body is complete.
+ * @param {Buffer[]} body
+ * @returns {{ push: (chunk: Buffer) => void, flush: () => void }}
+ */
+function createBodyChunkCoalescer (body) {
+  let pendingChunks = []
+  let pendingSize = 0
+
+  const flush = () => {
+    if (pendingChunks.length === 1) {
+      body.push(pendingChunks[0])
+    } else if (pendingChunks.length > 1) {
+      body.push(Buffer.concat(pendingChunks, pendingSize))
+    }
+    pendingChunks = []
+    pendingSize = 0
+  }
+
+  const push = (chunk) => {
+    if (chunk.byteLength >= COALESCE_THRESHOLD) {
+      // Large chunks are forwarded as-is rather than copied.
+      flush()
+      body.push(chunk)
+    } else {
+      pendingChunks.push(chunk)
+      pendingSize += chunk.byteLength
+
+      // Flush once the accumulated bytes (or number of chunks) reaches a
+      // threshold. Bounding the chunk count keeps the transient pending set
+      // small even when every chunk is a single byte.
+      if (
+        pendingSize >= COALESCE_THRESHOLD ||
+        pendingChunks.length >= COALESCE_MAX_CHUNKS
+      ) {
+        flush()
+      }
+    }
+  }
+
+  return { push, flush }
+}
+
 /**
  * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-cache-control
  * @see https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml
@@ -518,7 +586,11 @@ function parseCacheControlHeader (header) {
               output[key] = true
             } else if (output[key] !== true) {
               if (key in output) {
-                output[key] = output[key].concat(headers)
+                // Append in place: concat() would copy the accumulated list on
+                // every repeated directive, which is quadratic.
+                for (let j = 0; j < headers.length; j++) {
+                  output[key].push(headers[j])
+                }
               } else {
                 output[key] = headers
               }
@@ -531,7 +603,7 @@ function parseCacheControlHeader (header) {
               output[key] = true
             } else if (output[key] !== true) {
               if (key in output) {
-                output[key] = output[key].concat(fieldName)
+                output[key].push(fieldName)
               } else {
                 output[key] = [fieldName]
               }
@@ -648,6 +720,80 @@ function isInvalidOrWildcardVaryHeader (varyHeader) {
   return hasVaryStar(varyHeader) || parseVaryHeader(varyHeader, {}) === undefined
 }

+/**
+ * Whether a revalidation response varies on a field the stored response did
+ * not vary on.
+ *
+ * @param {{ vary?: Record<string, string | string[] | null> }} cachedValue
+ * @param {Record<string, string | string[] | null> | undefined} varyDirectives
+ *  The revalidation response's parsed Vary
+ * @returns {boolean}
+ */
+function revalidationResponseAddsVary (cachedValue, varyDirectives) {
+  if (!varyDirectives) {
+    return false
+  }
+
+  for (const key in varyDirectives) {
+    if (cachedValue.vary == null || !Object.hasOwn(cachedValue.vary, key)) {
+      return true
+    }
+  }
+
+  return false
+}
+
+/**
+ * Whether a revalidation response's Vary adds or removes a field compared to
+ * the stored response. A response without Vary leaves the stored one as is.
+ *
+ * @param {{ vary?: Record<string, string | string[] | null> }} cachedValue
+ * @param {Record<string, string | string[] | null> | undefined} varyDirectives
+ *  The revalidation response's parsed Vary
+ * @returns {boolean}
+ */
+function revalidationResponseChangesVary (cachedValue, varyDirectives) {
+  if (!varyDirectives) {
+    return false
+  }
+
+  if (revalidationResponseAddsVary(cachedValue, varyDirectives)) {
+    return true
+  }
+
+  for (const key in cachedValue.vary) {
+    if (!Object.hasOwn(varyDirectives, key)) {
+      return true
+    }
+  }
+
+  return false
+}
+
+/**
+ * Whether a revalidation response was produced by the cached URL itself, not by
+ * a redirect target.
+ *
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
+ * @param {URL[] | undefined} history The URLs visited while following redirects
+ * @returns {boolean}
+ */
+function revalidationTargetMatchesCacheKey (cacheKey, history) {
+  if (!Array.isArray(history) || history.length === 0) {
+    return true
+  }
+
+  try {
+    const cachedUrl = new URL(cacheKey.path, cacheKey.origin)
+    const responseUrl = history[history.length - 1]
+    return responseUrl.origin === cachedUrl.origin &&
+      responseUrl.pathname === cachedUrl.pathname &&
+      responseUrl.search === cachedUrl.search
+  } catch {
+    return false
+  }
+}
+
 /**
  * Note: this deviates from the spec a little. Empty etags ("", W/"") are valid,
  *  however, including them in cached responses serves little to no purpose.
@@ -682,6 +828,40 @@ function isEtagUsable (etag) {
   return false
 }

+/**
+ * Whether a validating (304) response's ETag refers to the same selected
+ * representation as the cached value. A 304 may only freshen a stored response
+ * when it identifies the same representation (RFC 9111 §4.3.4); a mismatched
+ * validator must not be used to update freshness or metadata around an old body.
+ *
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} cachedValue
+ * @param {Record<string, string | string[] | null> | undefined} headers
+ * @returns {boolean}
+ */
+function revalidationEtagMatchesCachedValue (cachedValue, headers) {
+  if (!Object.hasOwn(headers ?? {}, 'etag')) {
+    return true
+  }
+
+  const responseEtag = headers.etag
+  const cachedEtag = cachedValue.etag
+  if (
+    typeof responseEtag !== 'string' ||
+    typeof cachedEtag !== 'string' ||
+    !isEtagUsable(responseEtag) ||
+    !isEtagUsable(cachedEtag)
+  ) {
+    return false
+  }
+
+  if (!responseEtag.startsWith('W/')) {
+    return responseEtag === cachedEtag
+  }
+
+  const cachedOpaqueTag = cachedEtag.startsWith('W/') ? cachedEtag.slice(2) : cachedEtag
+  return responseEtag.slice(2) === cachedOpaqueTag
+}
+
 /**
  * @param {unknown} store
  * @returns {asserts store is import('../../types/cache-interceptor.d.ts').default.CacheStore}
@@ -752,13 +932,19 @@ module.exports = {
   normalizeHeaders,
   assertCacheKey,
   assertCacheValue,
+  createBodyChunkCoalescer,
   parseCacheControlHeader,
   hasInvalidCacheControlDirective,
   parseVaryHeader,
   hasVaryStar,
+  revalidationResponseAddsVary,
+  revalidationResponseChangesVary,
+  revalidationTargetMatchesCacheKey,
   isInvalidOrWildcardVaryHeader,
   isEtagUsable,
+  revalidationEtagMatchesCachedValue,
   assertCacheMethods,
   assertCacheStore,
-  makeDeduplicationKey
+  makeDeduplicationKey,
+  trimOWS
 }
diff --git a/deps/undici/src/lib/web/eventsource/eventsource-stream.js b/deps/undici/src/lib/web/eventsource/eventsource-stream.js
index e5f38604873..26c6afb8a8a 100644
--- a/deps/undici/src/lib/web/eventsource/eventsource-stream.js
+++ b/deps/undici/src/lib/web/eventsource/eventsource-stream.js
@@ -207,7 +207,7 @@ class EventSourceStream extends Transform {
       // If the previous line ended with an end-of-line, we need to check
       // if the next character is also an end-of-line.
       if (this.eventEndCheck) {
-        // If the the current character is an end-of-line, then the event
+        // If the current character is an end-of-line, then the event
         // is finished and we can process it

         // If the previous line ended with a carriage return, we need to
diff --git a/deps/undici/src/package-lock.json b/deps/undici/src/package-lock.json
index 820433c9581..4078f0d13d5 100644
--- a/deps/undici/src/package-lock.json
+++ b/deps/undici/src/package-lock.json
@@ -1,12 +1,12 @@
 {
   "name": "undici",
-  "version": "8.14.0",
+  "version": "8.14.1",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "undici",
-      "version": "8.14.0",
+      "version": "8.14.1",
       "license": "MIT",
       "devDependencies": {
         "@fastify/busboy": "3.2.6",
@@ -1131,9 +1131,9 @@
       }
     },
     "node_modules/@eslint/config-array": {
-      "version": "0.23.6",
-      "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz",
-      "integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==",
+      "version": "0.23.7",
+      "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.7.tgz",
+      "integrity": "sha512-Ix1tmZjA7/OmE7ROAfORe83hVnqlDzLpZVHFjHQt5mvLm1U03qMexpaxKqFIL362QV32SoPaZqmKQr3tdqFY2w==",
       "dev": true,
       "license": "Apache-2.0",
       "dependencies": {
@@ -1146,9 +1146,9 @@
       }
     },
     "node_modules/@eslint/config-array/node_modules/minimatch": {
-      "version": "11.0.8",
-      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz",
-      "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==",
+      "version": "11.0.9",
+      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
+      "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
       "dev": true,
       "license": "BlueOak-1.0.0",
       "dependencies": {
@@ -4268,9 +4268,9 @@
       }
     },
     "node_modules/cross-spawn": {
-      "version": "7.0.6",
-      "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
-      "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+      "version": "7.1.2",
+      "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.1.2.tgz",
+      "integrity": "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==",
       "dev": true,
       "license": "MIT",
       "dependencies": {
@@ -4566,9 +4566,9 @@
       }
     },
     "node_modules/eslint": {
-      "version": "10.15.0",
-      "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz",
-      "integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==",
+      "version": "10.16.0",
+      "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.16.0.tgz",
+      "integrity": "sha512-Xu3PRLG/wCaZWZ20gkExUcNqL2mWWsXTR+Lln3Sof4Y9WuA678fH9hrlQ8B6UNwbTnsKdDdBYOd2jxtycXVTGQ==",
       "dev": true,
       "license": "MIT",
       "workspaces": [
@@ -4577,7 +4577,7 @@
       "dependencies": {
         "@eslint-community/eslint-utils": "^4.8.0",
         "@eslint-community/regexpp": "^4.12.2",
-        "@eslint/config-array": "^0.23.6",
+        "@eslint/config-array": "^0.23.7",
         "@eslint/config-helpers": "^0.7.0",
         "@eslint/core": "^1.2.1",
         "@eslint/plugin-kit": "^0.7.3",
@@ -5138,9 +5138,9 @@
       }
     },
     "node_modules/fast-check": {
-      "version": "4.10.3",
-      "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.3.tgz",
-      "integrity": "sha512-SBaU6nhh+sXxb05r2IHAKfxnR/1Pu6MqtHYaewM1BY6V5xzOxOk+4yoWO7WfeeyZG1iArFE6/DO/7iLYMUuOJg==",
+      "version": "4.11.0",
+      "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.11.0.tgz",
+      "integrity": "sha512-V4Uc238rhQOdQlc+Gz7JG6SGBtrWnWL8d/6RyiBeCMcNKMhF6DZ0KkAVHJSyNV5r4lA0PmIpZ6iRpTVoz4qjoA==",
       "dev": true,
       "funding": [
         {
@@ -7221,9 +7221,9 @@
       "license": "MIT"
     },
     "node_modules/node-forge": {
-      "version": "1.4.3",
-      "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz",
-      "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==",
+      "version": "1.4.4",
+      "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.4.tgz",
+      "integrity": "sha512-T6VRRpF3+czIGcXW/LOeoD7Ej28d8CF1UMEAbJyJRUtYMvyXAgxUPW2kbUibumvV9LiUQAznJOFyeYclzSJMMg==",
       "dev": true,
       "license": "(BSD-3-Clause OR GPL-2.0)",
       "engines": {
@@ -9058,9 +9058,9 @@
       }
     },
     "node_modules/ws": {
-      "version": "8.23.0",
-      "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
-      "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
+      "version": "8.23.1",
+      "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz",
+      "integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==",
       "dev": true,
       "license": "MIT",
       "engines": {
diff --git a/deps/undici/src/package.json b/deps/undici/src/package.json
index 64d9987eae2..861e4d24d92 100644
--- a/deps/undici/src/package.json
+++ b/deps/undici/src/package.json
@@ -1,6 +1,6 @@
 {
   "name": "undici",
-  "version": "8.14.0",
+  "version": "8.14.1",
   "description": "An HTTP/1.1 client, written from scratch for Node.js",
   "homepage": "https://undici.nodejs.org",
   "bugs": {
diff --git a/deps/undici/src/types/client.d.ts b/deps/undici/src/types/client.d.ts
index 80ff8f21ab6..23d93ee7132 100644
--- a/deps/undici/src/types/client.d.ts
+++ b/deps/undici/src/types/client.d.ts
@@ -58,7 +58,7 @@ export declare namespace Client {
     maxKeepAliveTimeout?: never;
     /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
     keepAliveMaxTimeout?: number;
-    /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
+    /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `2e3` milliseconds (2s). */
     keepAliveTimeoutThreshold?: number;
     /** An IPC endpoint, either a Unix domain socket or Windows named pipe. Default: `null`. */
     socketPath?: string;
@@ -112,7 +112,7 @@ export declare namespace Client {
     /**
      * @description Time interval between PING frames dispatch
      * @default 60000
-     * @deprecated Use h2Options.connectionWindowSize instead
+     * @deprecated Use h2Options.pingInterval instead
      */
     pingInterval?: number;
     /**
diff --git a/deps/undici/src/types/dispatcher.d.ts b/deps/undici/src/types/dispatcher.d.ts
index 86f51f409cb..b2f7ad6a799 100644
--- a/deps/undici/src/types/dispatcher.d.ts
+++ b/deps/undici/src/types/dispatcher.d.ts
@@ -123,6 +123,8 @@ declare namespace Dispatcher {
     reset?: boolean;
     /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server */
     expectContinue?: boolean;
+    /** The TLS server name (SNI) used for this request on `https:` origins. Defaults to the hostname of the `host` header. A client reconnects when the server name of the next queued request differs from the current connection's. */
+    servername?: string;
   }
   export interface ConnectOptions<TOpaque = null> {
     origin: string | URL;
diff --git a/deps/undici/src/types/h2c-client.d.ts b/deps/undici/src/types/h2c-client.d.ts
index 331cc1d71b4..a7f0694a423 100644
--- a/deps/undici/src/types/h2c-client.d.ts
+++ b/deps/undici/src/types/h2c-client.d.ts
@@ -40,11 +40,11 @@ export declare namespace H2CClient {
     keepAliveTimeout?: number;
     /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
     keepAliveMaxTimeout?: number;
-    /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
+    /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `2e3` milliseconds (2s). */
     keepAliveTimeoutThreshold?: number;
     /** An IPC endpoint, either a Unix domain socket or Windows named pipe. Default: `null`. */
     socketPath?: string;
-    /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */
+    /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `100`. */
     pipelining?: number;
     /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */
     strictContentLength?: boolean;
diff --git a/deps/undici/undici.js b/deps/undici/undici.js
index 55eaae3423b..4286f32df08 100644
--- a/deps/undici/undici.js
+++ b/deps/undici/undici.js
@@ -589,6 +589,7 @@ var require_symbols = __commonJS({
       kQueued: /* @__PURE__ */ Symbol("queued"),
       kFree: /* @__PURE__ */ Symbol("free"),
       kConnected: /* @__PURE__ */ Symbol("connected"),
+      kHasConnectedClient: /* @__PURE__ */ Symbol("has connected client"),
       kClosed: /* @__PURE__ */ Symbol("closed"),
       kNeedDrain: /* @__PURE__ */ Symbol("need drain"),
       kReset: /* @__PURE__ */ Symbol("reset"),
@@ -834,7 +835,7 @@ var require_dispatcher_base = __commonJS({
       ClientClosedError,
       InvalidArgumentError
     } = require_errors();
-    var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
+    var { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kConnected, kHasConnectedClient } = require_symbols();
     var { defaultWebSocketMaxFragments, defaultWebSocketMaxPayloadSize } = require_constants();
     var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed");
     var kOnClosed = /* @__PURE__ */ Symbol("onClosed");
@@ -885,6 +886,14 @@ var require_dispatcher_base = __commonJS({
       get closed() {
         return this[kClosed];
       }
+      /**
+       * Whether at least one client is connected. Dispatchers that hold more than
+       * one client can answer this without counting all of them.
+       * @returns {boolean}
+       */
+      get [kHasConnectedClient]() {
+        return this[kConnected] > 0;
+      }
       close(callback) {
         if (callback === void 0) {
           return new Promise((resolve, reject) => {
@@ -1522,7 +1531,9 @@ var require_util = __commonJS({
     }
     __name(noop, "noop");
     function wrapRequestBody(body) {
-      if (isStream(body)) {
+      if (body instanceof BodyAsyncIterable || Array.isArray(body)) {
+        return body;
+      } else if (isStream(body)) {
         if (bodyLength(body) === 0) {
           body.on("data", function() {
             assert(false);
@@ -5471,7 +5482,7 @@ var require_pool_base = __commonJS({
     var { PoolStats } = require_stats();
     var DispatcherBase = require_dispatcher_base();
     var FixedQueue = require_fixed_queue();
-    var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require_symbols();
+    var { kConnected, kHasConnectedClient, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require_symbols();
     var { createAbortedController } = require_request();
     var kClients = /* @__PURE__ */ Symbol("clients");
     var kNeedDrain = /* @__PURE__ */ Symbol("needDrain");
@@ -5639,6 +5650,16 @@ var require_pool_base = __commonJS({
       get [kBusy]() {
         return this[kNeedDrain];
       }
+      // A pool can hold one client per open response, so stop at the first
+      // connected client instead of counting all of them.
+      get [kHasConnectedClient]() {
+        for (let i = 0; i < this[kClients].length; i++) {
+          if (this[kClients][i][kConnected]) {
+            return true;
+          }
+        }
+        return false;
+      }
       get [kConnected]() {
         let ret = 0;
         for (const { [kConnected]: connected } of this[kClients]) {
@@ -7847,10 +7868,6 @@ var require_client_h1 = __commonJS({
         if (this.statusCode >= 200) {
           const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout];
           this.setTimeout(bodyTimeout, TIMEOUT_BODY);
-        } else if (this.timeout) {
-          if (this.timeout.refresh) {
-            this.timeout.refresh();
-          }
         }
         if (request.method === "CONNECT") {
           assert(client[kRunning] === 1);
@@ -8738,7 +8755,9 @@ var require_client_h2 = __commonJS({
       kHTTP2Stream,
       kHTTP2SessionState,
       kHTTP2Options,
-      kMaxResponseSize
+      kMaxResponseSize,
+      kMaxRequests,
+      kCounter
     } = require_symbols();
     var { channels } = require_diagnostics();
     var kOpenStreams = /* @__PURE__ */ Symbol("open streams");
@@ -8873,6 +8892,24 @@ var require_client_h2 = __commonJS({
       return attempts <= MAX_GOAWAY_REPLAY_ATTEMPTS;
     }
     __name(registerGoAwayRefusal, "registerGoAwayRefusal");
+    function refuseHeldRequests(client, err) {
+      const queue = client[kQueue];
+      const failed = [];
+      let j = client[kPendingIdx];
+      for (let i = client[kPendingIdx]; i < queue.length; i++) {
+        const request = queue[i];
+        if (request != null && !registerGoAwayRefusal(request)) {
+          failed.push(request);
+        } else {
+          queue[j++] = request;
+        }
+      }
+      queue.length = j;
+      for (let i = 0; i < failed.length; i++) {
+        util.errorRequest(client, failed[i], err);
+      }
+    }
+    __name(refuseHeldRequests, "refuseHeldRequests");
     function closeStream(stream, code = NGHTTP2_REFUSED_STREAM) {
       if (stream != null && !stream.destroyed && !stream.closed) {
         try {
@@ -8930,6 +8967,8 @@ var require_client_h2 = __commonJS({
         // Armed while a PING checks whether the peer is still there after a
         // stream timed out. See probeHttp2Session.
         probeTimeout: null,
+        // Stop opening streams once this session reaches its request limit.
+        retiring: false,
         // Sockets start out ref'd. Session ref/unref proxies to the socket, so a
         // single cached flag lets us skip redundant uv ref/unref calls, provided
         // every ref/unref of the session or its socket goes through
@@ -8999,6 +9038,9 @@ var require_client_h2 = __commonJS({
          * @returns {boolean}
         */
         busy(request) {
+          if (session[kHTTP2SessionState].retiring) {
+            return true;
+          }
           if (session[kRemoteSettings] === false) {
             if (request == null) {
               if (client[kSize] > 0) return true;
@@ -9044,6 +9086,7 @@ var require_client_h2 = __commonJS({
       const socket = client[kSocket];
       const session = client[kHTTP2Session];
       if (socket?.destroyed === false) {
+        const { retiring } = session[kHTTP2SessionState];
         if (session[kOpenStreams] === 0 && client[kSize] === 0) {
           unrefH2Session(session);
         } else {
@@ -9054,7 +9097,7 @@ var require_client_h2 = __commonJS({
         } else {
           clearHttp2IdleTimeout(session);
         }
-        if (client[kMaxConcurrentStreams] === 0 && client[kRunning] === 0 && client[kPending] > 0) {
+        if (!retiring && client[kMaxConcurrentStreams] === 0 && client[kRunning] === 0 && client[kPending] > 0) {
           setNoStreamsTimeout(session);
         } else {
           clearNoStreamsTimeout(session);
@@ -9258,6 +9301,7 @@ var require_client_h2 = __commonJS({
       this[kReceivedGoAway] = true;
       const err = getGoAwayError(this, errorCode);
       const client = this[kClient];
+      const held = client[kRunning] === 0 && !this[kHTTP2SessionState]?.retiring;
       const previousPendingIdx = client[kPendingIdx];
       const pendingIdx = getGoAwayPendingIdx(client, lastStreamID);
       const retriableRequests = [];
@@ -9297,6 +9341,9 @@ var require_client_h2 = __commonJS({
       if (!this.closed && !this.destroyed) {
         this.close();
       }
+      if (held) {
+        refuseHeldRequests(client, err);
+      }
       client.emit("disconnect", client[kUrl], [client], err);
       client[kResume]();
     }
@@ -9343,8 +9390,12 @@ var require_client_h2 = __commonJS({
         client[kHTTP2Session] = null;
       }
       session.destroy(err);
+      const held = !session[kHTTP2SessionState].retiring && client[kRunning] === 0;
       client[kPendingIdx] = client[kRunningIdx];
       assert(client[kRunning] === 0);
+      if (held) {
+        refuseHeldRequests(client, err);
+      }
       client.emit("disconnect", client[kUrl], [client], err);
       client[kResume]();
     }
@@ -9358,7 +9409,7 @@ var require_client_h2 = __commonJS({
     }
     __name(onHttp2SocketError, "onHttp2SocketError");
     function onHttp2SocketEnd() {
-      util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
+      util.destroy(this, this[kError] ?? new SocketError("other side closed", util.getSocketInfo(this)));
     }
     __name(onHttp2SocketEnd, "onHttp2SocketEnd");
     function onSocketClose() {
@@ -9373,6 +9424,10 @@ var require_client_h2 = __commonJS({
       const client = session[kClient];
       stream[kHTTP2Session] = null;
       session[kOpenStreams] -= 1;
+      if (session[kOpenStreams] === 0 && session[kHTTP2SessionState].retiring && client[kHTTP2Session] === session && !session[kReceivedGoAway] && !session.closed && !session.destroyed) {
+        session[kSocket][kError] ??= new InformationalError("max requests per client reached");
+        session.close();
+      }
       if (session[kOpenStreams] === 0 && (client[kSize] === 0 || session[kReceivedGoAway])) {
         unrefH2Session(session);
         setHttp2IdleTimeout(session);
@@ -9540,7 +9595,12 @@ var require_client_h2 = __commonJS({
     __name(finalizeRequest, "finalizeRequest");
     function openStream(client, request, session, abort, headers, options) {
       try {
-        return session.request(headers, options);
+        const stream = session.request(headers, options);
+        const socket = session[kSocket];
+        if (socket[kMaxRequests] && ++socket[kCounter] >= socket[kMaxRequests]) {
+          session[kHTTP2SessionState].retiring = true;
+        }
+        return stream;
       } catch (err) {
         if (err?.code === "ERR_HTTP2_INVALID_SESSION" || err?.code === "ERR_HTTP2_GOAWAY_SESSION") {
           const wrappedErr2 = new SocketError(err.message, util.getSocketInfo(session[kSocket]));
@@ -11062,7 +11122,7 @@ var require_agent = __commonJS({
   "lib/dispatcher/agent.js"(exports2, module2) {
     "use strict";
     var { InvalidArgumentError, MaxOriginsReachedError } = require_errors();
-    var { kBusy, kClients, kConnected, kRunning, kPending, kClose, kDestroy, kDispatch, kUrl } = require_symbols();
+    var { kBusy, kClients, kHasConnectedClient, kRunning, kPending, kClose, kDestroy, kDispatch, kUrl } = require_symbols();
     var DispatcherBase = require_dispatcher_base();
     var Pool = require_pool();
     var Client = require_client();
@@ -11142,7 +11202,7 @@ var require_agent = __commonJS({
             if (this[kClients].get(key) !== dispatcher) {
               return;
             }
-            if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
+            if (dispatcher[kHasConnectedClient] || dispatcher[kBusy]) {
               return;
             }
             if (dispatcher[kPending] > 0) {
@@ -11910,7 +11970,7 @@ var require_socks5_proxy_agent = __commonJS({
     var { ConnectTimeoutError, InvalidArgumentError } = require_errors();
     var { Socks5Client, STATES } = require_socks5_client();
     var { stripIPv6Brackets } = require_socks5_utils();
-    var { kBusy, kConnected, kDispatch, kClose, kDestroy } = require_symbols();
+    var { kBusy, kHasConnectedClient, kDispatch, kClose, kDestroy } = require_symbols();
     var Pool = require_pool();
     var buildConnector = require_connect();
     var { setupConnectTimeout, getServerName } = require_util();
@@ -12130,7 +12190,7 @@ var require_socks5_proxy_agent = __commonJS({
             });
             this[kPools].set(originKey, pool);
             const closePoolIfUnused = /* @__PURE__ */ __name(() => {
-              if (this[kPools].get(originKey) !== pool || pool[kConnected] > 0 || pool[kBusy]) {
+              if (this[kPools].get(originKey) !== pool || pool[kHasConnectedClient] || pool[kBusy]) {
                 return;
               }
               this[kPools].delete(originKey);
@@ -12291,7 +12351,7 @@ var require_proxy_agent = __commonJS({
         this[kProxy] = { uri: href, protocol };
         this[kRequestTls] = opts.requestTls;
         this[kProxyTls] = opts.proxyTls;
-        this[kProxyHeaders] = opts.headers || {};
+        this[kProxyHeaders] = { ...opts.headers };
         this[kTunnelProxy] = proxyTunnel;
         if (opts.auth && opts.token) {
           throw new InvalidArgumentError("opts.auth cannot be used in combination with opts.token");
@@ -12538,16 +12598,22 @@ var require_env_http_proxy_agent = __commonJS({
         super(opts);
         this.#opts = opts;
         const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts;
-        this[kNoProxyAgent] = new Agent(agentOpts);
+        const { connect, tls, requestTls } = agentOpts;
+        const connectOpts = typeof connect === "function" ? void 0 : connect;
+        const tlsOpts = typeof tls === "object" ? tls : void 0;
+        this[kNoProxyAgent] = new Agent(
+          requestTls && typeof connect !== "function" ? { ...agentOpts, connect: { ...requestTls, ...connect } } : agentOpts
+        );
+        const proxyOpts = connectOpts || tlsOpts ? { ...agentOpts, requestTls: { ...tlsOpts, ...requestTls, ...connectOpts } } : agentOpts;
         const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
         if (HTTP_PROXY) {
-          this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY });
+          this[kHttpProxyAgent] = new ProxyAgent({ ...proxyOpts, uri: HTTP_PROXY });
         } else {
           this[kHttpProxyAgent] = this[kNoProxyAgent];
         }
         const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY;
         if (HTTPS_PROXY) {
-          this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY });
+          this[kHttpsProxyAgent] = new ProxyAgent({ ...proxyOpts, uri: HTTPS_PROXY });
         } else {
           this[kHttpsProxyAgent] = this[kHttpProxyAgent];
         }
@@ -18361,11 +18427,15 @@ var require_readable = __commonJS({
        * @returns {void}
        */
       _destroy(err, callback) {
-        if (!err && !this._readableState.endEmitted) {
+        const synthesized = !err && !this._readableState.endEmitted;
+        if (synthesized) {
           err = new RequestAbortedError();
         }
         if (err) {
-          this[kAbort]();
+          this[kAbort](err);
+        }
+        if (synthesized && this.listenerCount("error") === 0) {
+          this.once("error", noop);
         }
         if (!this[kUsed]) {
           setImmediate(callback, err);
@@ -18420,7 +18490,7 @@ var require_readable = __commonJS({
       push(chunk) {
         if (chunk) {
           this[kBytesRead] += chunk.length;
-          if (this[kConsume]) {
+          if (this[kConsume]?.started) {
             consumePush(this[kConsume], chunk);
             return this[kReading] ? super.push(chunk) : true;
           }
@@ -18573,7 +18643,6 @@ var require_readable = __commonJS({
     }
     __name(isUnusable, "isUnusable");
     function consume(stream, type) {
-      assert(!stream[kConsume]);
       return new Promise((resolve, reject) => {
         if (isUnusable(stream)) {
           const rState = stream._readableState;
@@ -18585,15 +18654,17 @@ var require_readable = __commonJS({
             reject(rState.errored ?? new TypeError("unusable"));
           }
         } else {
+          stream[kConsume] = {
+            type,
+            stream,
+            resolve,
+            reject,
+            length: 0,
+            body: [],
+            started: false
+          };
           queueMicrotask(() => {
-            stream[kConsume] = {
-              type,
-              stream,
-              resolve,
-              reject,
-              length: 0,
-              body: []
-            };
+            stream[kConsume].started = true;
             stream.on("error", function(err) {
               consumeFinish(this[kConsume], err);
             }).on("close", function() {
@@ -18980,7 +19051,9 @@ var require_api_request = __commonJS({
         if (res) {
           this.res = null;
           queueMicrotask(() => {
-            util.destroy(res.on("error", noop), err);
+            if (!util.isDestroyed(res)) {
+              util.destroy(res.on("error", noop), err);
+            }
           });
         }
         if (body) {
@@ -19121,6 +19194,7 @@ var require_api_stream = __commonJS({
         this.trailers = null;
         this.body = body;
         this.onInfo = onInfo || null;
+        this.responseStarted = false;
         if (util.isStream(body)) {
           body.on("error", (err) => {
             this.onResponseError(this.controller, err);
@@ -19168,11 +19242,14 @@ var require_api_stream = __commonJS({
             util.destroy(res2, fromErrorEvent ? void 0 : err);
           }
           this.callback = null;
-          this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers });
+          if (callback) {
+            this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers });
+          }
           if (err) {
             abort(err);
           }
         });
+        this.responseStarted = true;
         res.on("drain", () => controller.resume());
         this.res = res;
         const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain;
@@ -19207,7 +19284,7 @@ var require_api_stream = __commonJS({
         if (res) {
           this.res = null;
           util.destroy(res, err);
-        } else if (callback) {
+        } else if (callback && !this.responseStarted) {
           this.callback = null;
           queueMicrotask(() => {
             this.runInAsyncScope(callback, null, err, { opaque });
diff --git a/src/undici_version.h b/src/undici_version.h
index d1ca15c7924..a33b2a83ec9 100644
--- a/src/undici_version.h
+++ b/src/undici_version.h
@@ -2,5 +2,5 @@
 // Refer to tools/dep_updaters/update-undici.sh
 #ifndef SRC_UNDICI_VERSION_H_
 #define SRC_UNDICI_VERSION_H_
-#define UNDICI_VERSION "8.14.0"
+#define UNDICI_VERSION "8.14.1"
 #endif  // SRC_UNDICI_VERSION_H_