Skip to content

fix(ai): apply HTTP timeouts to all requests - #64692

Merged
rekram1-node merged 3 commits into
devfrom
ai-request-timeouts
Nov 18, 2026
Merged

rekram1-node merged 3 commits into
devfrom
ai-request-timeouts

Conversation

@rekram1-node

@rekram1-node rekram1-node commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Every HTTP request @opencode/ai makes now has a timeout, and a timeout set on a provider or in opencode.json reaches every model type, not just chat.

Before, chat requests were the only ones with a timeout. Media requests (image, video, speech, transcription), embeddings, decisions, compaction, realtime and Media.url downloads had none. Opencode turns off Bun's own fetch timeout, so one stalled provider could hang a call forever. A configured timeout was also dropped on every non-chat model.

How it works

Two primitives replace the per-route code:

  1. RequestExecutor applies the timeouts. Lint already forces every HTTP call through route/executor.ts, so this covers every request, including error bodies:

    execute(request)
      waiting for headers        ≤ min(timeout.headers ?? 5 min, timeout.total)
      body re-wrapped behind     timeout.chunk ?? 15 min between chunks, and the timeout.total deadline
      → HttpClientResponse.fromWeb(request, new Response(timedBody, { status, headers }))
    

    Re-wrapping the body means every reader (stream, text, json, formData, …) is bounded without re-implementing any of them. A stalled body fails as a retryable TransportError with code: "Timeout". responseStream, responseText and responseBytes turn read failures into the same error everywhere.

  2. One transport bundle per model. Media, decision and embedding models carry transport: { headers, timeout, http }, which mirrors the options that chat models already carry. mergeTransport is the only place that knows the fields:

    - .with({ headers: input.headers, http: input.http })   // repeated across ~25 provider files
    + .with({ ...mergeTransport(input) })

    Routes merge their settings with mergeTransport(route, patch). Requests merge model.transport under their own settings, including job status, result, cancel and resume calls.

ModelResolver in packages/core/src/model-resolver.ts applies the timeout settings from opencode.json to image, video and decision models, the same way it does for chat. It also applies the client certificate (tls) to video models, which only image and decision models got before.

Trade-offs

  • Breaking for experimental @opencode/ai media models. The http field on media, decision and embedding models moves into transport. Deployment headers on MediaRoute.ModelInput move there too. Decision and embedding route patches now merge http overlays instead of replacing them, which is how chat already behaves. Nothing in core reads the old fields.
  • The re-wrapped body costs an extra stream copy. Every timed response pipes through one more ReadableStream. The response's url is empty after re-wrapping. Nothing reads it; responseHttp uses request.url.
  • Polling tests now give the request time to start. Every request now races a header timer. Four polling tests used to advance the test clock before their request had started, so they now let it start first (test/lib/http.ts, test/video.test.ts, test/transcription.test.ts).

Guardrail

packages/ai/test/http-timeout.test.ts lists every method on ai and fails when a new one isn't covered. It checks that a provider-configured timeout applies to each method and to Realtime.connect.

Verification

  • bun run check from the repo root: lint, ast-grep, sdk-docs and typecheck across all 35 packages
  • bun run typecheck:tsc in packages/ai and packages/core
  • bun test in packages/ai: 2,267 pass, 0 fail
  • bun test test/http-timeout.test.ts test/executor.test.ts --rerun-each 10 in packages/ai: no failures
  • bun run script/test.ts test/model-resolver.test.ts test/video-generation.test.ts test/tool-image-generate.test.ts test/voice.test.ts in packages/core: 68 pass

Added by the opencode bot (AI-generated).

Public API: media/decision/embedding models: http → transport: { headers, timeout, http }; provider configure timeouts apply to all modalities (breaking for experimental @opencode/ai media callers)

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found no blocking problems. On the base, the new timeout tests (media route headers and body, Media.url downloads, compaction) hang; with this PR they fail cleanly with Transport/Timeout errors. The full packages/ai suite passes, typecheck:tsc is clean and the related packages/core tests pass. Moving the timeouts into RequestExecutor is the right layer.

