Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 7 additions & 5 deletions agent-langgraph-ts/src/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,14 @@ export function modelBaseUrl(env: Env): string | undefined {
}

/**
* The client's own retries: two, as the Python integrations default to, and none for a run the
* server retries itself, where one rate limit asked again several times over without the wait is
* worse than handing it back. LangChain JS would otherwise retry six times.
* The client's own retries: none. A failed call is asked again in one place, the run's step
* (`retry.ts`), which also asks again an answer that broke part way, which no client does, and says
* so to the person while it waits. Left on too, a provider that kept failing was asked thirty times
* where it should be asked ten, and LangChain JS would otherwise retry six times on its own. A run
* the server retries itself (`openbotSendOnce`) is asked once.
*/
function retries(run: RunModel): number {
return run.sendOnce ? 0 : 2;
function retries(_run: RunModel): number {
return 0;
}

function openAIModel(model: string, run: RunModel, env: Env): BaseChatModel {
Expand Down
360 changes: 360 additions & 0 deletions agent-langgraph-ts/src/retry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,360 @@
/**
* A model call that fails for a passing reason is asked again, by itself, and the turn carries on.
*
* FOUND ON OPENBOT CLOUD, 2026-12-04. A Bot on a ChatGPT plan was 17 steps into a turn, and had just
* said it would do more, when the model call for step 18 broke: chatgpt.com answered 200, and 0.6 s
* later reset the connection. The model gateway's answer broke with it, this engine's fetch read
* undici's `TypeError: terminated` (read ECONNRESET), and the run ended with a RUN_ERROR. The person
* read that the connection had dropped and had to press Carry on. Nothing in OpenBot cut it: the
* gateway bounds a stream by five minutes of silence on its raw bytes, the engine's own client by
* five minutes too, and the stream was under a second old. Four other calls through the gateway broke
* the same way in the same 17 seconds, across three servers and two organizations: a blip on the
* provider's side. The model client retried a failure before the answer began (a 502 two seconds
* earlier on the same step), but nothing retried an answer that broke once it had begun.
*
* WHAT THE LEADERS DO, AND SO WHAT THIS DOES (code.claude.com/docs/en/errors):
* - Claude Code retries a dropped connection, a server error, an overloaded answer, a request
* timeout and a passing 429 up to 10 times with exponential backoff (from 500 ms, at most 32 s
* apart) before it shows an error, and a connection that drops before any part of the answer is
* complete is asked again and the turn continues. So here: {@link RETRIES}, {@link FIRST_WAIT_MS},
* {@link LONGEST_WAIT_MS}.
* - A stalled stream is aborted and asked again at most once ({@link STALL_RETRIES}): OpenBot's
* gateway already waited five minutes of silence before it gave up on it.
* - A 429 is retried only when it is a passing throttle. A spend limit, a quota or an account out of
* credit is not a throttle, and is said at once. The wait the provider asks for (`retry-after-ms`,
* `retry-after`) is kept to; one longer than a minute is said rather than waited out
* ({@link THROTTLE_RETRIES}, {@link LONGEST_ASKED_WAIT_MS}).
* - Anthropic's own recovery for a stream interrupted part way: keep what was received, and ask again
* with a user message that says the response was interrupted and to continue from where it left off
* (platform.claude.com/docs/en/build-with-claude/streaming, "Error recovery"). The step's words so
* far stay on the person's screen and are carried on under the same message (`CONTINUE`).
* Thinking and a call's half-written arguments cannot be carried on; the step is asked again for
* those, and a run whose try broke mid-call ends with a MESSAGES_SNAPSHOT that holds only the
* calls the step finally made (run.ts, `brokeMidCall`).
* - No call is ever run twice: this engine runs no tools of its own but the recall, which reads
* memory, and every other call goes back to the caller only once the step is whole.
*
* ONE OWNER OF RETRIES. The model client's own (LangChain's, the vendor SDK's) are off (`models.ts`),
* so a failure is asked again here and nowhere else: ten tries, not ten times three. A run the server
* retries itself (`openbotSendOnce`) is asked once, as before.
*
* WHAT THE PERSON SEES: while a step waits to be asked again, the run sends AG-UI's own CUSTOM event
* `openbot.reconnecting` (`{ attempt, attempts, retryInMs }`), and `openbot.reconnected` once the
* answer is coming again. Plain AG-UI, so any Bot can send it and the app draws it the same for all:
* "Reconnecting…" on the work line. Only when the tries are used up does the run end with its
* RUN_ERROR, and the person reads the connection dropped, with Carry on, as before.
*/
import { links, statusOf } from "./errors.ts";

/** How many times a failed call is asked again, at most: Claude Code's ten. */
export const RETRIES = 10;
/** A stream that went silent until OpenBot's gateway gave up on it: asked again once. */
export const STALL_RETRIES = 1;
/** A passing 429: asked again at most this many times, each after the wait the provider asked. */
export const THROTTLE_RETRIES = 3;
/** A connection that never opened (refused, no answer to connect): asked again twice, as the SDKs do. */
export const UNREACHED_RETRIES = 2;
/** The first wait, then doubled each time: Claude Code's 500 ms. */
export const FIRST_WAIT_MS = 500;
/** The longest wait between two tries: Claude Code's 32 s. */
export const LONGEST_WAIT_MS = 32_000;
/** A provider asking for a longer wait than this is told to the person, not waited out. */
export const LONGEST_ASKED_WAIT_MS = 60_000;

/** The AG-UI CUSTOM event a run sends while it waits to ask its model again. */
export const RECONNECTING = "openbot.reconnecting";
/** The AG-UI CUSTOM event a run sends once the model's answer is coming again. */
export const RECONNECTED = "openbot.reconnected";

export type FailureKind =
| "dropped"
| "unreached"
| "stalled"
| "server"
| "throttled";

export type Passing = {
kind: FailureKind;
/** The wait the provider asked for, when it asked. */
askedMs?: number;
};

/** A connection that broke once the answer had begun, by Node's, undici's and the SDKs' codes. */
const BROKEN_CODES = new Set([
"ECONNRESET",
"EPIPE",
"ECONNABORTED",
"UND_ERR_SOCKET",
"UND_ERR_CLOSED",
"UND_ERR_BODY_TIMEOUT",
"UND_ERR_HEADERS_TIMEOUT",
"ERR_STREAM_PREMATURE_CLOSE",
]);
const BROKEN_WORDS =
/^terminated$|other side closed|socket hang up|socket connection was closed unexpectedly|premature close|^fetch failed$|^network error$|^Connection error\.?$/i;

/** A connection that never opened. Not ENOTFOUND: a name that does not resolve is a wrong address. */
const UNREACHED_CODES = new Set([
"ECONNREFUSED",
"ETIMEDOUT",
"UND_ERR_CONNECT_TIMEOUT",
"EHOSTUNREACH",
"ENETUNREACH",
"EAI_AGAIN",
]);

/** OpenBot's gateway giving up on a provider that went silent (model-gateway/silence.ts). */
const SILENT =
/openbot_model_silent|sent nothing for [\d.]+ seconds?, so OpenBot stopped waiting/i;

/** Words that say the money or the quota ran out: never a passing 429. The same as errors.ts. */
const SPENT =
/no credits remaining|credit[_ ]balance|insufficient[_ ]quota|used all available credits|spending limit|spend limit|exceeded your current quota|usage limits?|purchase (more )?credits|out of usage|billing/i;

function asRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object"
? (value as Record<string, unknown>)
: undefined;
}

/** Everything a link says about itself, for the words its body and message hold. */
function said(link: Record<string, unknown>): string {
let body = "";
for (const value of [link.error, link.body, link.responseBody]) {
if (typeof value === "string") body += ` ${value}`;
else if (value && typeof value === "object") {
try {
body += ` ${JSON.stringify(value)}`;
} catch {
// Not worth more than its message.
}
}
}
return `${typeof link.message === "string" ? link.message : ""} ${body}`;
}

/** The kinds a provider's error body names: Anthropic's `type`, OpenAI's `type` and `code`. */
function kinds(link: Record<string, unknown>): string {
const body =
asRecord(link.error) ?? asRecord(link.body) ?? asRecord(link.responseBody);
const nested = asRecord(body?.error);
return [body?.type, body?.code, nested?.type, nested?.code, link.type]
.filter((value): value is string => typeof value === "string")
.join(" ")
.toLowerCase();
}

/** A header from either shape an SDK keeps them in: `Headers`, or a plain record. */
function header(headers: unknown, name: string): string | undefined {
if (!headers || typeof headers !== "object") return undefined;
const get = (headers as { get?: unknown }).get;
const value =
typeof get === "function"
? (get.call(headers, name) as unknown)
: Object.entries(headers as Record<string, unknown>).find(
([key]) => key.toLowerCase() === name,
)?.[1];
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}

/**
* How long the provider asked to wait (`retry-after-ms`, then `retry-after` as seconds or an HTTP
* date), on the error or anything it wraps.
*/
export function askedWaitMs(
error: unknown,
now: () => number = Date.now,
): number | undefined {
for (const link of links(error)) {
const headers =
link.headers ?? link.responseHeaders ?? asRecord(link.response)?.headers;
const finer = Number(header(headers, "retry-after-ms"));
if (Number.isFinite(finer) && finer >= 0) return Math.ceil(finer);
const asked = header(headers, "retry-after");
if (asked === undefined) continue;
if (/^\d+(?:\.\d+)?$/.test(asked)) return Math.ceil(Number(asked) * 1000);
const at = Date.parse(asked);
if (!Number.isNaN(at)) return Math.max(0, at - now());
}
return undefined;
}

/** Whether whoever answered said not to ask again (`x-should-retry: false`), as OpenBot's gateway does. */
function toldNotTo(error: unknown): boolean {
return links(error).some((link) => {
const headers =
link.headers ?? link.responseHeaders ?? asRecord(link.response)?.headers;
return header(headers, "x-should-retry") === "false";
});
}

/**
* The passing failure a model call ended with, or undefined when asking again would not help: a stop
* the caller asked for, a refusal, a key, a quota, a request the provider could not take.
*/
export function passingFailure(error: unknown): Passing | undefined {
const chain = links(error);
if (
chain.some(
(link) =>
link.name === "AbortError" ||
// The model declined, or the request is too long even cleared: the same answer again.
link.name === "ModelDeclinedError" ||
link.name === "MessageTooLongError" ||
// A plan's harness, which asks its own model again itself (Claude Code, Codex).
link.name === "HarnessRunError",
)
)
return undefined;
const text = chain.map(said).join(" ");
if (SILENT.test(text)) return { kind: "stalled" };
for (const link of chain) {
const status = statusOf(link);
if (status === undefined) continue;
if (toldNotTo(error)) return undefined;
if (status === 429) {
if (SPENT.test(text) || /insufficient_quota|billing/.test(kinds(link)))
return undefined;
const askedMs = askedWaitMs(error);
return {
kind: "throttled",
...(askedMs !== undefined ? { askedMs } : {}),
};
}
// 408 a request timeout, 409 a lock the provider said to retry, 5xx and 529 overloaded.
if (status === 408 || status === 409 || status >= 500) {
const askedMs = askedWaitMs(error);
return { kind: "server", ...(askedMs !== undefined ? { askedMs } : {}) };
}
return undefined;
}
// A provider's error part way through a stream that began with a 200 has no status: its kind says.
for (const link of chain) {
const kind = kinds(link);
if (!kind) continue;
if (/rate_limit|too_many_requests/.test(kind) && !SPENT.test(text))
return { kind: "throttled" };
if (
/overloaded|server_error|api_error|internal|unavailable|timeout/.test(
kind,
)
)
return { kind: "server" };
if (/error/.test(kind) && link.name !== "TypeError") return undefined;
}
for (const link of chain) {
const code = typeof link.code === "string" ? link.code : undefined;
if (code && UNREACHED_CODES.has(code)) return { kind: "unreached" };
if (code && BROKEN_CODES.has(code)) return { kind: "dropped" };
}
for (const link of chain) {
// The OpenAI and Anthropic SDKs' own connection errors, by the class their constructor names.
const name = `${String(link.name)} ${(link as { constructor?: { name?: string } }).constructor?.name ?? ""}`;
if (/\bAPIConnectionTimeoutError\b|\bTimeoutError\b/.test(name))
return { kind: "dropped" };
if (/\bAPIConnectionError\b/.test(name)) return { kind: "dropped" };
if (
typeof link.message === "string" &&
BROKEN_WORDS.test(link.message.trim())
)
return { kind: "dropped" };
}
return undefined;
}

/** How many tries each kind of failure gets, at most. */
export function triesFor(kind: FailureKind): number {
if (kind === "stalled") return STALL_RETRIES;
if (kind === "throttled") return THROTTLE_RETRIES;
if (kind === "unreached") return UNREACHED_RETRIES;
return RETRIES;
}

/** The timing a test may shorten, so a test of ten tries does not wait two minutes. */
export type RetryTiming = { firstWaitMs: number; longestWaitMs: number };

let timing: RetryTiming = {
firstWaitMs: FIRST_WAIT_MS,
longestWaitMs: LONGEST_WAIT_MS,
};

/** Sets how long a step waits between tries. Tests only; the default is Claude Code's. */
export function useRetryTiming(next: Partial<RetryTiming>): () => void {
const before = timing;
timing = { ...timing, ...next };
return () => {
timing = before;
};
}

/** One step's tries: how many it has made, and how long to wait before the next one, if any. */
export class Retries {
private made = 0;
private byKind = new Map<FailureKind, number>();
private readonly random: () => number;
constructor(random: () => number = Math.random) {
this.random = random;
}

/** How many retries this step has made. */
get count(): number {
return this.made;
}

/**
* The wait before the next try of a call that failed this way, or undefined when it has had its
* tries: the kind's own number of them, and never more than {@link RETRIES} in all.
*/
next(
failure: Passing,
): { waitMs: number; attempt: number; attempts: number } | undefined {
const ofKind = this.byKind.get(failure.kind) ?? 0;
const attempts = triesFor(failure.kind);
if (ofKind >= attempts || this.made >= RETRIES) return undefined;
if (
failure.askedMs !== undefined &&
failure.askedMs > LONGEST_ASKED_WAIT_MS
)
return undefined;
this.byKind.set(failure.kind, ofKind + 1);
this.made += 1;
const backoff = Math.min(
timing.longestWaitMs,
timing.firstWaitMs * 2 ** (this.made - 1),
);
// A quarter either way, so a fleet that broke together does not ask again together.
const jittered = Math.round(backoff * (0.75 + this.random() * 0.5));
return {
waitMs: failure.askedMs ?? jittered,
attempt: ofKind + 1,
attempts,
};
}
}

/** Waits `ms`, or until the run is stopped, whichever comes first. */
export function pause(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
return;
}
const timer = setTimeout(() => {
signal?.removeEventListener("abort", stop);
resolve();
}, ms);
const stop = () => {
clearTimeout(timer);
reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
};
signal?.addEventListener("abort", stop, { once: true });
});
}

/**
* What a step is asked when its answer broke after it had begun to speak: what it said, as its own
* message, then Anthropic's documented way to carry on an interrupted stream, a user message that
* says so. Written for the model.
*/
export const CONTINUE =
"Your previous response was interrupted by a dropped connection right after the words above. Continue from exactly where it left off. Do not repeat anything you already said.";
Loading
Loading