GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(session): make retry cap and backoffDelay configurable per provider · eyalatox/opencode@42e103a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • core/src/v1/config
      • provider.ts
    • opencode
      • src
        • provider
          • provider.ts
        • session
          • processor.ts
          • retry.ts
      • test/session
        • retry.test.ts
    • sdk
      • js/src/v2/gen
        • types.gen.ts
      • openapi.json
    • web/src/content/docs
      • config.mdx
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/v1/config/provider.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/v1/config/provider.ts
+9-1Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
export * as ConfigProviderV1 from "./provider"
22

33
import { Schema } from "effect"
4-
import { PositiveInt } from "../../schema"
4+
import { NonNegativeInt, PositiveInt } from "../../schema"
55

66
export const ModelStatus = Schema.Literals(["alpha", "beta", "deprecated", "active"])
77

@@ -118,6 +118,14 @@ export const Info = Schema.Struct({
118118
description:
119119
"Timeout in milliseconds between streamed SSE chunks for this provider. If no chunk arrives within this window, the request is aborted.",
120120
}),
121+
retry: Schema.optional(NonNegativeInt).annotate({
122+
description:
123+
"Maximum number of retries for retryable API errors from this provider (default 5). Set to 0 to disable retries.",
124+
}),
125+
backoffDelay: Schema.optional(PositiveInt).annotate({
126+
description:
127+
"Initial delay in milliseconds for exponential backoff between retries (default 2000). Ignored when the provider responds with retry-after headers.",
128+
}),
121129
}),
122130
[Schema.Record(Schema.String, Schema.Any)],
123131
),
Collapse file

