Skip to content

Email for professionals and teams

Keep assistant tool schemas free of regex lookaround (#117)

rome-xi0c154998896c
diff --git a/src/lib/agent/schema-utils.ts b/src/lib/agent/schema-utils.ts
new file mode 100644
index 0000000..8064b23
--- /dev/null
+++ b/src/lib/agent/schema-utils.ts
@@ -0,0 +1,6 @@
+import { z } from "zod";
+
+const strictEmail = z.string().email();
+
+// Zod 4 emits z.string().email() as a JSON Schema pattern with lookaheads, which OpenRouter rejects.
+export const toolEmailSchema = z.string().refine((value) => strictEmail.safeParse(value).success, "Invalid email").meta({ format: "email", description: "A single email address" });
diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.ts
index 4fe3b26..e415d0a 100644
--- a/src/lib/agent/tools.ts
+++ b/src/lib/agent/tools.ts
@@ -18,6 +18,7 @@ import { getReplyRecipients } from "./reply";
import { formatAgentDraftBody } from "./draft-format";
import { editAgentDraft } from "./edit-draft";
import { requestAgentSend } from "./approvals/utils";
+import { toolEmailSchema } from "./schema-utils";
import type { AgentDraftEditInput } from "./types";
const id = z.string().min(1).max(160);
@@ -29,7 +30,7 @@ export const emailToolSchemas = {
get_email: z.object({ emailId: id }),
get_thread: z.object({ emailId: id }),
search_emails: z.object({ query: z.string().trim().min(1).max(300), folder: z.enum(["inbox", "sent", "scheduled", "draft", "archived", "trash", "spam"]).optional(), limit }),
- draft_email: z.object({ to: z.string().email(), subject: z.string().trim().min(1).max(500), body }),
+ draft_email: z.object({ to: toolEmailSchema, subject: z.string().trim().min(1).max(500), body }),
draft_reply: z.object({ emailId: id, body, replyAll: z.boolean().default(false) }),
edit_draft: z.object({
draftId: id, expectedRevision: z.number().int().positive(),
diff --git a/src/lib/calendar/tools.ts b/src/lib/calendar/tools.ts
index d40d0fc..1abb820 100644
--- a/src/lib/calendar/tools.ts
+++ b/src/lib/calendar/tools.ts
@@ -2,6 +2,7 @@ import { and, eq, gte, lt, ne, or } from "drizzle-orm";
import { z } from "zod";
import { getDb } from "@/db";
import { calendarEvents } from "@/db/schema";
+import { toolEmailSchema } from "@/lib/agent/schema-utils";
import { newId } from "@/lib/ids";
import { normalizeTimeZone, zonedDateFields } from "@/lib/time/utils";
import { normalizeCalendarColor } from "./colors";
@@ -16,7 +17,7 @@ const repeat = z.enum(["none", "daily", "weekly", "monthly", "weekdays"]);
const fields = {
title: z.string().trim().min(1).max(500), description: z.string().max(10_000), location: z.string().max(500),
startsAt: instant, endsAt: instant, timeZone: z.string().max(80), color: z.string().max(30),
- repeat, repeatDays: z.array(z.number().int().min(0).max(6)).max(7), attendees: z.array(z.string().email()).max(50),
+ repeat, repeatDays: z.array(z.number().int().min(0).max(6)).max(7), attendees: z.array(toolEmailSchema).max(50),
};
const update = z.object({ eventId: id, title: fields.title.optional(), description: fields.description.optional(), location: fields.location.optional(), startsAt: instant.optional(), endsAt: instant.optional(), timeZone: fields.timeZone.optional(), color: fields.color.optional(), repeat: repeat.optional(), repeatDays: fields.repeatDays.optional(), attendees: fields.attendees.optional() });
diff --git a/tests/agent-tool-schemas.test.mjs b/tests/agent-tool-schemas.test.mjs
new file mode 100644
index 0000000..6ba5157
--- /dev/null
+++ b/tests/agent-tool-schemas.test.mjs
@@ -0,0 +1,81 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import test, { after } from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { zodSchema } from "ai";
+import { build } from "esbuild";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const bundleDirectory = mkdtempSync(join(root, "node_modules", "mailflare-schema-bundle-"));
+await build({
+ stdin: {
+ contents: `
+ export { emailToolSchemas } from "./src/lib/agent/tools.ts";
+ export { calendarToolSchemas } from "./src/lib/calendar/tools.ts";
+ `,
+ resolveDir: root,
+ sourcefile: "agent-schema-entry.ts",
+ },
+ outfile: join(bundleDirectory, "entry.mjs"),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node24",
+ tsconfig: join(root, "tsconfig.json"),
+ packages: "external",
+ alias: {
+ "cloudflare:workers": "./server/runtime/cloudflare-workers.ts",
+ },
+ logLevel: "silent",
+});
+const { emailToolSchemas, calendarToolSchemas } = await import(pathToFileURL(join(bundleDirectory, "entry.mjs")).href);
+after(() => rmSync(bundleDirectory, { recursive: true, force: true }));
+
+// streamText sends zodSchema().jsonSchema (draft-07). MCP registerTool sends ~standard.jsonSchema.input (draft-2020-12).
+const LOOKAROUND = /\(\?(?:[=!]|<[=!])/;
+
+function providerSchemas(schema) {
+ return [
+ zodSchema(schema).jsonSchema,
+ schema["~standard"].jsonSchema.input({ target: "draft-2020-12" }),
+ ];
+}
+
+function patterns(schema, found = []) {
+ if (!schema || typeof schema !== "object") return found;
+ if (typeof schema.pattern === "string") found.push(schema.pattern);
+ for (const value of Object.values(schema)) {
+ if (Array.isArray(value)) value.forEach((item) => patterns(item, found));
+ else patterns(value, found);
+ }
+ return found;
+}
+
+const toolSchemas = { ...emailToolSchemas, ...calendarToolSchemas };
+
+test("model-facing email and calendar tool schemas contain no regex lookaround", () => {
+ const offenders = [];
+ for (const [name, schema] of Object.entries(toolSchemas)) {
+ for (const json of providerSchemas(schema)) {
+ for (const pattern of patterns(json)) {
+ if (LOOKAROUND.test(pattern)) offenders.push(`${name}: ${pattern}`);
+ }
+ }
+ }
+ assert.deepEqual(offenders, []);
+});
+
+test("draft and calendar execution still validate email addresses", () => {
+ const draft = { subject: "Hi", body: "Hello" };
+ assert.equal(emailToolSchemas.draft_email.safeParse({ ...draft, to: "not-an-email" }).success, false);
+ assert.equal(emailToolSchemas.draft_email.safeParse({ ...draft, to: "[email protected]" }).success, false);
+ assert.equal(emailToolSchemas.draft_email.safeParse({ ...draft, to: "[email protected]" }).success, true);
+
+ const event = { title: "Meet", startsAt: "2026-10-12T15:00:00.000Z", endsAt: "2026-10-12T16:00:00.000Z" };
+ assert.equal(calendarToolSchemas.create_event.safeParse({ ...event, attendees: ["not-an-email"] }).success, false);
+ assert.equal(calendarToolSchemas.create_event.safeParse({ ...event, attendees: ["[email protected]"] }).success, false);
+ assert.equal(calendarToolSchemas.create_event.safeParse({ ...event, attendees: ["[email protected]"] }).success, true);
+ assert.equal(calendarToolSchemas.update_events.safeParse({ updates: [{ eventId: "evt-1", attendees: ["not-an-email"] }] }).success, false);
+ assert.equal(calendarToolSchemas.update_events.safeParse({ updates: [{ eventId: "evt-1", attendees: ["[email protected]"] }] }).success, true);
+});