Public API:

  • Additions to RequestExecutor (@opencode/ai/route): CurrentTimeout, withTimeout, responseText and responseBytes.
  • Behaviour changes:
    • TransportOptions.timeout now applies to media, compaction and decision requests.
    • Media, realtime and Media.url download requests now get the default 5 min header and 15 min chunk limits; before, they had no limit.
    • Body-read failures on those paths now fail as a retryable TransportError instead of InvalidProviderOutputError.
  • Compatibility: no signatures change. Only callers that branch on the error tag of media read failures would notice.

One test concern is noted inline: the polling tests now depend on real time.

yield* TestClock.adjust(`${seconds} seconds`)
const fiber = yield* Effect.forkChild(program, { startImmediately: true })
for (let i = 0; i < seconds && fiber.pollUnsafe() === undefined; i++) {
yield* TestClock.withLive(Effect.sleep("1 millis"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This 1 ms real-time sleep (here and in video.test.ts) assumes the forked request handler has set up its next Effect.sleep within 1 ms of wall-clock time before the TestClock moves. On a loaded CI machine the handler may not be ready yet, so the clock moves past its timer and polling and retry ticks get skipped. Because settle only runs seconds iterations, one missed tick can fail the test. Could these tests wait on something they can observe instead, such as a Deferred completed by the handler or the recorded calls count, and adjust the clock after that? That would keep them independent of real time.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I re-reviewed the new commits and found nothing that would block a merge. Configured timeouts now reach every media, decision, embedding and extraction model, provider configure(...) and Realtime.connect. In packages/core, ModelResolver applies the provider's timeout settings to image, video and decision models, the same way it does for chat models. bun test and typecheck:tsc pass in packages/ai, and typecheck:tsc and model-resolver.test.ts pass in packages/core.

My earlier point about the real-time sleep in settle (test/lib/http.ts, and the same line in video.test.ts) is not addressed yet.

Public API:

  • Additions: an optional timeout field on MediaModel, the decision and embedding route Patch/Route, MediaRoute.ModelInput/deployment, MediaRequest's model and RealtimeConnectInput.
  • Behaviour change: the provider configure({ timeout }) now also applies to non-chat models.
  • Compatibility: existing callers don't need to change. Users with provider timeouts in opencode.json will now see them enforced on image, video and decision models too.

One new test concern is noted inline: the every-method test lets unsupported calls pass without checking a timeout.

// the 5 min default header timeout), so finishing here proves the 1 s configured timeout applied.
for (let i = 0; i < 240 && fiber.pollUnsafe() === undefined; i++) yield* TestClock.adjust("1 second")
const error = yield* Fiber.join(fiber)
if (error.reason._tag === "UnsupportedOperation") return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This early return means any ai method a provider doesn't support (for example image.start/status/result/cancel on OpenAI) passes without any timeout being checked, yet the method list above still counts it as covered. Could those methods use a provider that supports them, or could the test at least list which ones are expected to be unsupported, so a method that stops reaching the executor can't pass silently?

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Neither of my two earlier test points is addressed yet: the real-time sleep in settle (and in video.test.ts), and the UnsupportedOperation early return in the every-method test. I found nothing new that blocks the change.

Replacing the custom response wrapper with HttpClientResponse.fromWeb around the timed body is simpler. Cancelling the new body still cancels the underlying response body, and responses with no body (101, 204, 205, 304) are left as they are.

The new commits delete the test for default media timeouts and stalled media and download bodies. That test still passes against this code, but now only the header timeout is checked on media and Media.url downloads. One small stalled-body case would be worth keeping.

Tests and typecheck:tsc pass in packages/ai and packages/core.

Public API: this breaks existing callers of the experimental @opencode/ai media API.

  • The http field on media, decision and embedding models moves into transport: { headers, timeout, http }.
  • Deployment headers on MediaRoute.ModelInput move into the same transport field.
  • Decision and embedding route patches now merge http settings instead of replacing them.

Code that reads model.http must read model.transport.http instead. Core reads none of the old fields.

@rekram1-node
rekram1-node merged commit 73215c5 into dev Nov 18, 2026
14 checks passed
@rekram1-node
rekram1-node deleted the ai-request-timeouts branch November 18, 2026 17:55
@amrkmn amrkmn mentioned this pull request Nov 23, 2026
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant