An open-source, faster Devin alternative
TypeScript
api-edge: pass a sanitized turn failure reason through
Igor Zalutskic299cdeeffe0
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex c16d60b9..3f9daa00 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -6,6 +6,7 @@ import {hasBYOKPlanAccess,mintManagedAgentsAssertion,proxyManagedAgents,+ publicFailureMessage,} from "./managed_agents";function legacyPlanEnv(plan: string) {@@ -2177,6 +2178,7 @@ describe("managed agents proxy", () => {]);expect(body).not.toHaveProperty("runtimeToken");});+// The resource inventory (C9) is the durable list of an environment's// resources: a resource no active deployment declares any more still// appears while it holds documents.@@ -2260,4 +2262,96 @@ 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 () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({+ events: [+ {+ id: "event_1",+ seq: 9,+ timestamp: "2026-09-10T00:00:00.000Z",+ sessionId: "session-1",+ turnId: "turn-1",+ type: "turn.failed",+ data: {+ message:+ "The Workerd runtime rejects any useModel other than anthropic/claude-sonnet-4.6 (requested openai/gpt-5)",+ runtimeToken: "never-return-this",+ },+ },+ {+ id: "event_2",+ seq: 10,+ timestamp: "2026-09-10T00:00:01.000Z",+ sessionId: "session-1",+ type: "session.failed",+ data: {},+ },+ ],+ }),+ ),+ );++ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",+ ),+ memoryEnv,+ memoryCaller,+ "/api/managed-agents",+ );+ const body = (await response.json()) as {+ events: Array<{ type: string; data: Record<string, unknown> }>;+ };++ expect(body.events[0].data).toEqual({+ message:+ "The Workerd runtime rejects any useModel other than anthropic/claude-sonnet-4.6 (requested openai/gpt-5)",+ });+ expect(body.events[1].data).toEqual({+ message: "The agent could not complete this request.",+ });+ expect(JSON.stringify(body)).not.toContain("never-return-this");+ });++ it("strips paths, URLs, credentials and stack frames from failure reasons", () => {+ 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"),+ }),+ ).toBe("ENOENT: no such file or directory, open '<path>'");+ expect(+ publicFailureMessage({+ message:+ "fetch to http://127.0.0.1:4096/session/ses_1/message?token=abc failed: Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijklmnopqrstuvwxyz",+ }),+ ).toBe("fetch to <url> failed: Authorization: Bearer <redacted>");+ expect(+ publicFailureMessage({+ message:+ "provider rejected api_key=sk-ant-api03-0123456789abcdefghijklmnop and osb_0123456789abcdef; retry",+ }),+ ).toBe("provider rejected api_key=<redacted> and <redacted>; retry");+ expect(+ publicFailureMessage({+ reason: "Runtime harness is not ready\u0007",+ }),+ ).toBe("Runtime harness is not ready");+ const long = publicFailureMessage({+ message: "The turn exceeded its budget. ".repeat(40),+ });+ expect(long).toHaveLength(500);+ expect(long.endsWith("\u2026")).toBe(true);+ expect(publicFailureMessage(undefined)).toBe(+ "The agent could not complete this request.",+ );+ });});diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 84f9c57d..37b03c20 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -678,13 +678,59 @@ const PRIVATE_EVENT_KEYS = new Set(["platform_instructions",]);+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 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;+}+function publicEventData(type: string,value: unknown,): Record<string, unknown> {if (type.startsWith("runtime.") && type !== "runtime.log") return {};if (type === "session.failed" || type === "turn.failed") {- return { message: "The agent could not complete this request." };+ return { message: publicFailureMessage(value) };}const data = record(value) ?? {};return Object.fromEntries(