import * as z from "zod" import { defineAction } from "../../../automation/actions" import { EMAIL_ORIGIN_TOKEN } from "../../../lib/email-origin" import { buildRawMessage, getGmailApi, getMessageMetadata, getReplyMessageOptions, getReplyOptions, toDraftIdentifier, } from "@automate.ax/integration-contracts/gmail" import { GMAIL_COMPOSE_AND_METADATA_REQUIREMENT } from "../lib/scopes" import { DRAFT_IDENTIFIER_SCHEMA, REPLY_OPTIONS_SCHEMA, } from "@automate.ax/integration-contracts/gmail" /** * Creates a Gmail reply draft attached to the original conversation. * * Original recipients are derived from message headers, while optional To, Cc, * and Bcc inputs add recipients to the draft. */ export const draftGmailReply = defineAction("Draft Gmail reply") .describe("Creates a reply draft for a Gmail message.") .account("google", GMAIL_COMPOSE_AND_METADATA_REQUIREMENT) .input( REPLY_OPTIONS_SCHEMA.extend({ /** Immutable Gmail message ID receiving the reply. */ messageId: z.string().min(1), }), ) .output(DRAFT_IDENTIFIER_SCHEMA) .retry({ replaySafety: "unsafe" }) .handler(async ({ account, input, runtime }) => { const gmailApi = getGmailApi(account.secret) const reply = await getReplyOptions( gmailApi, await getMessageMetadata(gmailApi, input.messageId), input.replyAll ?? false, ) const { data: draft } = await gmailApi.users.drafts.create({ requestBody: { message: { raw: await buildRawMessage({ ...getReplyMessageOptions(reply, input), automationOriginToken: runtime[EMAIL_ORIGIN_TOKEN], bcc: input.bcc, from: input.from, headers: input.headers, html: input.html, priority: input.priority, replyTo: input.replyTo, text: input.text, }), threadId: reply.threadId, }, }, userId: "me", }) return toDraftIdentifier(draft, "reply draft") })