Skip to content

Add configurable retries for transient provider errors#54

Merged
rgarcia merged 3 commits into
mainfrom
hypeship/retry-provider-errors-1-fix
Jul 10, 2026
Merged

Add configurable retries for transient provider errors#54
rgarcia merged 3 commits into
mainfrom
hypeship/retry-provider-errors-1-fix

Conversation

@rgarcia

@rgarcia rgarcia commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Summary

  • add opt-in CUA-level retries for transient provider failures around individual provider requests
  • expose retry.enabled, retry.maxRetries, and retry.baseDelayMs through CuaAgent, CuaAgentHarness, and the CLI harness builder
  • default retries to disabled for backward compatibility; when enabled, default to 3 retries with 2s/4s/8s backoff
  • use pi-ai's transient-error and context-overflow classifiers while keeping provider retry options independent
  • buffer enabled retry attempts so failed deltas are discarded without repeating completed tool actions
  • settle invocation, iteration, malformed-stream, snapshot, abort, backoff, and replay failures without leaving callers pending

Testing

  • npm run typecheck
  • npm run build --workspace @onkernel/cua-cli
  • npm 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).

CuaAgent wraps the stream function; CuaAgentHarness and the CLI buildCuaHarness wrap Models.streamSimple / completeSimple only (generic stream / complete unchanged). 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 CuaRetryOptions from the agent package. Covered by provider-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.

@rgarcia rgarcia marked this pull request as ready for review July 9, 2026 20:48

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Create PR

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.

Comment thread packages/agent/src/provider-retry.ts Outdated
Comment thread packages/agent/src/provider-retry.ts
@rgarcia rgarcia changed the title Retry transient provider errors in CUA runs Add configurable retries for transient provider errors Jul 9, 2026
@rgarcia rgarcia marked this pull request as draft July 9, 2026 21:21

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Finally overwrites replay failure end
    • I added an ended guard in settle so replay-failure paths call output.end(failure) only once and are not overwritten by the finally end call, and added a regression test for that case.

Create PR

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.

Comment thread packages/agent/src/provider-retry.ts
@rgarcia rgarcia marked this pull request as ready for review July 9, 2026 21:57
@rgarcia rgarcia merged commit 88b101a into main Jul 10, 2026
6 checks passed
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