Skip to content

The open-source app everyone uses to manage agents at work

Add bounded AgentMail failure diagnostics (#14768)

Devin Foley3bbb8d0f6991
diff --git a/doc/connections/AGENTMAIL.md b/doc/connections/AGENTMAIL.md
index 3c589d84f9..7da4ac7b25 100644
--- a/doc/connections/AGENTMAIL.md
+++ b/doc/connections/AGENTMAIL.md
@@ -19,6 +19,15 @@ Verified custom domains are selectable after checking the API key. Complete DNS
setup in [AgentMail](https://docs.agentmail.to/custom-domains). Paperclip does not
register domains or manage DNS.
+Failed provider requests retain their HTTP status, a fixed operation name, and
+an allowlisted [AgentMail error code](https://docs.agentmail.to/errors). For
+example, `create_inbox` with `missing_permission` differs from `limit_exceeded`.
+An HTTP 403 alone does not establish the cause. Missing or unrecognized codes
+appear as `unknown`. Error-body inspection is limited to 8 KiB and one second;
+malformed, larger, or stalled responses keep the original HTTP failure. Provider
+messages, suggested fixes, URLs, inbox identifiers, and credentials are excluded
+from these diagnostics. These diagnostics do not retry or suppress failures.
+
The setup and Permissions page warn that an unrestricted inbox can receive mail
from anyone. Configure sender allowlists in AgentMail; Paperclip does not manage
or verify them. AgentMail controls new-message and reply lists separately. The
diff --git a/server/src/__tests__/agentmail-api.test.ts b/server/src/__tests__/agentmail-api.test.ts
index c308809baf..727a11c6f8 100644
--- a/server/src/__tests__/agentmail-api.test.ts
+++ b/server/src/__tests__/agentmail-api.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import { Webhook } from "svix";
import {
agentmailApi,
+ AgentmailApiError,
agentmailMessageSchema,
emailText,
emailReplyRecipients,
@@ -138,6 +139,116 @@ describe("AgentMail protocol boundary", () => {
"AgentMail request failed (403)",
);
});
+ it.each(["missing_permission", "limit_exceeded", "domain_not_verified"])(
+ "keeps a bounded create-inbox diagnostic for %s without provider data",
+ async (code) => {
+ const privateValue = "[email protected]";
+ const fetcher = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ code,
+ message: privateValue,
+ fix: `Use credential ${privateValue}`,
+ docs: `https://example.test/${privateValue}`,
+ nested: { code: privateValue },
+ }), { status: 403 }));
+ const error = await agentmailApi(privateValue, fetcher)
+ .createInbox({ username: privateValue }).catch((error: unknown) => error);
+ expect(error).toBeInstanceOf(AgentmailApiError);
+ expect(error).toMatchObject({ status: 403, operation: "create_inbox", providerCode: code });
+ expect(String(error)).toBe(`Error: AgentMail request failed (403) [operation=create_inbox, code=${code}]`);
+ expect(JSON.stringify(error)).not.toContain(privateValue);
+ expect((error as Error).stack).not.toContain(privateValue);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ },
+ );
+ it.each([
+ "private email and credentials",
+ JSON.stringify({ code: "[email protected]" }),
+ JSON.stringify({ code: ["missing_permission"] }),
+ JSON.stringify([{ code: "missing_permission" }]),
+ JSON.stringify({ message: "Forbidden" }),
+ JSON.stringify(null),
+ ])("does not copy unrecognized provider bodies into diagnostics (%#)", async (body) => {
+ const fetcher = vi.fn().mockResolvedValue(new Response(body, { status: 403 }));
+ await expect(agentmailApi("private-key", fetcher).whoami()).rejects.toMatchObject({
+ status: 403,
+ operation: "inspect_key",
+ providerCode: "unknown",
+ message: "AgentMail request failed (403) [operation=inspect_key, code=unknown]",
+ });
+ });
+ it.each([
+ ["GET", "/inboxes?limit=100", "list_inboxes"],
+ ["GET", "/inboxes/private%40example.test", "get_inbox"],
+ ["GET", "/domains?limit=100", "list_domains"],
+ ["GET", "/domains/private.example.test", "get_domain"],
+ ["POST", "/inboxes/private%40example.test/api-keys", "create_inbox_key"],
+ ["DELETE", "/inboxes/private%40example.test/api-keys/private-key", "delete_inbox_key"],
+ ["POST", "/inboxes/private%40example.test/webhooks", "create_webhook"],
+ ["DELETE", "/inboxes/private%40example.test/webhooks/private-hook", "delete_webhook"],
+ ["GET", "/inboxes/private%40example.test/messages?page_token=private-token", "list_messages"],
+ ["GET", "/inboxes/private%40example.test/messages/private-message", "get_message"],
+ ["GET", "/inboxes/private%40example.test/threads/private-thread", "get_thread"],
+ ["POST", "/inboxes/private%40example.test/messages/send", "send_message"],
+ ["POST", "/inboxes/private%40example.test/messages/private-message/reply", "reply_message"],
+ ["GET", "/inboxes/private%40example.test/messages/private-message/attachments/private-attachment", "get_attachment"],
+ ["POST", "/private-path?key=private-key", "request"],
+ ["PATCH", "/inboxes/private%40example.test", "request"],
+ ])("uses a fixed operation for %s route %#", async (method, path, operation) => {
+ const fetcher = vi.fn().mockResolvedValue(new Response(null, { status: 403 }));
+ const error = await agentmailApi("private-key", fetcher).request(path, method).catch((error: unknown) => error);
+ expect(error).toMatchObject({ operation, providerCode: "unknown" });
+ expect(String(error)).not.toContain("private");
+ expect(JSON.stringify(error)).not.toContain("private");
+ });
+ it("bounds the error body read and cancels the remaining stream", async () => {
+ const cancel = vi.fn();
+ const response = new Response(new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(JSON.stringify({ code: "missing_permission", message: "x".repeat(8192) })));
+ },
+ cancel,
+ }), { status: 403 });
+ await expect(agentmailApi("private-key", vi.fn().mockResolvedValue(response)).whoami())
+ .rejects.toMatchObject({ status: 403, providerCode: "unknown" });
+ expect(cancel).toHaveBeenCalledOnce();
+ });
+ it("keeps the HTTP status when the error body stalls or cancellation fails", async () => {
+ vi.useFakeTimers();
+ try {
+ const cancel = vi.fn().mockRejectedValue(new Error("private provider error"));
+ const response = new Response(new ReadableStream({ cancel }), { status: 403 });
+ const failure = expect(agentmailApi("private-key", vi.fn().mockResolvedValue(response)).whoami())
+ .rejects.toMatchObject({ status: 403, providerCode: "unknown" });
+ await vi.advanceTimersByTimeAsync(1000);
+ await failure;
+ expect(cancel).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ it("keeps retry classification when reading an error body fails", async () => {
+ const response = new Response(new ReadableStream({
+ start(controller) { controller.error(new Error("private provider error")); },
+ }), { status: 429, headers: { "retry-after": "9" } });
+ const fetcher = vi.fn().mockResolvedValue(response);
+ await expect(agentmailApi("private-key", fetcher).send("[email protected]", {}, "private-key"))
+ .rejects.toMatchObject({ status: 429, retryAfterMs: 9000, providerCode: "unknown", operation: "send_message" });
+ expect(fetcher).toHaveBeenCalledOnce();
+ });
+ it.each([403, 429])("preserves HTTP %s when the response body is already locked", async (status) => {
+ const response = new Response(JSON.stringify({ code: "missing_permission" }), {
+ status,
+ headers: { "retry-after": "9" },
+ });
+ const owner = response.body!.getReader();
+ try {
+ await expect(agentmailApi("private-key", vi.fn().mockResolvedValue(response))
+ .send("[email protected]", {}, "private-key"))
+ .rejects.toMatchObject({ status, retryAfterMs: 9000, providerCode: "unknown", operation: "send_message" });
+ } finally {
+ owner.releaseLock();
+ }
+ });
it("constructs deliberate reply-all from visible recipients, excluding self and Bcc", () => {
const envelope = {
from: "Sender <[email protected]>",
diff --git a/server/src/services/agentmail-api.ts b/server/src/services/agentmail-api.ts
index 7320e83e9e..3d95934af7 100644
--- a/server/src/services/agentmail-api.ts
+++ b/server/src/services/agentmail-api.ts
@@ -42,13 +42,84 @@ export interface AgentmailScope {
pod_id?: string;
inbox_id?: string;
}
+
+// Only these documented codes may leave the provider boundary. The other
+// response fields (including `fix`) can contain addresses, URLs, or credentials.
+const providerErrorCodes = [
+ "missing_authorization", "invalid_token_type", "unknown_api_key", "unauthorized",
+ "missing_permission", "permission_escalation", "unrestricted_key_required", "forbidden",
+ "validation_error", "not_found", "unprocessable", "query_range_too_wide",
+ "already_exists", "resource_taken", "limit_exceeded", "domain_not_verified",
+ "conflict", "race_condition", "resource_deleting", "cannot_delete", "message_rejected",
+ "rate_limit_exceeded", "service_unavailable", "internal_error",
+] as const;
+type ProviderErrorCode = (typeof providerErrorCodes)[number] | "unknown";
+const providerOperations = [
+ ["GET", /^\/auth\/me$/, "inspect_key"],
+ ["GET", /^\/inboxes$/, "list_inboxes"],
+ ["POST", /^\/inboxes$/, "create_inbox"],
+ ["GET", /^\/inboxes\/[^/]+$/, "get_inbox"],
+ ["GET", /^\/domains$/, "list_domains"],
+ ["GET", /^\/domains\/[^/]+$/, "get_domain"],
+ ["POST", /^\/inboxes\/[^/]+\/api-keys$/, "create_inbox_key"],
+ ["DELETE", /^\/inboxes\/[^/]+\/api-keys\/[^/]+$/, "delete_inbox_key"],
+ ["POST", /^\/inboxes\/[^/]+\/webhooks$/, "create_webhook"],
+ ["DELETE", /^\/inboxes\/[^/]+\/webhooks\/[^/]+$/, "delete_webhook"],
+ ["GET", /^\/inboxes\/[^/]+\/messages$/, "list_messages"],
+ ["GET", /^\/inboxes\/[^/]+\/messages\/[^/]+$/, "get_message"],
+ ["GET", /^\/inboxes\/[^/]+\/threads\/[^/]+$/, "get_thread"],
+ ["POST", /^\/inboxes\/[^/]+\/messages\/send$/, "send_message"],
+ ["POST", /^\/inboxes\/[^/]+\/messages\/[^/]+\/reply$/, "reply_message"],
+ ["GET", /^\/inboxes\/[^/]+\/messages\/[^/]+\/attachments\/[^/]+$/, "get_attachment"],
+] as const;
+type ProviderOperation = (typeof providerOperations)[number][2] | "request";
+
+async function readProviderErrorCode(response: Response): Promise<ProviderErrorCode> {
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ if (!response.body) return "unknown";
+ const bodyReader = response.body.getReader();
+ reader = bodyReader;
+ return await Promise.race([
+ (async (): Promise<ProviderErrorCode> => {
+ const parts: Uint8Array[] = [];
+ let bytes = 0;
+ for (;;) {
+ const part = await bodyReader.read();
+ if (part.done) break;
+ bytes += part.value.length;
+ if (bytes > 8 * 1024) return "unknown";
+ parts.push(part.value);
+ }
+ const body: unknown = JSON.parse(Buffer.concat(parts).toString("utf8"));
+ const code = body && typeof body === "object" && !Array.isArray(body)
+ ? (body as Record<string, unknown>).code
+ : undefined;
+ return providerErrorCodes.find((known) => known === code) ?? "unknown";
+ })(),
+ new Promise<ProviderErrorCode>((resolve) => {
+ timeout = setTimeout(() => resolve("unknown"), 1000);
+ }),
+ ]);
+ } catch {
+ // A malformed, truncated, or interrupted body must not replace the HTTP error.
+ return "unknown";
+ } finally {
+ clearTimeout(timeout);
+ void reader?.cancel().catch(() => {});
+ }
+}
+
export class AgentmailApiError extends Error {
constructor(
readonly status: number,
readonly retryAfterMs = 1000,
+ readonly operation: ProviderOperation = "request",
+ readonly providerCode: ProviderErrorCode = "unknown",
) {
// Provider bodies may contain credentials or private mail. Never log them.
- super(`AgentMail request failed (${status})`);
+ super(`AgentMail request failed (${status}) [operation=${operation}, code=${providerCode}]`);
}
}
export const AGENTMAIL_EVENTS = [
@@ -183,6 +254,10 @@ export function agentmailApi(apiKey: string, fetchImpl: typeof fetch = fetch) {
throw new AgentmailApiError(
response.status,
Math.max(1000, Math.min(300_000, Number.isFinite(delay) ? delay : 1000)),
+ providerOperations.find(([verb, route]) =>
+ verb === method && route.test(path.split("?")[0]),
+ )?.[2] ?? "request",
+ await readProviderErrorCode(response),
);
}
if (response.status === 204) return undefined as T;