Add configurable retries for transient provider errors#54
Merged
Conversation
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Retry wrapper swallows stream errors
- Wrapped the retry loop in a catch that now converts thrown stream/replay errors into terminal assistant error events so the output stream always ends.
- ✅ Fixed: Missing TSDoc on exports
- Added TSDoc comments for retry policy constants and both exported helpers to document behavior, caps, and scope of model wrapping.
Or push these changes by commenting:
@cursor push ced4bfe0cd
Preview (ced4bfe0cd)
diff --git a/packages/agent/src/provider-retry.ts b/packages/agent/src/provider-retry.ts
--- a/packages/agent/src/provider-retry.ts
+++ b/packages/agent/src/provider-retry.ts
@@ -12,8 +12,11 @@
type SimpleStreamOptions,
} from "@earendil-works/pi-ai";
+/** Maximum number of attempts, including the initial request. */
const MAX_ATTEMPTS = 4;
+/** Default cap for provider-suggested retry delays when callers do not set one. */
const DEFAULT_MAX_RETRY_DELAY_MS = 60_000;
+/** Largest timeout accepted by JS timers; longer waits are split into chunks. */
const MAX_TIMER_DELAY_MS = 2_147_483_647;
type RetryStreamFn = (
@@ -22,48 +25,65 @@
options?: SimpleStreamOptions,
) => AssistantMessageEventStream;
+/**
+ * Wraps a streaming call with retry handling for retryable provider errors.
+ *
+ * The wrapper retries up to `MAX_ATTEMPTS` with exponential backoff and optional
+ * provider-specified delays, then replays the terminal attempt to the caller.
+ */
export function withProviderRetry(streamFn: StreamFn): RetryStreamFn {
return (model, context, options) => {
const output = createAssistantMessageEventStream();
void (async () => {
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
- if (options?.signal?.aborted) {
- replayAborted(output, model);
- return;
- }
+ try {
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
+ if (options?.signal?.aborted) {
+ replayAborted(output, model);
+ return;
+ }
- const input = await streamFn(model, context, options);
- const events: AssistantMessageEvent[] = [];
- for await (const event of input) events.push(structuredClone(event));
- const terminal = events.at(-1);
- const message = terminalMessage(terminal);
- if (
- !message ||
- message.stopReason !== "error" ||
- !isRetryableAssistantError(message) ||
- attempt === MAX_ATTEMPTS - 1
- ) {
- replay(output, events, message);
- return;
- }
+ const input = await streamFn(model, context, options);
+ const events: AssistantMessageEvent[] = [];
+ for await (const event of input) events.push(structuredClone(event));
+ const terminal = events.at(-1);
+ const message = terminalMessage(terminal);
+ if (
+ !message ||
+ message.stopReason !== "error" ||
+ !isRetryableAssistantError(message) ||
+ attempt === MAX_ATTEMPTS - 1
+ ) {
+ replay(output, events, message);
+ return;
+ }
- const providerDelay = parseProviderDelay(message.errorMessage);
- const cap = options?.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;
- if (providerDelay !== undefined && cap > 0 && providerDelay > cap) {
- replay(output, events, message);
- return;
+ const providerDelay = parseProviderDelay(message.errorMessage);
+ const cap = options?.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;
+ if (providerDelay !== undefined && cap > 0 && providerDelay > cap) {
+ replay(output, events, message);
+ return;
+ }
+ const delay = Math.max(2_000 * 2 ** attempt, providerDelay ?? 0);
+ if (!(await wait(delay, options?.signal))) {
+ replayAborted(output, model);
+ return;
+ }
}
- const delay = Math.max(2_000 * 2 ** attempt, providerDelay ?? 0);
- if (!(await wait(delay, options?.signal))) {
- replayAborted(output, model);
- return;
- }
+ } catch (error) {
+ if (options?.signal?.aborted) replayAborted(output, model);
+ else replayUnexpectedError(output, model, error);
}
})();
return output;
};
}
+/**
+ * Returns a `Models` wrapper that applies provider retries to simple call paths.
+ *
+ * Only `streamSimple` and `completeSimple` are wrapped because Agent/Harness use
+ * those APIs; generic `stream` and `complete` pass through unchanged.
+ */
export function withProviderRetryModels(models: Models): Models {
const streamSimple = withProviderRetry((model, context, options) => models.streamSimple(model, context, options));
return {
@@ -98,7 +118,34 @@
}
function replayAborted(output: ReturnType<typeof createAssistantMessageEventStream>, model: Model<Api>): void {
- const message: AssistantMessage = {
+ const message = terminalErrorMessage(model, "aborted", "Request aborted");
+ output.push({ type: "start", partial: structuredClone(message) });
+ output.push({ type: "error", reason: "aborted", error: message });
+ output.end(message);
+}
+
+function replayUnexpectedError(
+ output: ReturnType<typeof createAssistantMessageEventStream>,
+ model: Model<Api>,
+ error: unknown,
+): void {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ const message = terminalErrorMessage(
+ model,
+ "error",
+ errorMessage || "Unexpected error while handling provider retry stream",
+ );
+ output.push({ type: "start", partial: message });
+ output.push({ type: "error", reason: "error", error: message });
+ output.end(message);
+}
+
+function terminalErrorMessage(
+ model: Model<Api>,
+ stopReason: Extract<AssistantMessage["stopReason"], "aborted" | "error">,
+ errorMessage: string,
+): AssistantMessage {
+ return {
role: "assistant",
content: [],
api: model.api,
@@ -112,13 +159,10 @@
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
- stopReason: "aborted",
- errorMessage: "Request aborted",
+ stopReason,
+ errorMessage,
timestamp: Date.now(),
};
- output.push({ type: "start", partial: structuredClone(message) });
- output.push({ type: "error", reason: "aborted", error: message });
- output.end(message);
}
function parseProviderDelay(message: string | undefined): number | undefined {
diff --git a/packages/agent/test/provider-retry.test.ts b/packages/agent/test/provider-retry.test.ts
--- a/packages/agent/test/provider-retry.test.ts
+++ b/packages/agent/test/provider-retry.test.ts
@@ -164,6 +164,30 @@
expect(deltas[1].partial.content).toEqual([{ type: "text", text: "ab" }]);
});
+ it("converts stream function rejections into terminal errors", async () => {
+ const retrying = withProviderRetry(async () => {
+ throw new Error("network exploded");
+ });
+ const result = await retrying(model, context).result();
+
+ expect(result.stopReason).toBe("error");
+ expect(result.errorMessage).toContain("network exploded");
+ });
+
+ it("converts stream processing failures into terminal errors", async () => {
+ const retrying = withProviderRetry(() => {
+ const stream = createAssistantMessageEventStream();
+ const value = assistant("stop");
+ stream.push({ type: "start", partial: value });
+ stream.push({ type: "start", partial: value, cannotClone: () => null } as unknown as AssistantMessageEvent);
+ return stream;
+ });
+ const result = await retrying(model, context).result();
+
+ expect(result.stopReason).toBe("error");
+ expect(result.errorMessage).toBeTruthy();
+ });
+
it("applies retries to Models.completeSimple", async () => {
vi.useFakeTimers();
let calls = 0;You can send follow-ups to the cloud agent here.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Finally overwrites replay failure end
- I added an
endedguard insettleso replay-failure paths calloutput.end(failure)only once and are not overwritten by thefinallyend call, and added a regression test for that case.
- I added an
Or push these changes by commenting:
@cursor push 48dd714a5e
Preview (48dd714a5e)
diff --git a/packages/agent/src/provider-retry.ts b/packages/agent/src/provider-retry.ts
--- a/packages/agent/src/provider-retry.ts
+++ b/packages/agent/src/provider-retry.ts
@@ -109,6 +109,7 @@
if (settled) return;
settled = true;
let terminalEmitted = false;
+ let ended = false;
try {
if (events) {
for (const event of events) {
@@ -128,11 +129,11 @@
} catch {
// end(result) still settles result() and any waiting iterator.
}
+ ended = true;
output.end(failure);
- return;
}
} finally {
- output.end(message);
+ if (!ended) output.end(message);
}
};
diff --git a/packages/agent/test/provider-retry.test.ts b/packages/agent/test/provider-retry.test.ts
--- a/packages/agent/test/provider-retry.test.ts
+++ b/packages/agent/test/provider-retry.test.ts
@@ -205,6 +205,20 @@
expect(calls).toBe(3);
});
+ it("keeps replay failure terminal message", async () => {
+ const retrying = withProviderRetry((() => textStream("ok")) as StreamFn, enabled);
+ const stream = retrying(model, context);
+ const push = stream.push.bind(stream);
+ let calls = 0;
+ (stream as typeof stream & { push: typeof stream.push }).push = (event) => {
+ if (calls++ === 0) throw new Error("replay failed");
+ return push(event);
+ };
+ const result = await stream.result();
+ expect(result.stopReason).toBe("error");
+ expect(result.errorMessage).toContain("Failed to replay provider response: replay failed");
+ });
+
it("aborts before the first request and during backoff", async () => {
const alreadyAborted = new AbortController();
alreadyAborted.abort();You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit c4be964. Configure here.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
retry.enabled,retry.maxRetries, andretry.baseDelayMsthroughCuaAgent,CuaAgentHarness, and the CLI harness builderTesting
npm run typechecknpm run build --workspace @onkernel/cua-clinpm exec --workspace @onkernel/cua-agent vitest -- run test/provider-retry.test.ts test/agent.test.ts(49 passed)npm exec --workspace @onkernel/cua-cli vitest -- run test/action-runner.test.ts(6 passed)npm test --workspace @onkernel/cua-agent(104 passed, 12 skipped)npm test --workspace @onkernel/cua-cli(81 passed, 5 skipped)Note
Medium Risk
Changes how provider streams are consumed and can multiply API calls when retries are enabled; default-off preserves prior behavior.
Overview
Adds opt-in retries around each provider request for transient failures (rate limits, 503s, network/timeouts), using pi-ai’s retryable-error and context-overflow checks. Disabled by default; when enabled, defaults are 3 extra attempts with 2s / 4s / 8s exponential backoff (
retry.enabled,retry.maxRetries,retry.baseDelayMs).CuaAgentwraps the stream function;CuaAgentHarnessand the CLIbuildCuaHarnesswrapModels.streamSimple/completeSimpleonly (genericstream/completeunchanged). Failed attempts are buffered and discarded so partial deltas are not replayed; a successful attempt replays one clean event sequence. Abort signals skip work before the first call and during backoff.Exports
CuaRetryOptionsfrom the agent package. Covered byprovider-retry, agent, and CLI action-runner tests.Reviewed by Cursor Bugbot for commit 2679597. Bugbot is set up for automated code reviews on this repo. Configure here.