import { defineDurable } from "@zapier/zapier-durable"; import { createZapierSdk } from "@zapier/zapier-sdk"; import { z } from "zod"; import { APPROVAL_CHANNEL_ID, APPROVE_REACTION, DECLINE_REACTION, MAX_POLLS, MODEL_ID, POLL_INTERVAL_SECONDS, PRODUCT_CONTEXT, REPLY_VOICE, SALESFORCE_EMAIL_FIELD, SALESFORCE_OBJECT, SENDER_EMAIL, } from "./config.ts"; const sdk = createZapierSdk(); const ROUTES = ["sales", "self_serve", "no_reply"] as const; const ROUTE_INSTRUCTIONS = "You read one reply to a nurture email, with the full thread and the contact's CRM record. Decide one route: " + "'sales' if they ask for pricing, a demo, a call, a contract, or describe a need big enough for a person to own; " + "'self_serve' if a helpful written answer and a link would get them moving on their own; " + "'no_reply' for out-of-office, unsubscribe requests, bounces and anything that needs no answer. " + "Then list up to three qualifying questions worth asking, only if their answers would change how the deal is handled, and give a one-sentence reason for the route. " + "Use only facts in the thread and the record."; const DRAFT_INSTRUCTIONS = "Write the email reply to the latest message in this thread. Answer what they asked first, in 3 to 6 short sentences. " + "If the route is 'sales', offer a short call and ask the qualifying questions you were given, at most two. " + "If the route is 'self_serve', answer directly and point them to the next step on their own. " + "Never invent pricing, features, dates or commitments that are not in the product context. No subject line, no signature. " + "Voice: " + REPLY_VOICE; // The email as the Gmail "New Labeled Email" trigger delivers it. Only the fields this zap reads are named. const InputSchema = z .object({ id: z.string(), thread_id: z.string(), subject: z.string().nullable().optional(), body_plain: z.string().nullable().optional(), from__email: z.string(), from__name: z.string().nullable().optional(), }) .loose(); const ReactionsSchema = z .object({ reactions: z.array(z.object({ name: z.string() }).loose()).optional(), message: z .object({ reactions: z.array(z.object({ name: z.string() }).loose()).optional(), }) .loose() .optional(), }) .loose(); const workflow = defineDurable( "route-and-draft-nurture-replies-with-slack-approval", async (ctx, rawInput) => { const input = InputSchema.parse( typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput, ); const sender = input.from__email.toLowerCase(); // The approved reply goes out from this account; skipping it keeps the zap from answering itself. if (sender === SENDER_EMAIL.toLowerCase()) { return { skipped: true, reason: "own-message", id: input.id }; } const thread = await ctx.step(`get-thread-${input.id}`, async () => sdk.runAction({ appKey: "gmail", actionType: "write", actionKey: "get_conversation", connection: "gmail", inputs: { thread_id: input.thread_id, format: "full" }, }), ); const contact = await ctx.step( `find-salesforce-contact-${input.id}`, async () => sdk.runAction({ appKey: "salesforce", actionType: "search", actionKey: "find_record", connection: "salesforce", inputs: { object: SALESFORCE_OBJECT, searchField: SALESFORCE_EMAIL_FIELD, searchValue: sender, }, }), ); const context = { latest_message: input.body_plain ?? "", subject: input.subject ?? "", thread: JSON.stringify(thread.data[0] ?? {}), crm_record: JSON.stringify(contact.data[0] ?? {}), }; const routed = await ctx.step(`route-reply-${input.id}`, async () => sdk.runAction({ appKey: "ai", actionType: "write", actionKey: "get_completion", inputs: { model_id: MODEL_ID, authentication_id: "0", instructions: ROUTE_INSTRUCTIONS, inputFields: context, includeWorkflowData: false, outputFields: [ { name: "route", type: "text", isRequired: true }, { name: "qualifying_questions", type: "text", isRequired: false }, { name: "reason", type: "text", isRequired: true }, ], }, }), ); const routing = (routed.data[0] ?? {}) as Record; const route = ROUTES.find((name) => name === routing.route?.trim().toLowerCase()) ?? "sales"; if (route === "no_reply") { return { skipped: true, reason: "no-reply-needed", id: input.id }; } const drafted = await ctx.step(`draft-reply-${input.id}`, async () => sdk.runAction({ appKey: "ai", actionType: "write", actionKey: "get_completion", inputs: { model_id: MODEL_ID, authentication_id: "0", instructions: DRAFT_INSTRUCTIONS, inputFields: { ...context, route, qualifying_questions: routing.qualifying_questions ?? "", product_context: PRODUCT_CONTEXT, }, includeWorkflowData: false, outputFields: [{ name: "reply", type: "text", isRequired: true }], }, }), ); const reply = String( (drafted.data[0] as { reply?: string } | undefined)?.reply ?? "", ).trim(); const who = input.from__name ? `${input.from__name} <${sender}>` : sender; const posted = await ctx.step( `post-draft-for-approval-${input.id}`, async () => sdk.runAction({ appKey: "slack", actionType: "write", actionKey: "channel_message", connection: "slack", inputs: { channel: APPROVAL_CHANNEL_ID, text: [ `*Reply from ${who}* (route: ${route})`, `_${routing.reason ?? ""}_`, "", `>${(input.body_plain ?? "").trim().slice(0, 600).replace(/\n/g, "\n>")}`, "", "*Draft reply:*", reply, "", `React :${APPROVE_REACTION}: to send it as written, or :${DECLINE_REACTION}: to skip it and answer by hand.`, ].join("\n"), }, }), ); const ts = String((posted.data[0] as { ts?: string } | undefined)?.ts); let decision: "approved" | "declined" | "expired" = "expired"; for ( let attempt = 1; decision === "expired" && attempt <= MAX_POLLS; attempt++ ) { await ctx.wait(`wait-for-decision-${attempt}`, POLL_INTERVAL_SECONDS); const checked = await ctx.step( `get-approval-reactions-${attempt}`, async () => sdk.runAction({ appKey: "slack", actionType: "search", actionKey: "get_message_reactions", connection: "slack", inputs: { channel: APPROVAL_CHANNEL_ID, timestamp: ts }, }), ); const found = ReactionsSchema.parse(checked.data[0] ?? {}); const names = (found.reactions ?? found.message?.reactions ?? []).map( (reaction) => reaction.name, ); if (names.includes(DECLINE_REACTION)) decision = "declined"; else if (names.includes(APPROVE_REACTION)) decision = "approved"; } if (decision === "approved") { await ctx.step(`send-approved-reply-${input.id}`, async () => sdk.runAction({ appKey: "gmail", actionType: "write", actionKey: "reply_to_message", connection: "gmail", inputs: { thread_id: input.thread_id, to: [sender], body: reply, body_type: "plain", }, }), ); } await ctx.step(`note-decision-in-thread-${input.id}`, async () => sdk.runAction({ appKey: "slack", actionType: "write", actionKey: "channel_message", connection: "slack", inputs: { channel: APPROVAL_CHANNEL_ID, thread_ts: ts, text: { approved: "Sent.", declined: "Skipped. Nothing was sent.", expired: "No decision in time. Nothing was sent.", }[decision], }, }), ); return { id: input.id, route, decision, sent: decision === "approved" }; }, ); export default workflow;