|
| 1 | +import { AIChatAgent } from "agents-sdk/ai-chat-agent"; |
| 2 | +import type { Env } from "../server"; |
| 3 | +import PostalMime from "postal-mime"; |
| 4 | +import { getAgentByName } from "agents-sdk"; |
| 5 | + |
| 6 | +import { createMimeMessage } from "mimetext"; |
| 7 | +import { streamText, createDataStreamResponse } from "ai"; |
| 8 | +import type { StreamTextOnFinishCallback } from "ai"; |
| 9 | +import { createOpenAI } from "@ai-sdk/openai"; |
| 10 | +import * as MockEmail from "../mock-cloudflare-email"; |
| 11 | +export async function sendEmail( |
| 12 | + id: DurableObjectId, |
| 13 | + EMAIL: SendEmail, |
| 14 | + from: string, |
| 15 | + fromName: string, |
| 16 | + fromDomain: string, |
| 17 | + recipient: string, |
| 18 | + subject: string, |
| 19 | + contentType: string, |
| 20 | + body: string |
| 21 | +) { |
| 22 | + if (!EMAIL) { |
| 23 | + throw new Error("Email is not configured"); |
| 24 | + } |
| 25 | + |
| 26 | + const msg = createMimeMessage(); |
| 27 | + msg.setSender({ name: fromName, addr: from }); |
| 28 | + msg.setRecipient(recipient); |
| 29 | + msg.setSubject(subject); |
| 30 | + msg.addMessage({ |
| 31 | + contentType: contentType, |
| 32 | + data: body, |
| 33 | + }); |
| 34 | + msg.setHeader("Message-ID", `<${idToBase64(id)}@${fromDomain}>`); |
| 35 | + |
| 36 | + // import this dynamically import { EmailMessage } from 'cloudflare:email' |
| 37 | + const { EmailMessage } = await import("cloudflare:email"); |
| 38 | + console.log(`sending email from ${from} to ${recipient}`); |
| 39 | + await EMAIL.send(new EmailMessage(from, recipient, msg.asRaw())); |
| 40 | + |
| 41 | + return "Email sent successfully!"; |
| 42 | +} |
| 43 | + |
| 44 | +export function idToBase64(id: DurableObjectId) { |
| 45 | + return Buffer.from(id.toString(), "hex").toString("base64"); |
| 46 | +} |
| 47 | + |
| 48 | +export function base64IDtoString(base64id: string) { |
| 49 | + return Buffer.from(base64id, "base64").toString("hex"); |
| 50 | +} |
| 51 | + |
| 52 | +async function createMockEmail(options: { |
| 53 | + id: string; |
| 54 | + from: string; |
| 55 | + name: string; |
| 56 | + to: string; |
| 57 | + subject: string; |
| 58 | + body: string; |
| 59 | + contentType: string; |
| 60 | +}) { |
| 61 | + const email = createMimeMessage(); |
| 62 | + email.setSender({ name: options.name, addr: options.from }); |
| 63 | + email.setRecipient(options.to); |
| 64 | + email.setSubject(options.subject); |
| 65 | + email.addMessage({ |
| 66 | + contentType: options.contentType, |
| 67 | + data: options.body, |
| 68 | + }); |
| 69 | + email.setHeader("Message-ID", `<${options.id}@${options.from}>`); |
| 70 | + const mockEmailMessage = new MockEmail.MockEmailMessage( |
| 71 | + options.from, |
| 72 | + options.to, |
| 73 | + email.asRaw() |
| 74 | + ); |
| 75 | + return mockEmailMessage; |
| 76 | +} |
| 77 | +export class EmailAgent extends AIChatAgent<Env> { |
| 78 | + openai = createOpenAI({ |
| 79 | + apiKey: this.env.OPENAI_API_KEY, |
| 80 | + }); |
| 81 | + |
| 82 | + async onRequest(request: Request) { |
| 83 | + const url = new URL(request.url); |
| 84 | + if (url.pathname.endsWith("/api/email") && request.method === "POST") { |
| 85 | + // this is dev mode, or we would have receievd it directly in onEmail |
| 86 | + // so let's redirect it there |
| 87 | + const body = await request.json<{ |
| 88 | + from: string; |
| 89 | + to: string; |
| 90 | + message: string; |
| 91 | + }>(); |
| 92 | + console.log("received email", body); |
| 93 | + const mockEmail = new MockEmail.MockForwardableEmailMessage( |
| 94 | + body.from, |
| 95 | + body.to, |
| 96 | + body.message |
| 97 | + ); |
| 98 | + this.onEmail(mockEmail); |
| 99 | + return new Response("OK", { status: 200 }); |
| 100 | + } |
| 101 | + |
| 102 | + return super.onRequest(request); |
| 103 | + } |
| 104 | + |
| 105 | + onEmail(email: ForwardableEmailMessage) { |
| 106 | + // |
| 107 | + } |
| 108 | + async onChatMessage(onFinish: StreamTextOnFinishCallback<any>) { |
| 109 | + const dataStreamResponse = createDataStreamResponse({ |
| 110 | + execute: async (dataStream) => { |
| 111 | + const result = streamText({ |
| 112 | + model: this.openai("gpt-4o"), |
| 113 | + messages: this.messages, |
| 114 | + onStepFinish: async (step) => { |
| 115 | + // if ([...this.getConnections()].length === 0) { |
| 116 | + if (true) { |
| 117 | + // send an email instead |
| 118 | + try { |
| 119 | + console.log("sending email", step.text); |
| 120 | + // we would replace this with a send_email call |
| 121 | + const mockEmail = await getAgentByName( |
| 122 | + this.env.MockEmailService, |
| 123 | + "default" |
| 124 | + ); |
| 125 | + const emailToSend = await createMockEmail({ |
| 126 | + id: this.ctx.id.toString(), |
| 127 | + |
| 128 | + name: "emailAgent", |
| 129 | + |
| 130 | + subject: "Email from emailAgent", |
| 131 | + body: step.text, |
| 132 | + contentType: "text/plain", |
| 133 | + }); |
| 134 | + mockEmail |
| 135 | + .toInbox({ |
| 136 | + from: emailToSend.from, |
| 137 | + to: emailToSend.to, |
| 138 | + message: emailToSend.message, |
| 139 | + }) |
| 140 | + .catch((e) => { |
| 141 | + console.error("error sending email", e); |
| 142 | + }); |
| 143 | + } catch (e) { |
| 144 | + console.error("error sending email", e); |
| 145 | + } |
| 146 | + } |
| 147 | + }, |
| 148 | + onFinish, |
| 149 | + }); |
| 150 | + |
| 151 | + result.mergeIntoDataStream(dataStream); |
| 152 | + }, |
| 153 | + }); |
| 154 | + |
| 155 | + return dataStreamResponse; |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +// export const emailHandler: EmailExportedHandler<Env> = |
| 160 | +// async function emailHandler( |
| 161 | +// email: ForwardableEmailMessage, |
| 162 | +// env: Env, |
| 163 | +// ctx: ExecutionContext |
| 164 | +// ) { |
| 165 | +// // @ts-ignore |
| 166 | +// console.log(Object.fromEntries(email.headers.entries())); |
| 167 | +// const parsed = await PostalMime.parse(email.raw); |
| 168 | +// console.log(parsed); |
| 169 | + |
| 170 | +// const routingMatch = email.headers |
| 171 | +// .get("references") |
| 172 | +// ?.match(/<([A-Za-z0-9+\/]{43}=)@gmad.dev/); |
| 173 | +// console.log({ |
| 174 | +// references: email.headers.get("references"), |
| 175 | +// do_match: routingMatch, |
| 176 | +// }); |
| 177 | + |
| 178 | +// if (routingMatch) { |
| 179 | +// const [_, base64id] = routingMatch; |
| 180 | + |
| 181 | +// try { |
| 182 | +// const ns = env.Email; |
| 183 | +// const stub = ns.get(ns.idFromString(base64IDtoString(base64id))); |
| 184 | +// await stub.receiveEmail( |
| 185 | +// email.from, |
| 186 | +// email.to, |
| 187 | +// email.headers.get("subject")!, |
| 188 | +// parsed.text! |
| 189 | +// ); |
| 190 | +// } catch (e) { |
| 191 | +// console.error(e); |
| 192 | +// } |
| 193 | +// } |
| 194 | +// }; |
0 commit comments