An open-source, faster Devin alternative
TypeScript
api-edge: typed public failures replace regex redaction of runtime errors
Igor Zalutski836d985d0a99
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 40deae3f..e3524af5 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -6,7 +6,7 @@ import {hasBYOKPlanAccess,mintManagedAgentsAssertion,proxyManagedAgents,- publicFailureMessage,+ publicFailure,} from "./managed_agents";function legacyPlanEnv(plan: string) {@@ -2312,9 +2312,10 @@ describe("managed agents proxy", () => {});});- // A failed turn carries its reason so the user can act on it; the reason is- // an operator-facing Error message, so paths, URLs and credentials go.- it("passes a sanitized turn failure reason through the event stream", async () => {+ // A failed turn carries a typed public failure: a stable code, a fixed+ // sentence and validated parameters. The runtime's own error text is an+ // operator message and never leaves the edge, whatever it contains.+ it("projects a turn failure as a typed public failure through the event stream", async () => {vi.stubGlobal("fetch",vi.fn(async () =>@@ -2338,6 +2339,19 @@ describe("managed agents proxy", () => {seq: 10,timestamp: "2026-09-10T00:00:01.000Z",sessionId: "session-1",+ turnId: "turn-2",+ type: "turn.failed",+ data: {+ message:+ "The agent runtime stopped reporting on this turn and its lease expired",+ reason: "runtime_lost",+ },+ },+ {+ id: "event_3",+ seq: 11,+ timestamp: "2026-09-10T00:00:02.000Z",+ sessionId: "session-1",type: "session.failed",data: {},},@@ -2359,49 +2373,158 @@ describe("managed agents proxy", () => {};expect(body.events[0].data).toEqual({- message:- "The Workerd runtime rejects any useModel other than anthropic/claude-sonnet-4.6 (requested openai/gpt-5)",+ code: "model_unavailable",+ message: "The model openai/gpt-5 is not available to this agent.",+ model: "openai/gpt-5",});expect(body.events[1].data).toEqual({+ code: "runtime_lost",+ message:+ "The agent runtime stopped responding and the turn was abandoned.",+ });+ expect(body.events[2].data).toEqual({+ code: "agent_failed",message: "The agent could not complete this request.",});expect(JSON.stringify(body)).not.toContain("never-return-this");+ expect(JSON.stringify(body)).not.toContain("Workerd");});- it("strips paths, URLs, credentials and stack frames from failure reasons", () => {+ it("classifies known runtime failures into typed public failures", () => {+ expect(publicFailure({ reason: "interrupted" })).toEqual({+ code: "interrupted",+ message: "The turn was interrupted before it finished.",+ });expect(- publicFailureMessage({- message: [- "ENOENT: no such file or directory, open '/Users/dev/app/.opencomputer/agent.js'",- " at Object.openSync (node:fs:581:3)",- " at /home/runner/work/index.js:12:5",- ].join("\n"),+ publicFailure({+ message: "OpenCode execution was interrupted",+ reason: "runtime_interrupted",}),- ).toBe("ENOENT: no such file or directory, open '<path>'");+ ).toEqual({+ code: "interrupted",+ message: "The turn was interrupted before it finished.",+ });+ expect(publicFailure({ reason: "session_ended" })).toEqual({+ code: "session_ended",+ message: "The session ended before the turn finished.",+ });+ expect(+ publicFailure({ message: "Model unavailable: openai/gpt-5-mini" }),+ ).toEqual({+ code: "model_unavailable",+ message: "The model openai/gpt-5-mini is not available to this agent.",+ model: "openai/gpt-5-mini",+ });+ // A model id that is not a model id is not echoed.+ expect(+ publicFailure({ message: "Model unavailable: sk-ant-api03-0123456789abcdefghijklmnop/x" }),+ ).toEqual({+ code: "model_unavailable",+ message: "The requested model is not available to this agent.",+ });expect(- publicFailureMessage({+ publicFailure({message:- "fetch to http://127.0.0.1:4096/session/ses_1/message?token=abc failed: Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijklmnopqrstuvwxyz",+ "AI_APICallError: 401 Unauthorized: invalid x-api-key sk-ant-api03-0123456789abcdefghijklmnop",}),- ).toBe("fetch to <url> failed: Authorization: Bearer <redacted>");+ ).toEqual({+ code: "model_rejected",+ message: "The model provider rejected the request.",+ });expect(- publicFailureMessage({- message:- "provider rejected api_key=sk-ant-api03-0123456789abcdefghijklmnop and osb_0123456789abcdef; retry",+ publicFailure({ message: "Rate limit exceeded; retry after 20s" }),+ ).toEqual({+ code: "model_rejected",+ message: "The model provider rejected the request.",+ });+ expect(+ publicFailure({+ message: "prompt is too long: 214000 tokens > 200000 maximum context length",}),- ).toBe("provider rejected api_key=<redacted> and <redacted>; retry");+ ).toEqual({+ code: "context_too_long",+ message: "The conversation is too long for the model's context window.",+ });+ expect(+ publicFailure({ message: "Tool module exported an unregistered tool: lookup_venue" }),+ ).toEqual({+ code: "tool_failed",+ message: "Tool lookup_venue failed.",+ tool: "lookup_venue",+ });+ expect(publicFailure({ message: "The tool has no edge implementation" })).toEqual({+ code: "tool_failed",+ message: "A tool failed.",+ });+ expect(publicFailure({ message: "Sandbox operation timed out" })).toEqual({+ code: "sandbox_timeout",+ message: "A sandbox command did not finish in time.",+ });expect(- publicFailureMessage({- reason: "Runtime harness is not ready\u0007",+ publicFailure({+ message: "Sandbox acquisition returned 503: {\"error\":\"no capacity in us-east\"}",}),- ).toBe("Runtime harness is not ready");- const long = publicFailureMessage({- message: "The turn exceeded its budget. ".repeat(40),+ ).toEqual({+ code: "sandbox_failed",+ message: "The sandbox could not run this turn.",});- expect(long).toHaveLength(500);- expect(long.endsWith("\u2026")).toBe(true);- expect(publicFailureMessage(undefined)).toBe(- "The agent could not complete this request.",- );+ expect(publicFailure({ reason: "Runtime harness is not ready\u0007" })).toEqual({+ code: "runtime_failed",+ message: "The agent runtime failed before the turn finished.",+ });+ expect(publicFailure({ message: "The Workerd runtime stream ended before the turn did" })).toEqual({+ code: "runtime_failed",+ message: "The agent runtime failed before the turn finished.",+ });+ expect(+ publicFailure({ message: "The deployment is missing tool module \"tools/x.js\"" }),+ ).toEqual({+ code: "deployment_invalid",+ message: "The deployment could not be loaded by the runtime.",+ });+ expect(publicFailure(undefined)).toEqual({+ code: "agent_failed",+ message: "The agent could not complete this request.",+ });+ });++ // Review reproductions: text the label-and-length redaction used to let+ // through. None of it is public now, because no runtime text is.+ it("never publishes unclassified runtime error text", () => {+ const leaks = [+ 'provider rejected {"api_key":"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6"} for org 42',+ "fetch failed: Authorization: Basic dXNlcjpwYXNz was refused",+ "connect to db: password=hunter2 host=10.0.0.5",+ [+ "ENOENT: no such file or directory, open '/Users/dev/app/.opencomputer/agent.js'",+ " at Object.openSync (node:fs:581:3)",+ ].join("\n"),+ "fetch to http://127.0.0.1:4096/session/ses_1/message?token=abc failed",+ "The turn exceeded its budget. ".repeat(40),+ ];+ expect(publicFailure({ message: leaks[3] })).toEqual({+ code: "agent_failed",+ message: "The agent could not complete this request.",+ });+ for (const message of leaks) {+ const failure = publicFailure({ message });+ // Whatever the classification, nothing but a fixed sentence goes out.+ expect(Object.keys(failure).sort()).toEqual(["code", "message"]);+ expect(failure.message).toMatch(/^[A-Z][a-z' ]+\.$/);+ const serialized = JSON.stringify(failure);+ expect(serialized).not.toContain("a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6");+ expect(serialized).not.toContain("dXNlcjpwYXNz");+ expect(serialized).not.toContain("hunter2");+ expect(serialized).not.toContain("/Users/dev");+ expect(serialized).not.toContain("127.0.0.1");+ }+ // Parameters are the only runtime-derived text, and they are validated:+ // a credential in a model or tool position is dropped.+ expect(+ publicFailure({+ message:+ "Tool module exported an unregistered tool: sk-ant-api03-0123456789abcdefghijklmnop",+ }),+ ).toEqual({ code: "tool_failed", message: "A tool failed." });});});diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 5beba837..edfa72da 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -678,50 +678,170 @@ const PRIVATE_EVENT_KEYS = new Set(["platform_instructions",]);+export type PublicFailureCode =+ | "interrupted"+ | "session_ended"+ | "runtime_lost"+ | "runtime_failed"+ | "deployment_invalid"+ | "model_unavailable"+ | "model_rejected"+ | "context_too_long"+ | "tool_failed"+ | "sandbox_timeout"+ | "sandbox_failed"+ | "agent_failed";++/**+ * What a `turn.failed` or `session.failed` event says in public: a stable+ * code, a fixed sentence, and at most one validated parameter. The runtime's+ * own error text is written for operators and can carry anything (paths,+ * internal URLs, credentials, stack frames), so it is classified here and+ * never forwarded. A failure no rule recognizes is `agent_failed`.+ */+export interface PublicFailure {+ code: PublicFailureCode;+ message: string;+ /** The model the agent asked for, when the runtime rejected it by id. */+ model?: string;+ /** The tool that failed, when the runtime named it. */+ tool?: string;+}+const GENERIC_FAILURE_MESSAGE = "The agent could not complete this request.";-const FAILURE_MESSAGE_LIMIT = 500;-// A turn or session failure reason is an Error message from the runtime,-// written for operators: it names what went wrong (a rejected model, a tool-// that is not available, a harness that never became ready) and the user-// needs that to act. It can also carry what the user must not see: absolute-// paths, internal URLs, credentials, stack frames. Keep the sentence, drop-// those.-export function publicFailureMessage(value: unknown): string {+const PUBLIC_FAILURE_MESSAGES: Record<PublicFailureCode, string> = {+ interrupted: "The turn was interrupted before it finished.",+ session_ended: "The session ended before the turn finished.",+ runtime_lost:+ "The agent runtime stopped responding and the turn was abandoned.",+ runtime_failed: "The agent runtime failed before the turn finished.",+ deployment_invalid: "The deployment could not be loaded by the runtime.",+ model_unavailable: "The requested model is not available to this agent.",+ model_rejected: "The model provider rejected the request.",+ context_too_long:+ "The conversation is too long for the model's context window.",+ tool_failed: "A tool failed.",+ sandbox_timeout: "A sandbox command did not finish in time.",+ sandbox_failed: "The sandbox could not run this turn.",+ agent_failed: GENERIC_FAILURE_MESSAGE,+};++// The typed reasons the session records itself, ahead of any runtime text.+const FAILURE_REASON_CODES: Record<string, PublicFailureCode> = {+ interrupted: "interrupted",+ runtime_interrupted: "interrupted",+ session_ended: "session_ended",+ runtime_lost: "runtime_lost",+};++// A parameter is the only runtime-derived text a public failure carries, so+// it must look like what it claims to be; anything else is dropped.+const MODEL_ID =+ /^(?:[a-z][a-z0-9-]{0,31}\/)?[a-z0-9][a-z0-9._:-]{0,63}$/i;+const TOOL_ID = /^[a-z0-9_][a-z0-9_.-]{0,63}$/i;+const CREDENTIAL_SHAPED =+ /^(?:sk|osb|ghp|gho|ghs|ghu|ghr|github_pat|xox[abprs]|key|token|secret)[-_]/i;++function validParameter(pattern: RegExp, value: string | undefined) {+ return value !== undefined &&+ pattern.test(value) &&+ !CREDENTIAL_SHAPED.test(value)+ ? value+ : undefined;+}++// 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<{+ code: PublicFailureCode;+ pattern: RegExp;+ parameter?: "model" | "tool";+}> = [+ {+ code: "model_unavailable",+ pattern: /rejects any useModel other than \S+ \(requested (\S+)\)/,+ parameter: "model",+ },+ {+ code: "model_unavailable",+ pattern: /^Model unavailable: (\S+?)\.?(?:\s|$)/,+ parameter: "model",+ },+ {+ code: "model_unavailable",+ 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: "model_rejected",+ pattern:+ /\b(?:401|403|429)\b|unauthori[sz]ed|invalid (?:x-)?api[ _-]?key|authentication|rate limit|quota|overloaded|insufficient(?: |_)(?:credits|quota)|APICallError|provider (?:rejected|error)/i,+ },+ {+ code: "tool_failed",+ pattern:+ /^Tool (?:module exported an unregistered tool|is defined more than once): (\S+)$/,+ parameter: "tool",+ },+ {+ code: "tool_failed",+ pattern: /^(?:Unknown tool|Tool) "?([A-Za-z0-9_.-]+)"? (?:failed|is not (?:available|registered)|threw)/,+ parameter: "tool",+ },+ { code: "tool_failed", pattern: /^The tool has no edge implementation/ },+ { code: "sandbox_timeout", pattern: /^Sandbox operation timed out/ },+ {+ code: "sandbox_failed",+ pattern: /^(?:Sandbox|The sandbox|Cannot terminate the sandbox)\b/,+ },+ {+ code: "deployment_invalid",+ pattern:+ /^(?:The deployment is missing|The Workerd agent artifact|The Workerd session has no pinned deployment|This Workerd slice requires|Agent must return instructions|Invalid artifact module path|The (?:private artifact service|Dynamic Worker Loader) is not configured|Artifact service returned)/,+ },+ {+ code: "runtime_failed",+ pattern:+ /^(?:Runtime harness|OpenCode|The (?:Workerd|reactive) (?:runtime|harness)|Prestarted OpenCode|Workerd runtime|Agent (?:render|tool metadata) returned|Render commit returned|Session state returned|Agent selected an unregistered)/,+ },+];++export function publicFailure(value: unknown): PublicFailure {const data = record(value) ?? {};- const raw =- typeof data.message === "string"- ? data.message- : typeof data.reason === "string"- ? data.reason- : "";- const message = raw- .split(/\r?\n/)- // Stack frames and their "Caused by" chains.- .filter((line) => !/^\s+at\s|^\s*caused by:/i.test(line))- .join(" ")- // Internal topology: URLs, then absolute filesystem paths. A bare name- // such as a model id (`anthropic/claude-sonnet-4.6`) is not a path.- .replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`)\]]+/gi, "<url>")- .replace(/(?<![\w@:.-])\/(?:[\w@.+-]+\/)+[\w@.+-]*/g, "<path>")- // Credentials by label, by prefix, then anything long enough to be one.- .replace(/\bBearer\s+\S+/gi, "Bearer <redacted>")- .replace(- /\b((?:api[_-]?key|token|secret|password|authorization))\s*[=:]\s*"?[^\s"',;]{16,}/gi,- "$1=<redacted>",- )- .replace(- /\b(?:sk|osb|ghp|gho|ghs|ghu|ghr|github_pat|xox[abprs])[-_][A-Za-z0-9_-]{8,}/g,- "<redacted>",- )- .replace(/\b[A-Za-z0-9+/_-]{40,}={0,2}\b/g, "<redacted>")- .replace(/[\u0000-\u001f\u007f]+/g, " ")- .replace(/\s+/g, " ")- .trim();- if (!message) return GENERIC_FAILURE_MESSAGE;- return message.length > FAILURE_MESSAGE_LIMIT- ? `${message.slice(0, FAILURE_MESSAGE_LIMIT - 1)}\u2026`- : message;+ const reason = typeof data.reason === "string" ? data.reason : "";+ const known = FAILURE_REASON_CODES[reason];+ if (known) return { code: known, message: PUBLIC_FAILURE_MESSAGES[known] };+ const message = typeof data.message === "string" ? data.message : reason;+ // 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();+ for (const rule of FAILURE_MESSAGE_RULES) {+ const match = firstLine.match(rule.pattern);+ if (!match) continue;+ if (rule.parameter === "model") {+ const model = validParameter(MODEL_ID, match[1]);+ if (model) {+ return {+ code: rule.code,+ message: `The model ${model} is not available to this agent.`,+ model,+ };+ }+ }+ if (rule.parameter === "tool") {+ const tool = validParameter(TOOL_ID, match[1]);+ if (tool) {+ return { code: rule.code, message: `Tool ${tool} failed.`, tool };+ }+ }+ return { code: rule.code, message: PUBLIC_FAILURE_MESSAGES[rule.code] };+ }+ return { code: "agent_failed", message: GENERIC_FAILURE_MESSAGE };}function publicEventData(@@ -730,7 +850,7 @@ function publicEventData(): Record<string, unknown> {if (type.startsWith("runtime.") && type !== "runtime.log") return {};if (type === "session.failed" || type === "turn.failed") {- return { message: publicFailureMessage(value) };+ return { ...publicFailure(value) };}const data = record(value) ?? {};return Object.fromEntries(diff --git a/docs/agents/events.mdx b/docs/agents/events.mdxindex dfad24e2..4ea9656d 100644--- a/docs/agents/events.mdx+++ b/docs/agents/events.mdx@@ -45,7 +45,7 @@ unknown type as informational and keep reading.| `session.created` | The session exists. Always the first event. | `agentId`, `deploymentId` || `session.status_changed` | The session moved between `new`, `connecting`, `idle`, `running`, `waiting_runtime`, `suspending`, `suspended`, `resuming`, `failed` and `ended` | `from`, `to` || `session.ended` | The owner ended the session. Queued and running turns were cancelled and memory writes revoked. | none |-| `session.failed` | The session cannot continue | `message`: a sanitized reason |+| `session.failed` | The session cannot continue | `code`, `message`: a [public failure](#public-failures) |### Turns@@ -57,13 +57,29 @@ unknown type as informational and keep reading.| `turn.interrupted` | This turn cancelled the turns that were running | `interruptedTurnIds` || `turn.started` | The runtime began the turn | none || `turn.completed` | The turn finished and the session is idle again | none |-| `turn.failed` | The turn stopped with an error | `message`: the runtime's reason, sanitized |+| `turn.failed` | The turn stopped with an error | `code`, `message`, and `model` or `tool` when named: a [public failure](#public-failures) || `turn.cancelled` | The turn was stopped by an interrupt | `reason`: `interrupted`; `replacementTurnId` when an interrupt-mode turn replaced it |-A failed turn's `message` is the runtime's own error, for example a rejected-model or a tool that is not available. Stack frames, URLs, file paths and-credential-shaped values are removed and the text is capped at 500-characters; when nothing readable remains, a generic sentence is sent.+#### Public failures++A failure's `data` is a stable `code`, a fixed `message` for that code, and+at most one parameter. The runtime's own error text is never sent; a failure+no rule recognizes is `agent_failed`.++| `code` | Meaning | Parameter |+| --- | --- | --- |+| `interrupted` | The turn was stopped before it finished | |+| `session_ended` | The session ended while the turn ran | |+| `runtime_lost` | The runtime stopped responding and the turn was abandoned | |+| `runtime_failed` | The runtime failed before the turn finished | |+| `deployment_invalid` | The runtime could not load the deployment | |+| `model_unavailable` | The requested model is not available to this agent | `model`: the requested model id |+| `model_rejected` | The model provider rejected the request: credentials, rate limit or quota | |+| `context_too_long` | The conversation exceeds the model's context window | |+| `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 | |+| `agent_failed` | Any other failure | |### Messages