The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // TODO: stopgap. Node 26's fetch (undici 8) negotiates HTTP/2 and the engine's |
| 2 | // unbounded fan-out onto one session got streams reset by Cloudflare. This |
| 3 | // copies the dispatcher wrap from huggingface.js (#2495) and OriginTrail/dkg |
| 4 | // (#2830). Revisit once undici's HTTP/2 path settles: either drop this, or |
| 5 | // replace it with request pacing driven by Cloudflare's `ratelimit` headers so |
| 6 | // the engine stops leaning on transport quirks to stay under the API limits. |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as Layer from "effect/Layer"; |
| 11 | |
| 12 | type Dispatch = (options: Record<string, unknown>, handler: unknown) => boolean; |
| 13 | interface Dispatcher { |
| 14 | compose(interceptor: (dispatch: Dispatch) => Dispatch): Dispatcher; |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Node 26 bundles undici 8, whose `fetch` negotiates HTTP/2 by default and |
| 19 | * funnels every concurrent request onto one session — which undici's |
| 20 | * HTTP/2 path has been resetting under load. Wrap Node's own global |
| 21 | * dispatcher (the npm `undici` package would mismatch the bundled major) |
| 22 | * so each request carries `allowH2: false`. `undefined` on Bun, on older |
| 23 | * Node, or if the slot can't be found — plain `fetch` as before. |
| 24 | */ |
| 25 | const resolveHttp1Dispatcher = async () => { |
| 26 | if ("Bun" in globalThis || Number.parseInt(process.versions.undici ?? "0", 10) < 8) return; |
| 27 | const slot = Symbol.for("undici.globalDispatcher.2"); |
| 28 | const lookup = () => (globalThis as Record<symbol, Dispatcher | undefined>)[slot]; |
| 29 | let base = lookup(); |
| 30 | if (base === undefined) { |
| 31 | // undici creates the dispatcher lazily on first fetch; `data:` never hits the network. |
| 32 | await fetch("data:,").catch(() => {}); |
| 33 | base = lookup(); |
| 34 | } |
| 35 | return base?.compose( |
| 36 | (dispatch) => (options, handler) => dispatch({ ...options, allowH2: false }, handler), |
| 37 | ); |
| 38 | }; |
| 39 | |
| 40 | /** The ambient `HttpClient`, forced onto HTTP/1.1 where `fetch` would negotiate HTTP/2. */ |
| 41 | export const Http1FetchHttpClient = Layer.effect( |
| 42 | HttpClient.HttpClient, |
| 43 | Effect.gen(function* () { |
| 44 | const base = yield* HttpClient.HttpClient; |
| 45 | const dispatcher = yield* Effect.promise(resolveHttp1Dispatcher); |
| 46 | if (dispatcher === undefined) return base; |
| 47 | return HttpClient.transform(base, (effect) => |
| 48 | Effect.provideService(effect, FetchHttpClient.RequestInit, { dispatcher } as RequestInit), |
| 49 | ); |
| 50 | }), |
| 51 | ); |