An open-source, faster Devin alternative
TypeScript
Classify a model call's failure from the runtime's typed fields
Igor Zalutskia0fc70d0e416
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex f182a81b..1287fa2f 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -3470,54 +3470,96 @@ describe("managed agents proxy", () => {code: "model_rejected",message: "The model provider rejected the request.",});- // The runtime's typed model-call failures: the class decides, the- // provider's own text after the colon is never forwarded.- expect(- publicFailure({- message:- "Model call failed (provider.internal 502) for anthropic/claude-sonnet-4.6: upstream socket hang up never-return-this",- }),- ).toEqual({+ // The typed fields the runtime records with a provider failure decide+ // the code; the provider's text is never forwarded.+ const providerFailure = (+ subtype: string,+ extra: Record<string, unknown> = {},+ attempts = 1,+ ) => ({+ message: "upstream said: sk-ant-never x-api-key rejected",+ failure: {+ class: "provider",+ subtype,+ provider: "openrouter",+ model: "anthropic/claude-sonnet-4.6",+ retry: { attempts, hostGranted: attempts > 1 },+ ...extra,+ },+ });+ expect(publicFailure(providerFailure("transport", {}, 2))).toEqual({code: "model_stream_failed",message:- "The model call to anthropic/claude-sonnet-4.6 failed before it finished, and its retry failed too.",+ "The model call to anthropic/claude-sonnet-4.6 failed before it finished and its retry failed too.",model: "anthropic/claude-sonnet-4.6",});- expect(- publicFailure({ message: "Model call failed (provider.transport): socket hang up" }),- ).toEqual({+ // A call that bypassed the retry (compaction, titling) failed once: no+ // retry is claimed.+ expect(publicFailure(providerFailure("internal", { status: 502 }))).toEqual({code: "model_stream_failed",- message: "The model call failed before it finished, and its retry failed too.",+ message:+ "The model call to anthropic/claude-sonnet-4.6 failed before it finished.",+ model: "anthropic/claude-sonnet-4.6",});expect(publicFailure({- message: "Model call failed (provider.invalid-output) for anthropic/claude-sonnet-4.6: The provider response ended with an unknown finish reason.",+ message: "socket hang up",+ failure: { class: "provider", subtype: "invalid-output", retry: { attempts: 3, hostGranted: false } },}),).toEqual({code: "model_stream_failed",- message:- "The model call to anthropic/claude-sonnet-4.6 failed before it finished, and its retry failed too.",- model: "anthropic/claude-sonnet-4.6",+ message: "The model call failed before it finished and its retry failed too.",});+ // A model id with a variant suffix survives intact.expect(- publicFailure({ message: "Model call failed (provider.auth 401) for anthropic/claude-sonnet-4.6: invalid x-api-key sk-ant-never" }),+ publicFailure(+ providerFailure("unknown", { model: "meta-llama/llama-3.3-70b-instruct:free" }, 2),+ ),).toEqual({- code: "model_rejected",- message: "The model provider rejected the request.",+ code: "model_stream_failed",+ message:+ "The model call to meta-llama/llama-3.3-70b-instruct:free failed before it finished and its retry failed too.",+ model: "meta-llama/llama-3.3-70b-instruct:free",});- expect(- publicFailure({ message: "Model call failed (provider.rate-limit 429): rate limited" }),- ).toEqual({+ for (const subtype of ["auth", "quota", "content-filter", "rate-limit"]) {+ expect(publicFailure(providerFailure(subtype, { status: 429 }))).toEqual({+ code: "model_rejected",+ message: "The model provider rejected the request.",+ });+ }+ expect(publicFailure(providerFailure("invalid-request", { status: 400 }))).toEqual({code: "model_rejected",message: "The model provider rejected the request.",});+ // An invalid request because the conversation outgrew the window.expect(- publicFailure({ message: "Model call failed (provider.no-route) for openai/gpt-5: no route" }),+ publicFailure({+ ...providerFailure("invalid-request", { status: 400 }),+ message: "prompt is too long: 214000 tokens > 200000 maximum context length",+ }),).toEqual({+ code: "context_too_long",+ message: "The conversation is too long for the model's context window.",+ });+ expect(publicFailure(providerFailure("no-route", { model: "openai/gpt-5" }))).toEqual({code: "model_unavailable",message: "The model openai/gpt-5 is not available to this agent.",model: "openai/gpt-5",});+ // A credential-shaped model id is dropped, never echoed.+ expect(+ publicFailure(providerFailure("transport", { model: "sk-ant-api03-0123456789abcdefghijklmnop" }, 2)),+ ).toEqual({+ code: "model_stream_failed",+ message: "The model call failed before it finished and its retry failed too.",+ });+ // Fields of another class fall through to the text rules.+ expect(+ publicFailure({+ message: "Sandbox operation timed out",+ failure: { class: "tool", subtype: "execution", retry: { attempts: 1, hostGranted: false } },+ }),+ ).toEqual({ code: "sandbox_timeout", message: "A sandbox command did not finish in time." });expect(publicFailure({message: "prompt is too long: 214000 tokens > 200000 maximum context length",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex a5384c67..2412d582 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -924,8 +924,7 @@ const PUBLIC_FAILURE_MESSAGES: Record<PublicFailureCode, string> = {tool_failed: "A tool failed.",sandbox_timeout: "A sandbox command did not finish in time.",sandbox_failed: "The sandbox could not run this turn.",- model_stream_failed:- "The model call failed before it finished, and its retry failed too.",+ model_stream_failed: "The model call failed before it finished.",agent_failed: GENERIC_FAILURE_MESSAGE,};@@ -952,6 +951,11 @@ function validParameter(pattern: RegExp, value: string | undefined) {: undefined;}+// The runtime's word that the conversation outgrew the model's window, in+// the provider's text.+const CONTEXT_TOO_LONG =+ /context (?:length|window|overflow)|too long|exceeds? the (?:maximum )?(?:context|token)|ContextOverflow/i;+// Message rules, first match wins. Each names the runtime error family it// recognizes; the captured group, if any, is the parameter.const FAILURE_MESSAGE_RULES: ReadonlyArray<{@@ -959,31 +963,6 @@ const FAILURE_MESSAGE_RULES: ReadonlyArray<{pattern: RegExp;parameter?: "model" | "tool";}> = [- // A model call the runtime named by its typed class, before any free text:- // `Model call failed (provider.<class>[ <status>])[ for <model>]: …`.- // The class decides: a rejection stays a rejection, a route with no model- // is unavailable, and everything transport-shaped failed after its retry.- {- code: "model_rejected",- pattern:- /^Model call failed \(provider\.(?:auth|quota|content-filter|invalid-request|rate-limit)\b/,- },- {- code: "model_unavailable",- pattern: /^Model call failed \(provider\.no-route(?: \d+)?\) for ([^\s:]+)/,- parameter: "model",- },- { code: "model_unavailable", pattern: /^Model call failed \(provider\.no-route\b/ },- {- code: "model_stream_failed",- pattern:- /^Model call failed \(provider\.(?:transport|internal|invalid-output|unknown)(?: \d+)?\) for ([^\s:]+)/,- parameter: "model",- },- {- code: "model_stream_failed",- pattern: /^Model call failed \(provider\.(?:transport|internal|invalid-output|unknown)\b/,- },{code: "model_unavailable",pattern: /rejects any useModel other than \S+ \(requested (\S+)\)/,@@ -999,11 +978,7 @@ const FAILURE_MESSAGE_RULES: ReadonlyArray<{pattern:/\bmodel (?:is )?not (?:found|available|supported)\b|ModelNotFound/i,},- {- code: "context_too_long",- pattern:- /context (?:length|window|overflow)|too long|exceeds? the (?:maximum )?(?:context|token)|ContextOverflow/i,- },+ { code: "context_too_long", pattern: CONTEXT_TOO_LONG },{code: "model_rejected",pattern:@@ -1039,6 +1014,71 @@ const FAILURE_MESSAGE_RULES: ReadonlyArray<{},];+// A model call's failure by the provider's typed class, as the runtime+// records it in the failure's `failure` fields. A rejection stays one, a+// route with no model is unavailable, and everything that failed in flight+// (the transport, the provider, a broken or malformed response) is+// `model_stream_failed`.+const PROVIDER_FAILURE_CODES: Record<string, PublicFailureCode> = {+ auth: "model_rejected",+ quota: "model_rejected",+ "content-filter": "model_rejected",+ "rate-limit": "model_rejected",+ "invalid-request": "model_rejected",+ "no-route": "model_unavailable",+ transport: "model_stream_failed",+ internal: "model_stream_failed",+ "invalid-output": "model_stream_failed",+ unknown: "model_stream_failed",+};++/**+ * The public failure from the typed fields the runtime recorded, when it+ * recorded a provider failure: `{ class: "provider", subtype, model?,+ * retry: { attempts } }`. The provider's text decides one thing only, on+ * an invalid request: whether the conversation outgrew the model's window.+ * The retry is named only when one happened; a call that bypasses the+ * runtime's retry (compaction, titling) fails on its first attempt.+ */+function structuredFailure(+ data: Record<string, unknown>,+ firstLine: string,+): PublicFailure | undefined {+ const failure = record(data.failure);+ if (!failure || failure.class !== "provider") return undefined;+ const subtype = typeof failure.subtype === "string" ? failure.subtype : "";+ const code = PROVIDER_FAILURE_CODES[subtype];+ if (!code) return undefined;+ if (subtype === "invalid-request" && CONTEXT_TOO_LONG.test(firstLine)) {+ return {+ code: "context_too_long",+ message: PUBLIC_FAILURE_MESSAGES.context_too_long,+ };+ }+ const model = validParameter(+ MODEL_ID,+ typeof failure.model === "string" ? failure.model : undefined,+ );+ if (code === "model_unavailable" && model) {+ return {+ code,+ message: `The model ${model} is not available to this agent.`,+ model,+ };+ }+ if (code === "model_stream_failed") {+ const retry = record(failure.retry);+ const retried =+ typeof retry?.attempts === "number" && retry.attempts > 1;+ return {+ code,+ message: `The model call${model ? ` to ${model}` : ""} failed before it finished${retried ? " and its retry failed too" : ""}.`,+ ...(model ? { model } : {}),+ };+ }+ return { code, message: PUBLIC_FAILURE_MESSAGES[code] };+}+export function publicFailure(value: unknown): PublicFailure {const data = record(value) ?? {};const reason = typeof data.reason === "string" ? data.reason : "";@@ -1048,6 +1088,10 @@ export function publicFailure(value: unknown): PublicFailure {// Classification reads only the first line: the sentence the runtime// wrote, before any stack frame or cause chain.const firstLine = message.split(/\r?\n/, 1)[0].trim();+ // The runtime's typed fields come first; the text rules serve runtimes+ // that recorded none.+ const structured = structuredFailure(data, firstLine);+ if (structured) return structured;for (const rule of FAILURE_MESSAGE_RULES) {const match = firstLine.match(rule.pattern);if (!match) continue;@@ -1056,10 +1100,7 @@ export function publicFailure(value: unknown): PublicFailure {if (model) {return {code: rule.code,- message:- rule.code === "model_stream_failed"- ? `The model call to ${model} failed before it finished, and its retry failed too.`- : `The model ${model} is not available to this agent.`,+ message: `The model ${model} is not available to this agent.`,model,};}diff --git a/docs/agents/events.mdx b/docs/agents/events.mdxindex 911851be..ae91c796 100644--- a/docs/agents/events.mdx+++ b/docs/agents/events.mdx@@ -83,12 +83,15 @@ A failure's `data` is a stable `code`, a fixed `message` for that code, andat most one parameter. The runtime's own error text is never sent; a failureno rule recognizes is `agent_failed`.-A model call that fails or whose response stream breaks is retried once-inside the turn before the turn fails; the retry appears in the log as a-`runtime.log` milestone with `phase: "model_retry"`, the attempt and the-failure's class (for example `provider.transport`), never the provider's-own text. A rejection is not retried: credentials, quota, content policy-and an invalid request are `model_rejected` at once.+A model call that fails in flight is retried inside the turn before the+turn fails: provider errors and rate limits on the runtime's own schedule,+and a transport failure or a response stream that breaks once more. Each+retry appears in the log as a `runtime.log` milestone with+`phase: "model_retry"`, the attempt and the failure's class (for example+`provider.transport`), never the provider's own text. A rejection is not+retried: credentials, quota, content policy and an invalid request are+`model_rejected` at once. A `model_stream_failed` message names its retry+only when one happened.| `code` | Meaning | Parameter || --- | --- | --- |@@ -103,7 +106,7 @@ and an invalid request are `model_rejected` at once.| `tool_failed` | A tool failed | `tool`: the tool id, when the runtime named it || `sandbox_timeout` | A sandbox command did not finish in time | || `sandbox_failed` | The sandbox could not run the turn | |-| `model_stream_failed` | The model call failed before it finished, or its response stream broke, and the retry failed too | `model`: the model id, when known |+| `model_stream_failed` | The model call failed before it finished, or its response stream broke; when it was retried, the retry failed too | `model`: the model id, when known || `agent_failed` | Any other failure | |### Messages