import { defineDurable } from "@zapier/zapier-durable"; import { createZapierSdk } from "@zapier/zapier-sdk"; import { z } from "zod"; import { AI_AUTHENTICATION_ID, AI_MODEL_ID, BOT_NAME, CATEGORIES, DIGEST_INSTRUCTIONS, INBOX_QUERY, MAX_BODY_CHARS, MAX_EMAILS, MAX_FULL_EMAILS, SLACK_CHANNEL, SORT_INSTRUCTIONS, } from "./config.ts"; // The sandbox provides Buffer; the compiler is not given node types. declare const Buffer: { from( data: string, encoding: "base64", ): { toString(encoding: "utf8"): string }; }; const sdk = createZapierSdk(); const GMAIL = "https://gmail.googleapis.com/gmail/v1/users/me"; // The daily schedule trigger sends nothing the zap reads; the schema only checks that the input parses. const InputSchema = z.object({}).loose(); const ProfileSchema = z.object({ emailAddress: z.string() }).loose(); const ListSchema = z .object({ messages: z .array(z.object({ id: z.string(), threadId: z.string() }).loose()) .default([]), }) .loose(); const MessageSchema = z .object({ threadId: z.string(), snippet: z.string().default(""), payload: z .object({ headers: z .array(z.object({ name: z.string(), value: z.string() })) .default([]), }) .loose() .optional(), }) .loose(); // One node of a message's MIME tree; parts nest, so each level is parsed as it's walked. const PartSchema = z .object({ mimeType: z.string().default(""), body: z.object({ data: z.string().optional() }).loose().optional(), parts: z.array(z.unknown()).default([]), }) .loose(); const FullMessageSchema = z.object({ payload: z.unknown() }).loose(); async function gmail(path: string): Promise { const response = await sdk.fetch(`${GMAIL}${path}`, { connection: "gmail" }); if (!response.ok) { throw new Error(`Gmail returned ${response.status} for ${path}`); } return response.json(); } function findPart(node: unknown, mimeType: string): string { const part = PartSchema.parse(node); if (part.mimeType === mimeType && part.body?.data) { // Gmail encodes bodies as URL-safe base64, which Buffer's base64 decoder also reads. return Buffer.from(part.body.data, "base64").toString("utf8"); } for (const child of part.parts) { const found = findPart(child, mimeType); if (found) return found; } return ""; } function htmlToText(html: string): string { return html .replace(/<(style|script)[\s\S]*?<\/\1>/gi, "") .replace(/|<\/(p|div|li|tr|h\d)>/gi, "\n") .replace(/<[^>]+>/g, "") .replace(/ /g, " ") .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, '"') .replace(/'/g, "'"); } // Replies carry the whole thread below them; the reply only needs what this email added. // A forward's "From:" block is left in, since the forwarded email is usually the ask. const QUOTE_START = /^(On .+wrote:|-{2,} ?Original Message ?-{2,}|-- ?)$/m; function bodyText(payload: unknown): string { const text = findPart(payload, "text/plain") || htmlToText(findPart(payload, "text/html")); const start = text.search(QUOTE_START); return (start === -1 ? text : text.slice(0, start)) .split("\n") .filter((line) => !line.startsWith(">")) .join("\n") .replace(/[ \t]+\n/g, "\n") .replace(/\n{3,}/g, "\n\n") .trim() .slice(0, MAX_BODY_CHARS); } const workflow = defineDurable( "post-a-daily-email-digest-to-slack-with-ai", async (ctx, rawInput) => { InputSchema.parse( typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput, ); const emails = await ctx.step("read-inbox", async () => { const { emailAddress } = ProfileSchema.parse(await gmail("/profile")); const list = ListSchema.parse( await gmail( `/messages?q=${encodeURIComponent(INBOX_QUERY)}&maxResults=${MAX_EMAILS}`, ), ); const found = []; for (const { id } of list.messages) { const message = MessageSchema.parse( await gmail( `/messages/${id}?format=metadata&metadataHeaders=From&metadataHeaders=Subject`, ), ); const header = (name: string) => message.payload?.headers.find((h) => h.name === name)?.value ?? ""; found.push({ id, from: header("From"), subject: header("Subject") || "(no subject)", snippet: message.snippet, // authuser opens the right account when the person is signed in to more than one. link: `https://mail.google.com/mail/?authuser=${encodeURIComponent(emailAddress)}#all/${message.threadId}`, }); } return found; }); if (emails.length === 0) { return { skipped: true, reason: "no-new-email" }; } const needsYou = await ctx.step("sort-inbox", async () => { const result = await sdk.runAction({ appKey: "ai", actionType: "write", actionKey: "get_completion", inputs: { model_id: AI_MODEL_ID, authentication_id: AI_AUTHENTICATION_ID, instructions: SORT_INSTRUCTIONS, inputFields: { emails: JSON.stringify( emails.map(({ id, from, subject, snippet }) => ({ id, from, subject, snippet, })), ), }, includeWorkflowData: false, outputFields: [ { name: "needs_you", description: "Ids of the emails that need the user, most urgent first, separated by commas.", type: "text", isRequired: false, }, ], }, }); const output = result.data[0] as { needs_you?: string } | undefined; const known = new Set(emails.map((email) => email.id)); return (output?.needs_you ?? "") .split(/[\s,]+/) .filter((id) => known.has(id)); }); const bodies = new Map(); for (const id of needsYou.slice(0, MAX_FULL_EMAILS)) { const body = await ctx.step(`read-email-${id}`, async () => bodyText( FullMessageSchema.parse(await gmail(`/messages/${id}?format=full`)) .payload, ), ); if (body) bodies.set(id, body); } const digest = await ctx.step("write-digest", async () => { const result = await sdk.runAction({ appKey: "ai", actionType: "write", actionKey: "get_completion", inputs: { model_id: AI_MODEL_ID, authentication_id: AI_AUTHENTICATION_ID, instructions: `${DIGEST_INSTRUCTIONS}\n\nCategories: ${CATEGORIES}`, inputFields: { today: new Date().toDateString(), needs_you: needsYou.join(", "), emails: JSON.stringify( emails.map((email) => bodies.has(email.id) ? { ...email, body: bodies.get(email.id) } : email, ), ), }, includeWorkflowData: false, outputFields: [ { name: "digest", description: "The whole digest as one Slack message.", type: "text", isRequired: true, }, ], }, }); const output = result.data[0] as { digest?: string } | undefined; return (output?.digest ?? "").trim(); }); if (!digest) { throw new Error("AI by Zapier returned no digest"); } // A member ID (U… or W…) gets the digest as a DM; anything else is a channel. const toPerson = /^[UW][A-Z0-9]+$/.test(SLACK_CHANNEL); const posted = await ctx.step("post-digest", async () => sdk.runAction({ appKey: "slack", actionType: "write", actionKey: toPerson ? "direct_message" : "channel_message", connection: "slack", inputs: { channel: SLACK_CHANNEL, text: digest, as_bot: "yes", username: BOT_NAME, unfurl: "no", add_edit_link: "no", }, }), ); return { emails: emails.length, needsYou: needsYou.length, readInFull: bodies.size, posted: posted.data[0] ?? null, }; }, ); export default workflow;