‎packages/opencode/src/provider/provider.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/provider/provider.ts
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1739,6 +1739,9 @@ const layer = Layer.effect(
17391739
const headerTimeout = options["headerTimeout"]
17401740
delete options["chunkTimeout"]
17411741
delete options["headerTimeout"]
1742+
// consumed by the session retry policy, not the provider SDK
1743+
delete options["retry"]
1744+
delete options["backoffDelay"]
17421745

17431746
options["fetch"] = async (input: any, init?: BunFetchRequestInit) => {
17441747
const fetchFn = customFetch ?? fetch
Collapse file

‎packages/opencode/src/session/processor.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/session/processor.ts
+9-1Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import type { SessionID } from "./schema"
1818
import { SessionRetry } from "./retry"
1919
import { SessionStatus } from "./status"
2020
import { SessionSummary } from "./summary"
21-
import type { Provider } from "@/provider/provider"
21+
import { Provider } from "@/provider/provider"
2222
import { Question } from "@/question"
2323
import { errorMessage } from "@/util/error"
2424
import { isRecord } from "@/util/record"
@@ -86,6 +86,7 @@ const layer = Layer.effect(
8686
const snapshot = yield* Snapshot.Service
8787
const agents = yield* Agent.Service
8888
const llm = yield* LLM.Service
89+
const provider = yield* Provider.Service
8990
const permission = yield* Permission.Service
9091
const plugin = yield* Plugin.Service
9192
const summary = yield* SessionSummary.Service
@@ -632,6 +633,10 @@ const layer = Layer.effect(
632633
ctx.needsCompaction = false
633634
ctx.shouldBreak = (yield* config.get()).experimental?.continue_loop_on_deny !== true
634635

636+
const options = (yield* provider.getProvider(input.model.providerID))?.options ?? {}
637+
const retryOption = (key: "retry" | "backoffDelay") =>
638+
typeof options[key] === "number" ? options[key] : undefined
639+
635640
return yield* Effect.gen(function* () {
636641
yield* Effect.gen(function* () {
637642
ctx.currentText = undefined
@@ -660,6 +665,8 @@ const layer = Layer.effect(
660665
Effect.retry(
661666
SessionRetry.policy({
662667
provider: input.model.providerID,
668+
retry: retryOption("retry"),
669+
backoffDelay: retryOption("backoffDelay"),
663670
parse,
664671
set: (info) => {
665672
return status.set(ctx.sessionID, {
@@ -705,6 +712,7 @@ export const node = LayerNode.make({
705712
Snapshot.node,
706713
Agent.node,
707714
LLM.node,
715+
Provider.node,
708716
Permission.node,
709717
Plugin.node,
710718
SessionSummary.node,
Collapse file

‎packages/opencode/src/session/retry.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/session/retry.ts
+14-7Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ function cap(ms: number) {
4343
return Math.min(ms, RETRY_MAX_DELAY)
4444
}
4545

46-
export function delay(attempt: number, error?: SessionV1.APIError, random = Math.random()) {
46+
export function delay(attempt: number, error?: SessionV1.APIError, random = Math.random(), backoffDelay?: number) {
4747
if (error) {
4848
const headers = error.data.responseHeaders
4949
if (headers) {
@@ -69,15 +69,15 @@ export function delay(attempt: number, error?: SessionV1.APIError, random = Math
6969
}
7070
}
7171

72-
return cap(exponential(attempt, random))
72+
return cap(exponential(attempt, random, backoffDelay))
7373
}
7474
}
7575

76-
return cap(Math.min(exponential(attempt, random), RETRY_MAX_DELAY_NO_HEADERS))
76+
return cap(Math.min(exponential(attempt, random, backoffDelay), RETRY_MAX_DELAY_NO_HEADERS))
7777
}
7878

79-
function exponential(attempt: number, random: number) {
80-
const base = RETRY_INITIAL_DELAY * Math.pow(RETRY_BACKOFF_FACTOR, attempt - 1)
79+
function exponential(attempt: number, random: number, backoffDelay?: number) {
80+
const base = (backoffDelay ?? RETRY_INITIAL_DELAY) * Math.pow(RETRY_BACKOFF_FACTOR, attempt - 1)
8181
return Math.ceil(base + base * RETRY_JITTER_FACTOR * random)
8282
}
8383

@@ -181,6 +181,8 @@ function parseJSON(value: unknown) {
181181

182182
export function policy(opts: {
183183
provider: string
184+
retry?: number
185+
backoffDelay?: number
184186
parse: (error: unknown) => Err
185187
set: (input: { attempt: number; message: string; action?: Retryable["action"]; next: number }) => Effect.Effect<void>
186188
}) {
@@ -189,9 +191,14 @@ export function policy(opts: {
189191
const error = opts.parse(meta.input)
190192
const retry = retryable(error, opts.provider)
191193
if (!retry) return Cause.done(meta.attempt)
192-
if (meta.attempt > RETRY_MAX_RETRIES) return Cause.done(meta.attempt)
194+
if (meta.attempt > (opts.retry ?? RETRY_MAX_RETRIES)) return Cause.done(meta.attempt)
193195
return Effect.gen(function* () {
194-
const wait = delay(meta.attempt, SessionV1.APIError.isInstance(error) ? error : undefined)
196+
const wait = delay(
197+
meta.attempt,
198+
SessionV1.APIError.isInstance(error) ? error : undefined,
199+
undefined,
200+
opts.backoffDelay,
201+
)
195202
const now = yield* Clock.currentTimeMillis
196203
yield* opts.set({
197204
attempt: meta.attempt,
Collapse file

‎packages/opencode/test/session/retry.test.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/test/session/retry.test.ts
+78Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,17 @@ describe("session.retry.delay", () => {
9494
expect(SessionRetry.delay(1, error)).toBe(SessionRetry.RETRY_MAX_DELAY)
9595
})
9696

97+
test("uses configured backoffDelay as the initial delay", () => {
98+
const error = apiError()
99+
const delays = Array.from({ length: 6 }, (_, index) => SessionRetry.delay(index + 1, error, 0, 1000))
100+
expect(delays).toStrictEqual([1000, 2000, 4000, 8000, 16000, 30000])
101+
})
102+
103+
test("prefers retry-after headers over configured backoffDelay", () => {
104+
const error = apiError({ "retry-after-ms": "1500" })
105+
expect(SessionRetry.delay(1, error, 0, 5000)).toBe(1500)
106+
})
107+
97108
it.instance("policy updates retry status and increments attempts", () =>
98109
Effect.gen(function* () {
99110
const sessionID = SessionID.make("session-retry-test")
@@ -146,6 +157,73 @@ describe("session.retry.delay", () => {
146157
expect(attempts).toStrictEqual([1, 2, 3, 4, 5])
147158
}),
148159
)
160+
161+
it.instance("policy stops after the configured retry limit", () =>
162+
Effect.gen(function* () {
163+
const sessionID = SessionID.make("session-retry-limit-test")
164+
const error = apiError({ "retry-after-ms": "0" })
165+
const status = yield* SessionStatus.Service
166+
167+
const step = yield* Schedule.toStepWithMetadata(
168+
SessionRetry.policy({
169+
provider: "test",
170+
retry: 1,
171+
parse: Schema.decodeUnknownSync(SessionV1.APIError.Schema),
172+
set: (info) =>
173+
status.set(sessionID, {
174+
type: "retry",
175+
attempt: info.attempt,
176+
message: info.message,
177+
next: info.next,
178+
}),
179+
}),
180+
)
181+
yield* step(error)
182+
const second = yield* step(error).pipe(Effect.exit)
183+
184+
expect(second._tag).toBe("Failure")
185+
expect(yield* status.get(sessionID)).toMatchObject({
186+
type: "retry",
187+
attempt: 1,
188+
message: "boom",
189+
})
190+
}),
191+
)
192+
193+
it.instance("policy retry option can raise the attempt limit", () =>
194+
Effect.gen(function* () {
195+
const error = apiError({ "retry-after-ms": "0" })
196+
const step = yield* Schedule.toStepWithMetadata(
197+
SessionRetry.policy({
198+
provider: "test",
199+
retry: SessionRetry.RETRY_MAX_RETRIES + 2,
200+
parse: Schema.decodeUnknownSync(SessionV1.APIError.Schema),
201+
set: () => Effect.void,
202+
}),
203+
)
204+
for (let attempt = 1; attempt <= SessionRetry.RETRY_MAX_RETRIES + 2; attempt++) {
205+
yield* step(error)
206+
}
207+
const exhausted = yield* step(error).pipe(Effect.exit)
208+
expect(exhausted._tag).toBe("Failure")
209+
}),
210+
)
211+
212+
it.instance("policy with retry 0 never retries", () =>
213+
Effect.gen(function* () {
214+
const error = apiError({ "retry-after-ms": "0" })
215+
const step = yield* Schedule.toStepWithMetadata(
216+
SessionRetry.policy({
217+
provider: "test",
218+
retry: 0,
219+
parse: Schema.decodeUnknownSync(SessionV1.APIError.Schema),
220+
set: () => Effect.void,
221+
}),
222+
)
223+
const result = yield* step(error).pipe(Effect.exit)
224+
expect(result._tag).toBe("Failure")
225+
}),
226+
)
149227
})
150228

151229
describe("session.retry.retryable", () => {
Collapse file

‎packages/sdk/js/src/v2/gen/types.gen.ts‎

Copy file name to clipboardExpand all lines: packages/sdk/js/src/v2/gen/types.gen.ts
+3-1Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1755,7 +1755,9 @@ export type ProviderConfig = {
17551755
*/
17561756
headerTimeout?: number | false
17571757
chunkTimeout?: number
1758-
[key: string]: unknown | string | boolean | number | false | number | false | number | undefined
1758+
retry?: number
1759+
backoffDelay?: number
1760+
[key: string]: unknown | string | boolean | number | false | number | false | number | number | undefined
17591761
}
17601762
models?: {
17611763
[key: string]: {
Collapse file

‎packages/sdk/openapi.json‎

Copy file name to clipboardExpand all lines: packages/sdk/openapi.json
+8Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20784,6 +20784,14 @@
2078420784
"chunkTimeout": {
2078520785
"type": "integer",
2078620786
"exclusiveMinimum": 0
20787+
},
20788+
"retry": {
20789+
"type": "integer",
20790+
"minimum": 0
20791+
},
20792+
"backoffDelay": {
20793+
"type": "integer",
20794+
"exclusiveMinimum": 0
2078720795
}
2078820796
},
2078920797
"additionalProperties": {}
Collapse file

‎packages/web/src/content/docs/config.mdx‎

Copy file name to clipboardExpand all lines: packages/web/src/content/docs/config.mdx
+5-1Lines changed: 5 additions & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ You can configure the providers and models you want to use in your OpenCode conf
374374

375375
The `small_model` option configures a separate model for lightweight tasks like title generation. By default, OpenCode tries to use a cheaper model if one is available from your provider, otherwise it falls back to your main model.
376376

377-
Provider options can include `timeout`, `chunkTimeout`, and `setCacheKey`:
377+
Provider options can include `timeout`, `chunkTimeout`, `retry`, `backoffDelay`, and `setCacheKey`:
378378

379379
```json title="opencode.json"
380380
{
@@ -384,6 +384,8 @@ Provider options can include `timeout`, `chunkTimeout`, and `setCacheKey`:
384384
"options": {
385385
"timeout": 600000,
386386
"chunkTimeout": 30000,
387+
"retry": 3,
388+
"backoffDelay": 1000,
387389
"setCacheKey": true
388390
}
389391
}
@@ -393,6 +395,8 @@ Provider options can include `timeout`, `chunkTimeout`, and `setCacheKey`:
393395

394396
- `timeout` - Request timeout in milliseconds (default: 300000). Set to `false` to disable.
395397
- `chunkTimeout` - Timeout in milliseconds between streamed response chunks. If no chunk arrives in time, the request is aborted.
398+
- `retry` - Maximum number of retries for retryable API errors like rate limits or server errors (default: 5). Set to `0` to disable retries.
399+
- `backoffDelay` - Initial delay in milliseconds for exponential backoff between retries (default: 2000). Ignored when the provider responds with `retry-after` headers.
396400
- `setCacheKey` - Ensure a cache key is always set for designated provider.
397401

398402
You can also configure [local models](/docs/models#local). [Learn more](/docs/models).

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.