diff --git a/agent-langgraph-ts/src/models.ts b/agent-langgraph-ts/src/models.ts index 5959988693..f8881dd361 100644 --- a/agent-langgraph-ts/src/models.ts +++ b/agent-langgraph-ts/src/models.ts @@ -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 { diff --git a/agent-langgraph-ts/src/retry.ts b/agent-langgraph-ts/src/retry.ts new file mode 100644 index 0000000000..aef7903528 --- /dev/null +++ b/agent-langgraph-ts/src/retry.ts @@ -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 | undefined { + return value && typeof value === "object" + ? (value as Record) + : undefined; +} + +/** Everything a link says about itself, for the words its body and message hold. */ +function said(link: Record): 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 { + 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).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): () => 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(); + 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 { + 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."; diff --git a/agent-langgraph-ts/src/run.ts b/agent-langgraph-ts/src/run.ts index 4612d62c0c..34c17506c2 100644 --- a/agent-langgraph-ts/src/run.ts +++ b/agent-langgraph-ts/src/run.ts @@ -26,6 +26,11 @@ * snapshot is the whole thread: each step of a long task sent the whole conversation back, N²/2 * messages over a turn of N steps (FOUND IN THE WASTE AUDIT AFTER 1.2.7). A caller that takes * a run with no snapshot builds the same thread, as it does for any AG-UI agent that sends none. + * The one exception: a step asked again after a try that broke while writing a call (retry.ts) + * ends with a snapshot, the only AG-UI way to take the half-written call out of the thread. + * - A model call that fails for a passing reason (a dropped connection, a server error, an + * overload, a passing 429) is asked again here, with backoff, and the run carries on from where + * the step was; meanwhile the run sends CUSTOM `openbot.reconnecting` (`retry.ts`). * * THE ONE OPENBOT EXTENSION: MODEL ROUTING. This engine has no model of its own, so the caller may * name one in `forwardedProps`, AG-UI's channel for what only the agent reads: `openbotModel`, @@ -52,6 +57,7 @@ import { AIMessage, type AIMessageChunk, type BaseMessage, + HumanMessage, ToolMessage, } from "@langchain/core/messages"; import type { RunnableConfig } from "@langchain/core/runnables"; @@ -115,6 +121,15 @@ import { stopPromptCache, withCachedInstructions, } from "./prompt-cache.ts"; +import { + CONTINUE, + type FailureKind, + passingFailure, + pause, + RECONNECTED, + RECONNECTING, + Retries, +} from "./retry.ts"; import { signatureOf, signatureOfDelta, @@ -123,6 +138,23 @@ import { export type Emit = (event: BaseEvent) => void; +/** + * What one step has put on the person's screen so far, kept across its tries (`retry.ts`), so a try + * after a broken answer carries on the same message instead of starting another. + */ +type Carry = { + /** The step's message: its words, and the parent of its calls. */ + messageId: string; + /** Whether its TEXT_MESSAGE_START was sent. */ + textOpen: boolean; + /** The words it has said, across every try. */ + said: string; + /** Calls a broken try started and never finished, to be closed before the next try. */ + unfinished: string[]; + /** A try is under way after a failure, and says `openbot.reconnected` once it answers. */ + reconnecting: boolean; +}; + export type RunContext = { tools: readonly Tool[]; model: BaseChatModel; @@ -148,6 +180,17 @@ export type RunContext = { * or undefined where it is not. */ reminder: ReminderForm | undefined; + /** + * Whether a step whose model call failed for a passing reason is asked again here (`retry.ts`): + * always, but for a run the server retries itself (`openbotSendOnce`). + */ + retries: boolean; + /** + * A try that broke while it was writing a call was asked again: the half-written call is in the + * caller's thread, and the run ends with a MESSAGES_SNAPSHOT that holds only what the step made. + */ + brokeMidCall: boolean; + log: Pick; }; /** @@ -250,11 +293,18 @@ async function streamStep( model: BaseChatModel | ReturnType>, messages: BaseMessage[], run: RunContext, + carry: Carry, ): Promise { - const messageId = randomUUID(); + const messageId = carry.messageId; const slots = new Map(); - let textOpen = false; + // What earlier tries of this step said, which this one carries on (`retry.ts`). + const before = carry.said; let whole: AIMessageChunk | undefined; + const answering = () => { + if (!carry.reconnecting) return; + carry.reconnecting = false; + run.emit({ type: "CUSTOM", name: RECONNECTED, value: {} } as BaseEvent); + }; const start = (slot: Slot) => { slot.started = true; @@ -305,19 +355,39 @@ async function streamStep( // On a run that asked for Claude's progress updates, each one is said as the step's words, where // it was written: before the call it introduces. const words = run.progressUpdates ? new ProgressWords() : undefined; - const stream = await model.stream(messages, { signal: run.signal }); - for await (const chunk of stream as AsyncIterable) { - whole = whole ? whole.concat(chunk) : chunk; + try { + const stream = await model.stream(messages, { signal: run.signal }); + for await (const chunk of stream as AsyncIterable) { + answering(); + whole = whole ? whole.concat(chunk) : chunk; + take(chunk); + } + } catch (error) { + // A call this try started is left unfinished; it is closed if the step is asked again. + carry.unfinished = [...slots.values()] + .filter((slot) => slot.started && slot.id) + .map((slot) => slot.id as string); + throw error; + } + answering(); + if (carry.textOpen) + run.emit({ type: "TEXT_MESSAGE_END", messageId } as BaseEvent); + if (!whole) return new AIMessage({ id: messageId, content: before }); + return answered(whole); + + /** One chunk of the answer, said as it arrives. */ + function take(chunk: AIMessageChunk): void { const delta = words ? words.add(chunk.content) : chunk.text; if (delta) { - if (!textOpen) { - textOpen = true; + if (!carry.textOpen) { + carry.textOpen = true; run.emit({ type: "TEXT_MESSAGE_START", messageId, role: "assistant", } as BaseEvent); } + carry.said += delta; run.emit({ type: "TEXT_MESSAGE_CONTENT", messageId, delta } as BaseEvent); } for (const piece of callPieces(chunk)) { @@ -347,82 +417,111 @@ async function streamStep( if (signature) slotFor(delta).signature = signature; } } - if (textOpen) run.emit({ type: "TEXT_MESSAGE_END", messageId } as BaseEvent); - if (!whole) return new AIMessage({ id: messageId, content: "" }); - - const refusal = declined(whole); - if (refusal) throw new ModelDeclinedError(refusal); - - const ordered = [...slots.values()].sort((a, b) => a.index - b.index); - const parsed = whole.tool_calls ?? []; - /* - * A CALL WITH NO NAME IS NO CALL. FOUND LIVE ON OPENBOT CLOUD, 1 December 2026: a call this engine - * started with the name `""` was kept in the conversation, and every later turn in it was refused, - * by Claude (`tool_use.name: String should have at least 1 character`) and by Gemini - * (`function_response.name: Name cannot be empty`). No provider takes a call without a name and no - * tool answers to one, so it is left out: never started, never run, never sent back to the model. - * The server drops one too (openbot-backend `toolkit/src/nameless-calls.ts`), for every Bot. - */ - const nameless = new Set(); - const calls = ordered.flatMap((slot, position) => { - slot.id ??= parsed[position]?.id ?? randomUUID(); - slot.name ??= parsed[position]?.name ?? ""; - if (!slot.name.trim()) { - nameless.add(slot.id); - return []; - } - if (!slot.started) start(slot); - run.emit({ type: "TOOL_CALL_END", toolCallId: slot.id } as BaseEvent); - const sealed = signatureOf(parsed[position]) ?? slot.signature; - if (sealed) - run.emit({ - type: "REASONING_ENCRYPTED_VALUE", - subtype: "tool-call", - entityId: slot.id, - encryptedValue: sealed, - } as BaseEvent); - let args: Record = {}; - try { - const value = slot.args.trim() ? JSON.parse(slot.args) : {}; - if (value && typeof value === "object" && !Array.isArray(value)) - args = value; - } catch { - args = - (parsed[position]?.args as Record | undefined) ?? {}; - } - // What else the provider put on the call (Gemini's thought signature) stays with it. - return [ - { - ...(parsed[position] ?? {}), - id: slot.id, - name: slot.name, - args, - type: "tool_call" as const, - ...(sealed ? { thoughtSignature: sealed } : {}), - }, - ]; - }); - if (nameless.size > 0) - console.warn( - JSON.stringify({ - type: "nameless-tool-call-dropped", - where: "engine", - count: nameless.size, - }), - ); - // The provider's own content is kept for the rest of this run (Anthropic's thinking and tool_use - // blocks, progress updates among them, signed and unchanged; the Responses API's reasoning - // items), so a tool step continues the way it began. All but a nameless call's own block, which - // the provider would refuse on the next step of this run. - return new AIMessage({ - id: messageId, - content: withoutNamelessBlocks(whole.content, nameless) as never, - tool_calls: calls, - additional_kwargs: whole.additional_kwargs, - response_metadata: whole.response_metadata, - ...(whole.usage_metadata ? { usage_metadata: whole.usage_metadata } : {}), - }); + /** The step as the thread keeps it, once its answer is whole. */ + function answered(whole: AIMessageChunk): AIMessage { + const refusal = declined(whole); + if (refusal) throw new ModelDeclinedError(refusal); + + const ordered = [...slots.values()].sort((a, b) => a.index - b.index); + const parsed = whole.tool_calls ?? []; + /* + * A CALL WITH NO NAME IS NO CALL. FOUND LIVE ON OPENBOT CLOUD, 1 December 2026: a call this engine + * started with the name `""` was kept in the conversation, and every later turn in it was refused, + * by Claude (`tool_use.name: String should have at least 1 character`) and by Gemini + * (`function_response.name: Name cannot be empty`). No provider takes a call without a name and no + * tool answers to one, so it is left out: never started, never run, never sent back to the model. + * The server drops one too (openbot-backend `toolkit/src/nameless-calls.ts`), for every Bot. + */ + const nameless = new Set(); + const calls = ordered.flatMap((slot, position) => { + slot.id ??= parsed[position]?.id ?? randomUUID(); + slot.name ??= parsed[position]?.name ?? ""; + if (!slot.name.trim()) { + nameless.add(slot.id); + return []; + } + if (!slot.started) start(slot); + run.emit({ type: "TOOL_CALL_END", toolCallId: slot.id } as BaseEvent); + const sealed = signatureOf(parsed[position]) ?? slot.signature; + if (sealed) + run.emit({ + type: "REASONING_ENCRYPTED_VALUE", + subtype: "tool-call", + entityId: slot.id, + encryptedValue: sealed, + } as BaseEvent); + let args: Record = {}; + try { + const value = slot.args.trim() ? JSON.parse(slot.args) : {}; + if (value && typeof value === "object" && !Array.isArray(value)) + args = value; + } catch { + args = + (parsed[position]?.args as Record | undefined) ?? {}; + } + // What else the provider put on the call (Gemini's thought signature) stays with it. + return [ + { + ...(parsed[position] ?? {}), + id: slot.id, + name: slot.name, + args, + type: "tool_call" as const, + ...(sealed ? { thoughtSignature: sealed } : {}), + }, + ]; + }); + if (nameless.size > 0) + console.warn( + JSON.stringify({ + type: "nameless-tool-call-dropped", + where: "engine", + count: nameless.size, + }), + ); + + // The provider's own content is kept for the rest of this run (Anthropic's thinking and tool_use + // blocks, progress updates among them, signed and unchanged; the Responses API's reasoning + // items), so a tool step continues the way it began. All but a nameless call's own block, which + // the provider would refuse on the next step of this run. + return new AIMessage({ + id: messageId, + content: carriedOn( + before, + withoutNamelessBlocks(whole.content, nameless), + ) as never, + tool_calls: calls, + additional_kwargs: whole.additional_kwargs, + response_metadata: whole.response_metadata, + ...(whole.usage_metadata ? { usage_metadata: whole.usage_metadata } : {}), + }); + } +} + +/** Blocks a provider puts first in an answer, which a carried-on step's earlier words go after. */ +const LEADING = new Set(["thinking", "redacted_thinking", "reasoning"]); + +/** + * A step's content, carried on from a try that broke after saying `before` (`retry.ts`): the words + * said first, then what the try that answered said. Thinking stays first, where Anthropic asks for + * it, and nothing else of the answer moves. + */ +function carriedOn( + before: string, + content: AIMessageChunk["content"], +): AIMessageChunk["content"] { + if (!before) return content; + if (typeof content === "string") return `${before}${content}`; + const at = content.findIndex( + (block) => !LEADING.has(String((block as { type?: unknown }).type)), + ); + const split = at < 0 ? content.length : at; + return [ + ...content.slice(0, split), + { type: "text", text: before }, + ...content.slice(split), + ] as AIMessageChunk["content"]; } /** A step's content without the `tool_use` blocks of calls left out for having no name. */ @@ -446,6 +545,49 @@ function saidLine(message: AIMessage, progressUpdates: boolean): boolean { return words.trim() !== ""; } +/** + * Between two tries of a step: the calls the broken try started are closed, so no call is left + * open in the caller's thread (the snapshot the run then ends with holds only the calls the step finally + * made), the person is told the Bot is reconnecting, and the wait is waited, or the run stopped. + */ +async function reconnect( + run: RunContext, + carry: Carry, + kind: FailureKind, + next: { waitMs: number; attempt: number; attempts: number }, + error: unknown, +): Promise { + for (const toolCallId of carry.unfinished) + run.emit({ type: "TOOL_CALL_END", toolCallId } as BaseEvent); + if (carry.unfinished.length > 0) run.brokeMidCall = true; + carry.unfinished = []; + run.emit({ + type: "CUSTOM", + name: RECONNECTING, + value: { + attempt: next.attempt, + attempts: next.attempts, + retryInMs: next.waitMs, + }, + } as BaseEvent); + carry.reconnecting = true; + // The error's name and code only: its message can carry an address, its body a request. + const link = error as { name?: unknown; code?: unknown }; + run.log.warn( + JSON.stringify({ + type: "model-call-retrying", + kind, + attempt: next.attempt, + attempts: next.attempts, + waitMs: next.waitMs, + said: carry.said.length > 0, + error: typeof link?.name === "string" ? link.name : typeof error, + ...(typeof link?.code === "string" ? { code: link.code } : {}), + }), + ); + await pause(next.waitMs, run.signal); +} + async function answer(state: StateType, config: RunnableConfig) { const run = runOf(config); const offered = boundTools(run.tools); @@ -457,6 +599,15 @@ async function answer(state: StateType, config: RunnableConfig) { saidLine(message, run.progressUpdates), ) : []; + // This step's tries, and what it has put on the person's screen across them (`retry.ts`). + const tries = new Retries(); + const carry: Carry = { + messageId: randomUUID(), + textOpen: false, + said: "", + unfinished: [], + reconnecting: false, + }; for (;;) { // Only what this call sends is cleared: the run's own thread stays whole, for recall and for // the snapshot it hands back. @@ -486,11 +637,42 @@ async function answer(state: StateType, config: RunnableConfig) { : offered.length && run.model.bindTools ? run.model.bindTools(offered) : run.model; + // A try after an answer that broke part way carries on from its words (`CONTINUE`). + const asked = carry.said.trim() + ? [ + ...messages, + new AIMessage({ content: carry.said }), + new HumanMessage({ content: CONTINUE }), + ] + : messages; try { - const message = await streamStep(model, messages, run); + const message = await streamStep(model, asked, run, carry); + if (tries.count > 0) + run.log.warn( + JSON.stringify({ + type: "model-call-recovered", + retries: tries.count, + }), + ); return { messages: [message] }; } catch (error) { if (run.signal?.aborted) throw error; + // A passing failure (a dropped connection, a server error, an overload, a passing 429): the + // step is asked again after a wait, and the person sees "Reconnecting…" meanwhile. + const passing = run.retries ? passingFailure(error) : undefined; + const next = passing ? tries.next(passing) : undefined; + if (passing && next) { + await reconnect(run, carry, passing.kind, next, error); + continue; + } + if (passing && tries.count > 0) + run.log.warn( + JSON.stringify({ + type: "model-call-retries-used-up", + kind: passing.kind, + retries: tries.count, + }), + ); // A proxy in front of Claude that does not take context editing: clear here instead. if (clearsOnServer(run.model) && refusesContextEditing(error)) { stopContextEditing(run.model); @@ -605,6 +787,56 @@ export const graph = new StateGraph(State) .addConditionalEdges("tools", afterRecall, ["answer", END]) .compile(); +/** + * A message the graph added, as AG-UI carries it, for the snapshot a run ends with after a try that + * broke mid-call (`brokeMidCall`): its words as they streamed, Claude's progress updates included + * where the run asked for them, so the snapshot keeps the lines the person saw. + */ +function asAgui( + message: BaseMessage, + progressUpdates: boolean, +): Message | undefined { + const type = message.getType(); + if (type === "ai") { + const ai = message as AIMessage; + const calls = ai.tool_calls ?? []; + return { + id: ai.id ?? randomUUID(), + role: "assistant", + content: progressUpdates ? progressWords(ai.content) : ai.text, + ...(calls.length + ? { + toolCalls: calls.map((call) => { + const sealed = signatureOf(call); + return { + id: call.id ?? "", + type: "function" as const, + function: { + name: call.name, + arguments: JSON.stringify(call.args ?? {}), + }, + ...(sealed ? { encryptedValue: sealed } : {}), + }; + }), + } + : {}), + } as Message; + } + if (type === "tool") { + const tool = message as ToolMessage; + return { + id: tool.id ?? randomUUID(), + role: "tool", + toolCallId: tool.tool_call_id, + content: + typeof tool.content === "string" + ? tool.content + : JSON.stringify(tool.content), + } as Message; + } + return undefined; +} + /** * The calls this run made and left for the caller, in the order the model made them: every call * with no result in the run. AG-UI's `pendingToolCallIds` must be exactly these. @@ -708,6 +940,9 @@ export async function runAgent( model, emit, signal: options.signal, + retries: !choice.sendOnce, + brokeMidCall: false, + log, answersRecall: !offered.some((tool) => tool.name === RECALL), room: { stage: startingStage(input) }, progressUpdates: showsProgressUpdates(model), @@ -727,8 +962,21 @@ export async function runAgent( ); keepStage(input.threadId, run.room.stage); // No MESSAGES_SNAPSHOT: the step's events already built every message it added, in the - // caller's thread (see the module comment). + // caller's thread (see the module comment). But for a step asked again after a try that broke + // while it was writing a call: that call is in the caller's thread, half written, and only a + // snapshot takes it out again (`reconnect`). const all = final.messages as BaseMessage[]; + if (run.brokeMidCall) + emit({ + type: "MESSAGES_SNAPSHOT", + messages: [ + ...(input.messages ?? []), + ...all + .slice(thread.length) + .map((message) => asAgui(message, run.progressUpdates)) + .filter((message): message is Message => !!message), + ], + } as BaseEvent); const pending = pendingCalls(all.slice(thread.length)); emit({ type: "RUN_FINISHED", diff --git a/agent-langgraph-ts/test/fake-provider.ts b/agent-langgraph-ts/test/fake-provider.ts index ff211960de..287a1c3472 100644 --- a/agent-langgraph-ts/test/fake-provider.ts +++ b/agent-langgraph-ts/test/fake-provider.ts @@ -48,7 +48,8 @@ export type Turn = */ cut?: true; } - | { status: number; body: unknown } + /** An error answer, with the headers the provider sends beside it (`retry-after`). */ + | { status: number; body: unknown; headers?: Record } /** * A 200 whose stream begins, says `text` if there is any, and then carries the provider's error * as its own wire sends one part way (`streamedError`). @@ -782,7 +783,10 @@ export async function fakeProvider(respond: Responder): Promise { } const turn = respond(recorded, requests.length - 1); if ("status" in turn) { - response.writeHead(turn.status, { "content-type": "application/json" }); + response.writeHead(turn.status, { + "content-type": "application/json", + ...(turn.headers ?? {}), + }); response.end(JSON.stringify(turn.body)); return; } diff --git a/agent-langgraph-ts/test/model-gateway.ts b/agent-langgraph-ts/test/model-gateway.ts index 8b93f6c8f8..c69c90f299 100644 --- a/agent-langgraph-ts/test/model-gateway.ts +++ b/agent-langgraph-ts/test/model-gateway.ts @@ -190,10 +190,22 @@ export async function modelGateway( } recorded.status = reply.status; const passed: Record = {}; - for (const name of ["content-type", "request-id", "x-request-id"]) { - const value = reply.headers.get(name); - if (value) passed[name] = value; - } + // What the server's gateway hands back (`keptResponseHeader`): the type, and what a client needs + // to wait and retry. + reply.headers.forEach((value, name) => { + if ( + [ + "content-type", + "retry-after", + "retry-after-ms", + "request-id", + "x-request-id", + ].includes(name) || + name.startsWith("x-ratelimit-") || + name.startsWith("anthropic-ratelimit-") + ) + passed[name] = value; + }); response.writeHead(reply.status, passed); if (!reply.body) return response.end(); const body = Readable.fromWeb(reply.body as never); diff --git a/agent-langgraph-ts/test/model-route.test.ts b/agent-langgraph-ts/test/model-route.test.ts index 9922b27efc..48cae86efb 100644 --- a/agent-langgraph-ts/test/model-route.test.ts +++ b/agent-langgraph-ts/test/model-route.test.ts @@ -13,6 +13,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { inspect } from "node:util"; +import { RETRIES, useRetryTiming } from "../src/retry.ts"; import { always, type FakeProvider, @@ -661,10 +662,15 @@ const DECK = Array.from( `## Slide ${slide + 1}\n\n- Spotify's use case\n- The Java/ADK POC\n- Open question ${slide + 1}`, ).join("\n\n---\n\n"); -test("A model's stream that breaks part way through a call on the gateway's /v1/responses ends the run saying the connection dropped, and carrying on answers", async () => { +/* + * A stream that breaks once is asked again by the engine itself (reconnect.test.ts). One that keeps + * breaking through every try ends the run saying the connection dropped, as before. + */ +test("A model's stream that keeps breaking part way through a call on the gateway's /v1/responses ends the run, after every try, saying the connection dropped, and carrying on answers", async (t) => { if (live) return; // A broken stream is the fake provider's to script. + t.after(useRetryTiming({ firstWaitMs: 1, longestWaitMs: 2 })); const cut: Responder = (request, index) => - index === 0 + index <= RETRIES ? { text: "I'll make a short call deck around Spotify's use case and the Java/ADK POC.", calls: [ @@ -692,6 +698,7 @@ test("A model's stream that breaks part way through a call on the gateway's /v1/ gateway.requests[0]!.path, "/api/model-provider/v1/responses", ); + assert.equal(gateway.requests.length, RETRIES + 1, "every try was made"); // What the person saw before it broke stays: the line and the call it was making. assert.match(words(first.events), /short call deck/); assert.ok( diff --git a/agent-langgraph-ts/test/reconnect.test.ts b/agent-langgraph-ts/test/reconnect.test.ts new file mode 100644 index 0000000000..e11082ffc0 --- /dev/null +++ b/agent-langgraph-ts/test/reconnect.test.ts @@ -0,0 +1,434 @@ +/** + * A model call that fails for a passing reason is asked again by the engine itself, and the run + * finishes: no RUN_ERROR, no Carry on (src/retry.ts). + * + * FOUND ON OPENBOT CLOUD, 2026-12-04: a Bot on the gateway's /v1/responses was 17 steps into a turn + * when chatgpt.com reset the stream 0.6 s after it began. The engine read undici's + * `TypeError: terminated` (read ECONNRESET) and the run ended, so the turn stopped and the person had + * to press Carry on. Here the fake provider resets the socket the same way (a TCP RST part way + * through its real SSE), behind the gateway's contract, which breaks its answer with it. + */ +import assert from "node:assert/strict"; +import { after, before, test } from "node:test"; +import { inspect } from "node:util"; +import { RETRIES, useRetryTiming } from "../src/retry.ts"; +import { + always, + fakeProvider, + type Recorded, + type Responder, + type Turn, +} from "./fake-provider.ts"; +import { + conversation, + type Event, + run, + threadAfter, + withEngine, +} from "./helpers.ts"; +import { modelGateway } from "./model-gateway.ts"; + +// Ten tries at Claude Code's backoff take two minutes; the rule is the same at a millisecond. +let restore: () => void; +before(() => { + restore = useRetryTiming({ firstWaitMs: 1, longestWaitMs: 2 }); +}); +after(() => restore()); + +const SLIDES_TOOL = { + name: "GOOGLESLIDES_CREATE_SLIDES_MARKDOWN", + description: "Create a Google Slides presentation from Markdown.", + parameters: { + type: "object", + properties: { title: { type: "string" }, markdown: { type: "string" } }, + required: ["title", "markdown"], + }, +}; + +const DECK = Array.from( + { length: 40 }, + (_, slide) => + `## Slide ${slide + 1}\n\n- The use case\n- Open question ${slide + 1}`, +).join("\n\n---\n\n"); + +const LINE = "I'll make a short call deck around the use case."; + +const ask = (overrides: Record = {}) => + conversation({ + messages: [ + { + id: "standing-role:test-bot", + role: "system", + content: "You are Test Bot.", + }, + { id: "u1", role: "user", content: "Make me a call deck." }, + ], + ...overrides, + }); + +function words(events: Event[]): string { + return events + .filter((event) => event.type === "TEXT_MESSAGE_CONTENT") + .map((event) => String(event.delta)) + .join(""); +} + +function custom(events: Event[], name: string): Event[] { + return events.filter( + (event) => event.type === "CUSTOM" && event.name === name, + ); +} + +/** The run's last event, which must be its one terminal event. */ +function finished(events: Event[]): Event { + const last = events.at(-1)!; + assert.equal(last.type, "RUN_FINISHED", inspect(last, { depth: 4 })); + assert.equal( + events.filter((event) => event.type === "RUN_ERROR").length, + 0, + "no RUN_ERROR: the person is never asked to carry on", + ); + return last; +} + +/** The words of every message a request sent the model, in order, by role. */ +function sentText(request: Recorded): string { + return JSON.stringify(request.body); +} + +test("A stream that breaks part way through a call on the gateway's /v1/responses is asked again by itself, and the run finishes with the call", async () => { + const fake = await fakeProvider((_, index) => + index === 0 + ? { + text: LINE, + calls: [ + { + id: "call_slides", + name: SLIDES_TOOL.name, + args: { title: "Call deck", markdown: DECK }, + }, + ], + cut: true, + } + : { + calls: [ + { + id: "call_slides_again", + name: SLIDES_TOOL.name, + args: { title: "Call deck", markdown: "## One slide" }, + }, + ], + }, + ); + const gateway = await modelGateway( + { + openai: { base: fake.base, key: "sk-upstream" }, + anthropic: { base: fake.base, key: "sk-ant-upstream" }, + }, + "openai", + ); + try { + gateway.mint("run-token"); + const input = ask({ + tools: [SLIDES_TOOL], + forwardedProps: { + openbotModel: { model: "gpt-5.6-terra", reasoningEffort: "low" }, + openbotModelRoute: { via: "openai", token: "run-token" }, + }, + }); + const result = await withEngine( + { + env: { + OPENBOT_MODEL_GATEWAY_URL: gateway.url, + BOT_PROVIDER: "openai", + OPENAI_API_KEY: "", + }, + }, + (base) => run(base, input), + ); + const done = finished(result.events); + assert.equal(gateway.requests.length, 2, "asked once more, not more"); + assert.equal(gateway.requests[1]!.path, "/api/model-provider/v1/responses"); + // The line the person saw is said once, and the try after the break carried on from it. + assert.equal(words(result.events), LINE); + assert.match( + sentText(fake.requests[1]!), + /interrupted by a dropped connection/, + ); + assert.ok(sentText(fake.requests[1]!).includes(LINE)); + // Reconnecting while it waited, and back once the answer came. + const reconnecting = custom(result.events, "openbot.reconnecting"); + assert.equal(reconnecting.length, 1); + const value = reconnecting[0]!.value as Record; + assert.equal(value.attempt, 1); + assert.equal(value.attempts, RETRIES); + assert.equal(typeof value.retryInMs, "number"); + assert.equal(custom(result.events, "openbot.reconnected").length, 1); + // The step's one message, under one id: the line, and the call the answered try made. + const starts = result.events.filter( + (event) => event.type === "TEXT_MESSAGE_START", + ); + assert.equal(starts.length, 1); + assert.deepEqual( + (done.outcome as { pendingToolCallIds?: string[] }).pendingToolCallIds, + ["call_slides_again"], + ); + // What the caller holds after applying the events, as the server and the browser apply them. + const thread = await threadAfter(input, result.events); + const reply = thread.at(-1) as { + role: string; + content?: string; + toolCalls?: { id: string }[]; + }; + assert.equal(reply.role, "assistant"); + assert.equal(reply.content, LINE); + assert.deepEqual( + reply.toolCalls?.map((call) => call.id), + ["call_slides_again"], + "the broken try's half-written call is not kept", + ); + } finally { + await gateway.close(); + await fake.close(); + } +}); + +type Provider = "openai" | "anthropic" | "google"; + +function envFor(provider: Provider, base: string): Record { + if (provider === "anthropic") + return { + BOT_PROVIDER: "anthropic", + ANTHROPIC_API_KEY: "sk-ant-test", + ANTHROPIC_BASE_URL: base, + }; + if (provider === "google") + return { + BOT_PROVIDER: "google", + GOOGLE_API_KEY: "AIza-test", + GOOGLE_GENERATIVE_AI_BASE_URL: `${base}/v1beta`, + }; + return { + BOT_PROVIDER: "openai", + OPENAI_API_KEY: "sk-test", + OPENAI_BASE_URL: `${base}/v1`, + }; +} + +async function runOn(provider: Provider, respond: Responder) { + const fake = await fakeProvider(respond); + try { + const result = await withEngine( + { env: envFor(provider, fake.base) }, + (base) => run(base, conversation()), + ); + return { events: result.events, requests: fake.requests }; + } finally { + await fake.close(); + } +} + +/** The first `failures` answers fail as `turn` does; then the model answers. */ +const failingThen = + (failures: number, turn: Turn): Responder => + (_, index) => + index < failures ? turn : { text: "Pineapple." }; + +for (const provider of ["openai", "anthropic", "google"] as const) { + test(`${provider}: a connection reset part way through an answer is asked again, and the run finishes`, async () => { + const result = await runOn( + provider, + failingThen(1, { text: "Half an answer that never arrives", cut: true }), + ); + finished(result.events); + assert.equal(result.requests.length, 2); + assert.match(words(result.events), /Pineapple\.$/); + assert.equal(custom(result.events, "openbot.reconnecting").length, 1); + }); +} + +test("Anthropic overloaded part way through its stream is asked again, and the run finishes", async () => { + const result = await runOn( + "anthropic", + failingThen(2, { + streamError: { + type: "error", + error: { type: "overloaded_error", message: "Overloaded" }, + }, + }), + ); + finished(result.events); + assert.equal(result.requests.length, 3); + assert.equal(words(result.events), "Pineapple."); + assert.deepEqual( + custom(result.events, "openbot.reconnecting").map( + (event) => (event.value as { attempt: number }).attempt, + ), + [1, 2], + ); +}); + +test("A 529 and a 503 before the answer begins are asked again, and the run finishes", async () => { + const result = await runOn("anthropic", (_, index) => + index === 0 + ? { + status: 529, + body: { + type: "error", + error: { type: "overloaded_error", message: "Overloaded" }, + }, + } + : index === 1 + ? { + status: 503, + body: { + type: "error", + error: { type: "api_error", message: "Service unavailable" }, + }, + } + : { text: "Pineapple." }, + ); + finished(result.events); + assert.equal(result.requests.length, 3); +}); + +test("A passing 429 waits the time the provider asked for, then answers", async () => { + const started = Date.now(); + const result = await runOn("openai", (_, index) => + index === 0 + ? { + status: 429, + headers: { "retry-after-ms": "300" }, + body: { + error: { + message: + "Rate limit reached for gpt-4.1 on tokens per min (TPM).", + type: "tokens", + code: "rate_limit_exceeded", + }, + }, + } + : { text: "Pineapple." }, + ); + finished(result.events); + assert.equal(result.requests.length, 2); + assert.ok(Date.now() - started >= 300, "the provider's wait was kept to"); + assert.equal( + ( + custom(result.events, "openbot.reconnecting")[0]!.value as { + retryInMs: number; + } + ).retryInMs, + 300, + ); +}); + +test("A customer's own quota (a 429 that is not a throttle) is said at once, never asked again", async () => { + const result = await runOn( + "openai", + always({ + status: 429, + body: { + error: { + message: + "You exceeded your current quota, please check your plan and billing details.", + type: "insufficient_quota", + code: "insufficient_quota", + }, + }, + }), + ); + assert.equal(result.requests.length, 1); + assert.equal(result.events.at(-1)!.type, "RUN_ERROR"); + assert.equal(result.events.at(-1)!.code, "OPENBOT_MODEL_BILLING"); + assert.equal(custom(result.events, "openbot.reconnecting").length, 0); +}); + +test("A 429 asking for a longer wait than a minute is said, not waited out", async () => { + const result = await runOn( + "openai", + always({ + status: 429, + headers: { "retry-after": "600" }, + body: { + error: { + message: "Rate limit reached for gpt-4.1 on requests per day (RPD).", + type: "requests", + code: "rate_limit_exceeded", + }, + }, + }), + ); + assert.equal(result.requests.length, 1); + assert.equal(result.events.at(-1)!.type, "RUN_ERROR"); + assert.equal( + (result.events.at(-1) as { metadata?: { errorCategory?: string } }).metadata + ?.errorCategory, + "rate_limit", + ); +}); + +test("A request the provider can't take is never asked again", async () => { + const result = await runOn( + "anthropic", + always({ + status: 400, + body: { + type: "error", + error: { + type: "invalid_request_error", + message: + "messages.1.content.0.image.source.base64: invalid base64 data", + }, + }, + }), + ); + assert.equal(result.requests.length, 1); + assert.equal(result.events.at(-1)!.type, "RUN_ERROR"); +}); + +test("A connection that keeps dropping is asked again ten times, and then the run says the connection dropped, as before", async () => { + const result = await runOn( + "openai", + always({ text: "Half an answer that never arrives", cut: true }), + ); + assert.equal( + result.requests.length, + RETRIES + 1, + "the first ask and ten more", + ); + assert.equal(custom(result.events, "openbot.reconnecting").length, RETRIES); + const error = result.events.at(-1) as { + type: string; + message: string; + code?: string; + }; + assert.equal(error.type, "RUN_ERROR"); + assert.equal(error.code, "OPENBOT_MODEL_REFUSED"); + assert.match( + error.message, + /^Connection dropped \((ECONNRESET|terminated|other side closed|UND_ERR_SOCKET)\) before your model provider finished answering\.$/, + ); + assert.equal( + result.events.filter((event) => event.type === "RUN_ERROR").length, + 1, + ); +}); + +test("A run the server retries itself (openbotSendOnce) is asked once, as before", async () => { + const fake = await fakeProvider( + always({ text: "Half an answer that never arrives", cut: true }), + ); + try { + const result = await withEngine( + { env: envFor("openai", fake.base) }, + (base) => + run(base, conversation({ forwardedProps: { openbotSendOnce: true } })), + ); + assert.equal(fake.requests.length, 1); + assert.equal(result.events.at(-1)!.type, "RUN_ERROR"); + assert.equal(custom(result.events, "openbot.reconnecting").length, 0); + } finally { + await fake.close(); + } +});