Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions packages/core/src/websearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { HttpClientError } from "effect/http"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import { Bus } from "./bus.js"
import { KV } from "./kv.js"
import { WebSearchMcp } from "./plugin/websearch/mcp.js"
import { State } from "./state.js"

export const ID = WebSearch.ID
Expand Down Expand Up @@ -210,10 +211,10 @@ const layer = Layer.effect(
if (result._tag === "Success") return new Response({ providerID: provider.id, results: result.success })
const cause = result.failure
const error = new RequestError({ providerID: provider.id, cause })
if (choice !== "random" || !HttpClientError.isHttpClientError(cause) || cause.response?.status !== 429)
return yield* error
const now = yield* Clock.currentTimeMillis
cooldown = { until: now + cooldownMillis(cause.response.headers["retry-after"], now), error }
const until = choice === "random" ? failoverUntil(cause, now) : undefined
if (until === undefined) return yield* error
cooldown = { until, error }
cooldowns.set(provider.id, cooldown)
}
provider = randomProvider(yield* Clock.currentTimeMillis, affinity, attempted)
Expand All @@ -224,6 +225,17 @@ const layer = Layer.effect(
}),
)

// Quota, plan-limit and provider-reported failures (402, Tavily's 432, MCP `isError`) rarely clear within a minute, but
// an `isError` can also be specific to one query, so the provider is skipped for an hour rather than for good.
// Auth failures (401/403) stay visible instead.
function failoverUntil(cause: unknown, now: number) {
if (Schema.is(WebSearchMcp.ToolError)(cause)) return now + 3_600_000
if (!HttpClientError.isHttpClientError(cause)) return
const status = cause.response?.status
if (status === 429) return now + cooldownMillis(cause.response?.headers["retry-after"], now)
if (status === 402 || status === 432) return now + 3_600_000
}

function cooldownMillis(value: string | undefined, now: number) {
if (!value?.trim()) return 60_000
const seconds = Number(value)
Expand Down
45 changes: 45 additions & 0 deletions packages/core/test/websearch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect } from "bun:test"
import { Deferred, Effect, Exit, Fiber, Scope } from "effect"
import { TestClock } from "effect/testing"
import { KV } from "@opencode/core/kv"
import { WebSearchMcp } from "@opencode/core/plugin/websearch/mcp"
import { Bus } from "@opencode/core/bus"
import { WebSearch } from "@opencode/core/websearch"
import { Session } from "@opencode/schema/session"
Expand Down Expand Up @@ -330,6 +331,50 @@ describe("WebSearch", () => {
expect(parallel.calls).toEqual([])
}),
)
;[
{ name: "MCP tool errors", cause: () => new WebSearchMcp.ToolError({ message: "Free MCP quota exhausted" }) },
{ name: "HTTP 402", cause: () => TestWebSearch.httpError(402) },
{ name: "HTTP 432", cause: () => TestWebSearch.httpError(432) },
].forEach(({ name, cause }) => {
it.effect(`fails over on ${name} with random and skips the provider for an hour`, () =>
Effect.gen(function* () {
const exa = yield* register("exa")
const parallel = yield* register("parallel")
const websearch = yield* WebSearch.Service
yield* websearch.select("random")
const first = yield* websearch.query({ query: "first" })
const failed = first.providerID === exa.providerID ? exa : parallel
const replacement = first.providerID === exa.providerID ? parallel : exa
failed.failure.cause = cause()
expect((yield* websearch.query({ query: "retry" })).providerID).toBe(replacement.providerID)
failed.failure.cause = undefined
yield* TestClock.adjust("59 minutes")
replacement.failure.cause = cause()
const error = yield* websearch.query({ query: "exhausted" }).pipe(Effect.flip)
expect(error).toMatchObject({ providerID: replacement.providerID, cause: replacement.failure.cause })
expect(failed.calls).toEqual([{ query: "first" }, { query: "retry" }])
yield* TestClock.adjust("1 minute")
expect((yield* websearch.query({ query: "recovered" })).providerID).toBe(failed.providerID)
}),
)

it.effect(`does not fail over a fixed provider on ${name}`, () =>
Effect.gen(function* () {
const exa = yield* register("exa")
const parallel = yield* register("parallel")
const websearch = yield* WebSearch.Service
yield* websearch.select(exa.providerID)
exa.failure.cause = cause()
expect(yield* websearch.query({ query: "fixed" }).pipe(Effect.flip)).toMatchObject({
providerID: exa.providerID,
cause: exa.failure.cause,
})
exa.failure.cause = undefined
expect((yield* websearch.query({ query: "recovered" })).providerID).toBe(exa.providerID)
expect(parallel.calls).toEqual([])
}),
)
})

it.effect("reselects when the active provider is removed", () =>
Effect.gen(function* () {
Expand Down
2 changes: 1 addition & 1 deletion services/site/src/docs/content/websearch.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ Use `"random"` to choose an available provider automatically. Each session keeps

## Limits

When a provider returns HTTP 429, random selection retries the search with another available provider. The rate-limited provider waits for its `Retry-After` period, or 60 seconds when the response does not include a valid period.
With random selection, a search that hits a rate limit, an exhausted quota or plan limit (HTTP 402, or Tavily's 432), or an error reported by the provider's search service is retried with another available provider. A rate-limited provider (HTTP 429) waits for its `Retry-After` period, or 60 seconds when the response does not include a valid period. Any other provider that failed this way is skipped for an hour. If every provider fails, the search reports the last provider's error. A provider you chose directly never fails over.

```text
Exa returns HTTP 429
Expand Down
Loading