Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add custom email (IMAP/SMTP) support for agents (#12)
Gener14b5558e28b6
diff --git a/package.json b/package.jsonindex 49c9e5ac9..40b66a4a6 100644--- a/package.json+++ b/package.json@@ -5,7 +5,7 @@"scripts": {"build": "turbo run build","test": "turbo run test",- "predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '✓ Generated src/web/.dev.vars (fill in OAuth keys if needed)')",+ "predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '✓ Generated src/web/.dev.vars (fill in OAuth keys if needed)'); [ -f src/email-worker/.dev.vars ] || (cp src/email-worker/.dev.vars.example src/email-worker/.dev.vars && KEY=$(grep '^ENCRYPTION_KEY=' src/web/.dev.vars | cut -d= -f2-) && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$KEY|\" src/email-worker/.dev.vars && echo '✓ Generated src/email-worker/.dev.vars (synced ENCRYPTION_KEY from web)')","dev": "turbo run dev --filter='!@alook/cli'","clean": "rm -rf node_modules src/*/node_modules src/*/dist src/*/.turbo .turbo src/web/.next src/web/.open-next src/*/.wrangler .alook","clean:builds": "rm -rf src/*/dist src/web/.next src/web/.open-next .turbo src/*/.turbo",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7c7389045..212099dbe 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -51,12 +51,18 @@ importers:'@alook/shared':specifier: workspace:*version: link:../shared+ cf-imap:+ specifier: ^0.0.12+ version: 0.0.12([email protected])nanoid:specifier: ^5.1.9version: 5.1.9postal-mime:specifier: ^2.7.4version: 2.7.4+ worker-mailer:+ specifier: ^1.2.1+ version: 1.2.1devDependencies:'@cloudflare/workers-types':specifier: ^4.20260418.1@@ -2933,6 +2939,11 @@ packages:resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}+ resolution: {integrity: sha512-ZE4XWXZPV+aXZTcJKWNAgg340WEmP29SKZ+mnweZQ2q8KTcDGXT3oz5LLTXwGA2huRpI55+lBqIk4nB+nIfz4Q==}+ peerDependencies:+ typescript: ^5.0.0+resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}engines: {node: '>=18'}@@ -5936,6 +5947,9 @@ packages:resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-gS2ei/mrpRqNs+AHmqxhT6vFPwCLw2qnz5ShmyGD0ULaU0Q9hxnFAcx9jhAip/MnD6+MjgnQu6hQQgA8mlOkVA==}+resolution: {integrity: sha512-phyPjRnx+mQDfkhN9ENPioL1L0SdhYs4S0YmJK/xF9Oga+ykNfdSy1MHnsOj8yqnOV96zcVQMx32dJ0r3pq0jQ==}engines: {node: '>=16'}@@ -9082,6 +9096,10 @@ snapshots:+ dependencies:+ typescript: 6.0.3+@@ -12639,6 +12657,8 @@ snapshots:+ [email protected]: {}+optionalDependencies:'@cloudflare/workerd-darwin-64': 1.20260415.1diff --git a/src/cli/commands/email.test.ts b/src/cli/commands/email.test.tsindex 1532008d6..c4742e5ae 100644--- a/src/cli/commands/email.test.ts+++ b/src/cli/commands/email.test.ts@@ -273,14 +273,16 @@ describe("email send subcommand shape", () => {expect(mandatory).toContain("--body-file");});- it("accepts --attachment and --workspace as optional", () => {+ it("accepts --attachment, --workspace, and --from as optional", () => {const opts = (send as unknown as { options: { long: string; mandatory?: boolean }[] }).options;const longs = opts.map((o) => o.long);const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);expect(longs).toContain("--attachment");expect(longs).toContain("--workspace");+ expect(longs).toContain("--from");expect(mandatory).not.toContain("--attachment");expect(mandatory).not.toContain("--workspace");+ expect(mandatory).not.toContain("--from");});});@@ -412,6 +414,41 @@ describe("email send behavior", () => {expect(postJSONMock).not.toHaveBeenCalled();});+ it("passes --from to API payload when provided", async () => {+ const bodyPath = join(SEND_TMP, "body.html");+ writeFileSync(bodyPath, "<p>From custom</p>");+ postJSONMock.mockResolvedValueOnce({ id: "em_3", to_email: "[email protected]" });++ const { exitCode } = await runSend([+ "--agent_id", "ag_1",+ "--to", "[email protected]",+ "--subject", "Custom from",+ "--body-file", bodyPath,+ "--from", "[email protected]",+ ]);++ expect(exitCode).toBeNull();+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;+ expect(payload.from).toBe("[email protected]");+ });++ it("omits from in payload when --from is not provided", async () => {+ const bodyPath = join(SEND_TMP, "body.html");+ writeFileSync(bodyPath, "<p>Default from</p>");+ postJSONMock.mockResolvedValueOnce({ id: "em_4", to_email: "[email protected]" });++ const { exitCode } = await runSend([+ "--agent_id", "ag_1",+ "--to", "[email protected]",+ "--subject", "Default",+ "--body-file", bodyPath,+ ]);++ expect(exitCode).toBeNull();+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;+ expect(payload.from).toBeUndefined();+ });+it("errors when body file is empty", async () => {const bodyPath = join(SEND_TMP, "empty.html");writeFileSync(bodyPath, "");diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.tsindex 55f9ce446..2cea8420a 100644--- a/src/cli/commands/email.ts+++ b/src/cli/commands/email.ts@@ -262,6 +262,7 @@ export function emailCommand(): Command {.requiredOption("--to <addr>", "Recipient email address").requiredOption("--subject <s>", "Subject line").requiredOption("--body-file <path>", "Path to HTML body file")+ .option("--from <addr>", "Send from a specific email address (custom mailbox)").option("--in-reply-to <emailId>", "Email ID to reply to (sets threading headers)").option("--attachment <path>",@@ -349,6 +350,7 @@ export function emailCommand(): Command {htmlBody,attachments,...(inReplyTo ? { inReplyTo, references } : {}),+ ...(opts.from ? { from: opts.from } : {}),});console.log(`Sent email to ${res.to_email} (id: ${res.id})`);} catch (err) {diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.tsindex 140ce5f9a..5a0e9135f 100644--- a/src/cli/daemon/execenv/context.test.ts+++ b/src/cli/daemon/execenv/context.test.ts@@ -29,7 +29,7 @@ describe("buildInstructionContent email tool injection", () => {expect(content).toContain("npx @alook/cli set --agent_id agent-123 --email_id <EMAIL_ID> --status read");expect(content).toContain("/tmp/alook-emails/");expect(content).toContain("metadata.json");- expect(content).toContain("Your email address is '[email protected]'");+ expect(content).toContain("'[email protected]' (default, Alook platform address)");});it("includes send-email docs when agent has email handle", () => {@@ -69,7 +69,7 @@ describe("buildInstructionContent email tool injection", () => {});const content = buildInstructionContent(task);- expect(content).toContain("Your email address is '[email protected]'");+ expect(content).toContain("'[email protected]' (default, Alook platform address)");expect(content).toContain("Your owner's email address is '[email protected]'");});@@ -79,7 +79,7 @@ describe("buildInstructionContent email tool injection", () => {});const content = buildInstructionContent(task);- expect(content).toContain("Your email address is '[email protected]'");+ expect(content).toContain("'[email protected]' (default, Alook platform address)");expect(content).not.toContain("owner's email");});diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex 7235dddfb..5eefa9832 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -79,9 +79,15 @@ You can communicate with the world through Alook CLI.Your alook agent id is '${task.agentId}'. remember this, most of alook cli will requires you input your agent id.`;- if (task.agent?.emailHandle) {- content += `Your email address is '${toAlookAddress(task.agent.emailHandle)}'.-${task.agent.userEmail ? `Your owner's email address is '${task.agent.userEmail}'.` : ""}+ const alookAddr = task.agent?.emailHandle ? toAlookAddress(task.agent.emailHandle) : null;+ const customAddrs = (task.agent?.emailAddresses ?? []).filter((a) => a !== alookAddr);++ if (alookAddr || customAddrs.length > 0) {+ const lines: string[] = [];+ if (alookAddr) lines.push(`- '${alookAddr}' (default, Alook platform address)`);+ for (const a of customAddrs) lines.push(`- '${a}' (custom IMAP/SMTP mailbox)`);+ content += `Your email addresses:\n${lines.join("\n")}+${task.agent?.userEmail ? `Your owner's email address is '${task.agent.userEmail}'.` : ""}### Emails---@@ -99,8 +105,9 @@ Before starting to process an email, mark it as read:#### Sending a new emailWrite the HTML body to a file first, then send it. The body is forwarded as-is (HTML).- Run 'npx @alook/cli email send --agent_id ${task.agentId} --to <ADDRESS> --subject "<SUBJECT>" --body-file <PATH_TO_HTML>'+- To send from a specific mailbox, add '--from <YOUR_EMAIL_ADDRESS>'. Without '--from', the default Alook address is used.- Attach files with '--attachment <PATH>' — repeat the flag for multiple attachments. Each file is uploaded before sending.-- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --attachment /tmp/report.pdf --attachment /tmp/chart.png'+- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --from [email protected] --attachment /tmp/report.pdf'#### Replying to an emailTo reply to an email, add '--in-reply-to <EMAIL_ID>' to the send command. This sets the correct email threading headers so the recipient's email client groups the reply into the same conversation thread.diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.tsindex 727217159..ddb6bc015 100644--- a/src/cli/daemon/types.ts+++ b/src/cli/daemon/types.ts@@ -26,6 +26,7 @@ export interface TaskAgentData {name: string;instructions: string;emailHandle?: string | null;+ emailAddresses?: string[];userEmail?: string | null;runtimeConfig?: Record<string, unknown>;}@@ -113,7 +114,7 @@ export function fromApiTask(api: import("@alook/shared").TaskApi): Task {contextKey: api.context_key ?? null,context: (api.context as Record<string, unknown>) ?? undefined,agent: api.agent- ? { name: api.agent.name, instructions: api.agent.instructions, emailHandle: api.agent.email_handle ?? undefined, userEmail: api.agent.user_email ?? undefined, runtimeConfig: api.agent.runtime_config ?? undefined }+ ? { name: api.agent.name, instructions: api.agent.instructions, emailHandle: api.agent.email_handle ?? undefined, emailAddresses: api.agent.email_addresses ?? [], userEmail: api.agent.user_email ?? undefined, runtimeConfig: api.agent.runtime_config ?? undefined }: undefined,repos: undefined,createdAt: api.created_at,diff --git a/src/email-worker/.dev.vars.example b/src/email-worker/.dev.vars.examplenew file mode 100644index 000000000..0f2c1ecdc--- /dev/null+++ b/src/email-worker/.dev.vars.example@@ -0,0 +1,11 @@+# =============================================================================+# Email Worker — Local Development Secrets+# =============================================================================+# Copy this file to .dev.vars and fill in your values.+# Wrangler reads .dev.vars automatically for local dev secrets.+# NEVER commit .dev.vars — it contains real secrets.+# =============================================================================++# Encryption key for IMAP/SMTP credentials (generate with: openssl rand -base64 32)+# Must match ENCRYPTION_KEY in web/.dev.vars — predev script syncs this automatically.+ENCRYPTION_KEY=diff --git a/src/email-worker/package.json b/src/email-worker/package.jsonindex 944d2c322..25ce41601 100644--- a/src/email-worker/package.json+++ b/src/email-worker/package.json@@ -10,8 +10,10 @@},"dependencies": {"@alook/shared": "workspace:*",+ "cf-imap": "^0.0.12","nanoid": "^5.1.9",- "postal-mime": "^2.7.4"+ "postal-mime": "^2.7.4",+ "worker-mailer": "^1.2.1"},"devDependencies": {"@cloudflare/workers-types": "^4.20260418.1",diff --git a/src/email-worker/src/imap-poller-do.test.ts b/src/email-worker/src/imap-poller-do.test.tsnew file mode 100644index 000000000..ead318aa4--- /dev/null+++ b/src/email-worker/src/imap-poller-do.test.ts@@ -0,0 +1,337 @@+import { describe, it, expect, vi, beforeEach } from "vitest"++// Mock cloudflare:workers — provide a real-enough DurableObject base class+vi.mock("cloudflare:workers", () => ({+ DurableObject: class {+ ctx: any+ env: any+ constructor(ctx: any, env: any) {+ this.ctx = ctx+ this.env = env+ }+ },+}))++// Mock cf-imap — using vi.hoisted so mock fns are available inside vi.mock factory+const { mockConnect, mockSelectFolder, mockSearchEmails, mockFetchEmails, mockLogout } = vi.hoisted(() => ({+ mockConnect: vi.fn().mockResolvedValue(undefined),+ mockSelectFolder: vi.fn().mockResolvedValue({ exists: 5 }),+ mockSearchEmails: vi.fn<() => Promise<number[]>>().mockResolvedValue([]),+ mockFetchEmails: vi.fn<() => Promise<any[]>>().mockResolvedValue([]),+ mockLogout: vi.fn().mockResolvedValue(true),+}))++vi.mock("cf-imap", () => {+ return {+ CFImap: class {+ connect = mockConnect+ selectFolder = mockSelectFolder+ searchEmails = mockSearchEmails+ fetchEmails = mockFetchEmails+ logout = mockLogout+ },+ }+})++// Mock nanoid+let nanoidCounter = 0+vi.mock("nanoid", () => ({+ nanoid: (len?: number) => `mock-${++nanoidCounter}`,+}))++// Mock @alook/shared/crypto+vi.mock("@alook/shared/crypto", () => ({+ encrypt: (val: string) => `encrypted:${val}`,+ decrypt: (val: string) => `decrypted:${val}`,+}))++// Mock @alook/shared+const mockGetEmailAccount = vi.fn()+const mockUpdateEmailAccount = vi.fn()+const mockIsWhitelisted = vi.fn().mockResolvedValue(true)++vi.mock("@alook/shared", () => {+ const noopLogger = {+ debug: () => {},+ info: () => {},+ warn: () => {},+ error: () => {},+ child: () => noopLogger,+ }+ return {+ createDb: () => ({}),+ createLogger: () => noopLogger,+ DEV_WEB_URL: "http://localhost:3000",+ queries: {+ emailAccount: {+ getEmailAccount: (...args: any[]) => mockGetEmailAccount(...args),+ getEmailAccountById: (...args: any[]) => mockGetEmailAccount(...args),+ updateEmailAccount: (...args: any[]) => mockUpdateEmailAccount(...args),+ },+ whitelist: {+ isWhitelisted: (...args: any[]) => mockIsWhitelisted(...args),+ },+ },+ }+})++import { ImapPollerDO } from "./imap-poller-do"++const ACCOUNT = {+ id: "aea_test1",+ agentId: "ag_test1",+ workspaceId: "ws_test1",+ emailAddress: "[email protected]",+ imapHost: "imap.gmail.com",+ imapPort: 993,+ imapUsername: "enc-user",+ imapPassword: "enc-pass",+ imapTls: true,+ smtpHost: "smtp.gmail.com",+ smtpPort: 587,+ smtpUsername: "enc-user",+ smtpPassword: "enc-pass",+ smtpTls: 1,+ pollIntervalSeconds: 60,+ lastSyncedUid: "0",+ lastSyncedAt: null,+ status: "active",+ errorMessage: "",+}++function createMockCtx() {+ const storage = new Map<string, any>()+ let alarm: number | null = null+ const ctx = {+ storage: {+ get: vi.fn(async (key: string) => storage.get(key)),+ put: vi.fn(async (key: string, val: any) => { storage.set(key, val) }),+ delete: vi.fn(async (key: string) => { storage.delete(key) }),+ deleteAll: vi.fn(async () => { storage.clear() }),+ setAlarm: vi.fn(async (time: number) => { alarm = time }),+ deleteAlarm: vi.fn(async () => { alarm = null }),+ },+ getWebSockets: vi.fn().mockReturnValue([]),+ }+ return { ctx, storage, getAlarm: () => alarm }+}++function createMockEnv() {+ const putR2 = vi.fn().mockResolvedValue(undefined)+ const webFetch = vi.fn().mockResolvedValue(new Response("ok"))+ return {+ env: {+ DB: {} as D1Database,+ EMAIL_BUCKET: { put: putR2 } as unknown as R2Bucket,+ WEB_SERVICE: { fetch: webFetch } as unknown as Fetcher,+ SEND_EMAIL: {} as SendEmail,+ IMAP_POLLER: {} as DurableObjectNamespace,+ ENCRYPTION_KEY: "test-secret",+ },+ putR2,+ webFetch,+ }+}++function createDO() {+ const { ctx, storage, getAlarm } = createMockCtx()+ const { env, putR2, webFetch } = createMockEnv()+ const durable = new ImapPollerDO(ctx as any, env as any)+ return { durable, ctx, storage, env, putR2, webFetch, getAlarm }+}++beforeEach(() => {+ nanoidCounter = 0+ vi.clearAllMocks()+ mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT })+ mockUpdateEmailAccount.mockResolvedValue(undefined)+ mockIsWhitelisted.mockResolvedValue(true)+ mockSearchEmails.mockResolvedValue([])+ mockFetchEmails.mockResolvedValue([])+})++// ─── T3: alarm normal flow ───++describe("alarm — normal flow", () => {+ it("fetches unseen emails, stores in R2, notifies web, and reschedules", async () => {+ const { durable, ctx, putR2, webFetch } = createDO()++ mockSearchEmails.mockResolvedValue([1, 2])+ mockFetchEmails.mockResolvedValue([+ { from: "[email protected]", to: "[email protected]", subject: "Hi", messageID: "<msg1>", raw: "raw1", body: "", contentType: "text/plain", date: new Date() },+ { from: "[email protected]", to: "[email protected]", subject: "Hey", messageID: "<msg2>", raw: "raw2", body: "", contentType: "text/plain", date: new Date() },+ ])++ await ctx.storage.put("accountId", "aea_test1")+ await durable.alarm()++ expect(putR2).toHaveBeenCalledTimes(2)+ expect(webFetch).toHaveBeenCalledTimes(2)++ const notify1 = JSON.parse(webFetch.mock.calls[0][1].body)+ expect(notify1.agentId).toBe("ag_test1")+ expect(notify1.from).toBe("[email protected]")+ expect(notify1.subject).toBe("Hi")+ expect(notify1.isWhitelisted).toBe(true)++ expect(mockUpdateEmailAccount).toHaveBeenCalled()+ expect(ctx.storage.setAlarm).toHaveBeenCalled()+ })+})++// ─── T4: whitelist filtering ───++describe("alarm — whitelist filtering", () => {+ it("passes isWhitelisted=true for whitelisted sender", async () => {+ const { durable, ctx, webFetch } = createDO()+ mockSearchEmails.mockResolvedValue([1])+ mockFetchEmails.mockResolvedValue([+ { from: "[email protected]", to: "[email protected]", subject: "Hi", messageID: "", raw: "raw", body: "", contentType: "text/plain", date: new Date() },+ ])+ mockIsWhitelisted.mockResolvedValue(true)++ await ctx.storage.put("accountId", "aea_test1")+ await durable.alarm()++ const notify = JSON.parse(webFetch.mock.calls[0][1].body)+ expect(notify.isWhitelisted).toBe(true)+ })++ it("passes isWhitelisted=false for non-whitelisted sender", async () => {+ const { durable, ctx, webFetch } = createDO()+ mockSearchEmails.mockResolvedValue([1])+ mockFetchEmails.mockResolvedValue([+ { from: "[email protected]", to: "[email protected]", subject: "Spam", messageID: "", raw: "raw", body: "", contentType: "text/plain", date: new Date() },+ ])+ mockIsWhitelisted.mockResolvedValue(false)++ await ctx.storage.put("accountId", "aea_test1")+ await durable.alarm()++ const notify = JSON.parse(webFetch.mock.calls[0][1].body)+ expect(notify.isWhitelisted).toBe(false)+ })+})++// ─── T5: connection failure & backoff ───++describe("alarm — connection failure & backoff", () => {+ it("sets error status and schedules with backoff on connection failure", async () => {+ const { durable, ctx } = createDO()+ mockConnect.mockRejectedValueOnce(new Error("Connection timeout"))++ await ctx.storage.put("accountId", "aea_test1")+ await durable.alarm()++ expect(mockUpdateEmailAccount).toHaveBeenCalledWith(+ expect.anything(), "aea_test1", "ws_test1",+ expect.objectContaining({ status: "error", errorMessage: expect.stringContaining("Connection timeout") })+ )+ expect(ctx.storage.setAlarm).toHaveBeenCalled()+ })+})++// ─── T6: auth failure ───++describe("alarm — auth failure", () => {+ it("stops polling on authentication error", async () => {+ const { durable, ctx } = createDO()+ mockConnect.mockResolvedValueOnce(undefined)+ mockSelectFolder.mockRejectedValueOnce(new Error("Authentication failed"))++ await ctx.storage.put("accountId", "aea_test1")+ await durable.alarm()++ expect(mockUpdateEmailAccount).toHaveBeenCalledWith(+ expect.anything(), "aea_test1", "ws_test1",+ expect.objectContaining({ status: "error", errorMessage: expect.stringContaining("Authentication") })+ )+ expect(ctx.storage.deleteAlarm).toHaveBeenCalled()+ })+})++// ─── T7: no new emails ───++describe("alarm — no new emails", () => {+ it("reschedules without fetching when SEARCH returns empty", async () => {+ const { durable, ctx, putR2, webFetch } = createDO()+ mockSearchEmails.mockResolvedValue([])++ await ctx.storage.put("accountId", "aea_test1")+ await durable.alarm()++ expect(mockFetchEmails).not.toHaveBeenCalled()+ expect(putR2).not.toHaveBeenCalled()+ expect(webFetch).not.toHaveBeenCalled()+ expect(ctx.storage.setAlarm).toHaveBeenCalled()+ expect(mockUpdateEmailAccount).toHaveBeenCalledWith(+ expect.anything(), "aea_test1", "ws_test1",+ expect.objectContaining({ status: "active" })+ )+ })+})++// ─── T8: fetch() routing ───++describe("fetch() routing", () => {+ it("POST /start sets accountId and schedules alarm", async () => {+ const { durable, ctx } = createDO()+ const res = await durable.fetch(new Request("http://internal/start", {+ method: "POST",+ body: JSON.stringify({ accountId: "aea_test1" }),+ }))+ expect(res.status).toBe(200)+ expect(await ctx.storage.get("accountId")).toBe("aea_test1")+ expect(ctx.storage.setAlarm).toHaveBeenCalled()+ })++ it("POST /stop cancels alarm and clears storage", async () => {+ const { durable, ctx } = createDO()+ await ctx.storage.put("accountId", "aea_test1")+ const res = await durable.fetch(new Request("http://internal/stop", { method: "POST" }))+ expect(res.status).toBe(200)+ expect(ctx.storage.deleteAlarm).toHaveBeenCalled()+ expect(ctx.storage.deleteAll).toHaveBeenCalled()+ })++ it("POST /sync triggers immediate poll", async () => {+ const { durable, ctx } = createDO()+ await ctx.storage.put("accountId", "aea_test1")+ const res = await durable.fetch(new Request("http://internal/sync", { method: "POST" }))+ expect(res.status).toBe(200)+ expect(mockSearchEmails).toHaveBeenCalled()+ })++ it("GET /status returns account status", async () => {+ const { durable, ctx } = createDO()+ await ctx.storage.put("accountId", "aea_test1")+ mockGetEmailAccount.mockResolvedValue({ status: "active", lastSyncedAt: "2025-01-01", errorMessage: "" })+ const res = await durable.fetch(new Request("http://internal/status", { method: "GET" }))+ const json = await res.json() as any+ expect(json.status).toBe("active")+ expect(json.lastSyncedAt).toBe("2025-01-01")+ })++ it("GET /status returns stopped when no accountId", async () => {+ const { durable } = createDO()+ const res = await durable.fetch(new Request("http://internal/status", { method: "GET" }))+ const json = await res.json() as any+ expect(json.status).toBe("stopped")+ })+})++// ─── T9: lifecycle ───++describe("lifecycle", () => {+ it("stops polling when account is deleted from DB", async () => {+ const { durable, ctx } = createDO()+ mockGetEmailAccount.mockResolvedValue(null)+ await ctx.storage.put("accountId", "aea_test1")++ await durable.alarm()++ expect(ctx.storage.deleteAlarm).toHaveBeenCalled()+ expect(ctx.storage.deleteAll).toHaveBeenCalled()+ expect(mockSearchEmails).not.toHaveBeenCalled()+ })+})diff --git a/src/email-worker/src/imap-poller-do.ts b/src/email-worker/src/imap-poller-do.tsnew file mode 100644index 000000000..f87d3936e--- /dev/null+++ b/src/email-worker/src/imap-poller-do.ts@@ -0,0 +1,210 @@+import { DurableObject } from "cloudflare:workers"+import { CFImap } from "cf-imap"+import { nanoid } from "nanoid"+import { createDb, queries, createLogger } from "@alook/shared"+import { decrypt } from "@alook/shared/crypto"+import type { EmailEnv } from "./types"++const log = createLogger({ service: "imap-poller" })++const MAX_BACKOFF_MS = 15 * 60 * 1000+const MAX_EMAILS_PER_POLL = 50++export class ImapPollerDO extends DurableObject<EmailEnv> {+ private accountId: string | null = null++ async fetch(request: Request): Promise<Response> {+ const url = new URL(request.url)++ if (url.pathname === "/start" && request.method === "POST") {+ const body = await request.json<{ accountId: string }>()+ this.accountId = body.accountId+ await this.ctx.storage.put("accountId", body.accountId)+ await this.ctx.storage.put("backoffMs", 0)+ await this.ctx.storage.setAlarm(Date.now() + 1000)+ return Response.json({ ok: true })+ }++ if (url.pathname === "/stop" && request.method === "POST") {+ await this.ctx.storage.deleteAlarm()+ await this.ctx.storage.deleteAll()+ return Response.json({ ok: true })+ }++ if (url.pathname === "/sync" && request.method === "POST") {+ await this.pollImap()+ return Response.json({ ok: true })+ }++ if (url.pathname === "/status" && request.method === "GET") {+ const accountId = await this.ctx.storage.get<string>("accountId")+ if (!accountId) return Response.json({ status: "stopped" })+ const db = createDb(this.env.DB)+ const account = await queries.emailAccount.getEmailAccountById(db, accountId)+ if (!account) return Response.json({ status: "not_found" })+ return Response.json({+ status: account.status,+ lastSyncedAt: account.lastSyncedAt,+ errorMessage: account.errorMessage,+ })+ }++ return Response.json({ error: "not found" }, { status: 404 })+ }++ async alarm(): Promise<void> {+ await this.pollImap()+ }++ private async pollImap(): Promise<void> {+ const accountId = this.accountId ?? await this.ctx.storage.get<string>("accountId")+ if (!accountId) return++ const db = createDb(this.env.DB)+ const account = await queries.emailAccount.getEmailAccountById(db, accountId)+ if (!account) {+ await this.ctx.storage.deleteAlarm()+ await this.ctx.storage.deleteAll()+ return+ }++ const pollLog = log.child({ accountId, agentId: account.agentId })+ let imap: CFImap | null = null++ try {+ const secret = this.env.ENCRYPTION_KEY+ if (!secret) throw new Error("ENCRYPTION_KEY not configured")++ const imapUsername = decrypt(account.imapUsername, secret)+ const imapPassword = decrypt(account.imapPassword, secret)++ imap = new CFImap({+ host: account.imapHost,+ port: account.imapPort,+ tls: account.imapTls as unknown as boolean,+ auth: { username: imapUsername, password: imapPassword },+ })++ await imap.connect()+ await imap.selectFolder("INBOX")++ const unseenSeqs = await imap.searchEmails({ seen: false })+ pollLog.info("search complete", { unseen: unseenSeqs.length })++ if (unseenSeqs.length === 0) {+ await queries.emailAccount.updateEmailAccount(db, accountId, account.workspaceId, {+ lastSyncedAt: new Date().toISOString(),+ status: "active",+ errorMessage: "",+ })+ await this.scheduleNext(account.pollIntervalSeconds * 1000)+ await imap.logout()+ return+ }++ const sorted = [...unseenSeqs].sort((a, b) => a - b)+ const batch = sorted.slice(0, MAX_EMAILS_PER_POLL)+ const start = batch[0]!+ const end = batch[batch.length - 1]!++ const fetched = await imap.fetchEmails({+ folder: "INBOX",+ limit: [start, end],+ fetchBody: true,+ peek: false,+ })++ pollLog.info("fetched emails", { count: fetched.length })++ for (const email of fetched) {+ const r2Id = nanoid()+ const r2Key = `emails/${r2Id}/raw`+ await this.env.EMAIL_BUCKET.put(r2Key, email.raw, {+ httpMetadata: { contentType: "message/rfc822" },+ })++ const fromEmail = email.from+ const isWhitelisted = await queries.whitelist.isWhitelisted(+ db, account.agentId, account.workspaceId, fromEmail+ )++ await this.notifyWeb({+ agentId: account.agentId,+ workspaceId: account.workspaceId,+ r2Key,+ from: fromEmail,+ to: account.emailAddress,+ subject: email.subject || "",+ isWhitelisted,+ messageId: email.messageID || "",+ inReplyTo: "",+ references: "",+ })+ }++ await queries.emailAccount.updateEmailAccount(db, accountId, account.workspaceId, {+ lastSyncedAt: new Date().toISOString(),+ status: "active",+ errorMessage: "",+ })++ await this.ctx.storage.put("backoffMs", 0)+ await this.scheduleNext(account.pollIntervalSeconds * 1000)+ await imap.logout()+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err)+ pollLog.error("poll failed", { error: msg })++ const isAuthError = /auth|login|credentials/i.test(msg)++ await queries.emailAccount.updateEmailAccount(db, accountId, account.workspaceId, {+ status: "error",+ errorMessage: msg.slice(0, 500),+ })++ if (isAuthError) {+ pollLog.warn("auth error — stopping polling, user must fix credentials")+ await this.ctx.storage.deleteAlarm()+ return+ }++ const currentBackoff = (await this.ctx.storage.get<number>("backoffMs")) ?? 0+ const nextBackoff = Math.min(+ currentBackoff === 0 ? account.pollIntervalSeconds * 1000 : currentBackoff * 2,+ MAX_BACKOFF_MS+ )+ await this.ctx.storage.put("backoffMs", nextBackoff)+ await this.scheduleNext(nextBackoff)++ try { await imap?.logout() } catch { /* ignore */ }+ }+ }++ private async scheduleNext(delayMs: number): Promise<void> {+ await this.ctx.storage.setAlarm(Date.now() + delayMs)+ }++ private async notifyWeb(payload: Record<string, unknown>): Promise<void> {+ const traceId = nanoid(12)+ const body = JSON.stringify(payload)+ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ "X-Trace-Id": traceId,+ }++ const init: RequestInit = { method: "POST", headers, body }++ try {+ const res = await this.env.WEB_SERVICE.fetch("http://internal/api/email/notify", init)+ if (!res.ok) throw new Error(`WEB_SERVICE responded ${res.status}`)+ } catch (serviceErr) {+ try {+ const { DEV_WEB_URL } = await import("@alook/shared")+ const fallback = await fetch(`${DEV_WEB_URL}/api/email/notify`, init)+ if (!fallback.ok) throw new Error(`fallback responded ${fallback.status}`)+ } catch {+ throw serviceErr instanceof Error ? serviceErr : new Error(String(serviceErr))+ }+ }+ }+}diff --git a/src/email-worker/src/index.test.ts b/src/email-worker/src/index.test.tsindex fb55e03db..535989f7b 100644--- a/src/email-worker/src/index.test.ts+++ b/src/email-worker/src/index.test.ts@@ -1,6 +1,28 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { createMockR2, createMockFetcher, createMockMessage, createMockSendEmail } from "./__mocks__/cf"+// Mock cloudflare:workers (DO base class) — needed because index.ts re-exports ImapPollerDO+vi.mock("cloudflare:workers", () => ({+ DurableObject: class {},+}))++// Mock cf-imap — not used by index.ts directly but imported transitively+vi.mock("cf-imap", () => ({+ CFImap: class {},+}))++// Mock worker-mailer+const mockWorkerMailerSend = vi.fn().mockResolvedValue(undefined)+vi.mock("worker-mailer", () => ({+ WorkerMailer: { send: (...args: any[]) => mockWorkerMailerSend(...args) },+}))++// Mock @alook/shared/crypto (separate subpath export, not in barrel)+vi.mock("@alook/shared/crypto", () => ({+ encrypt: (val: string) => `encrypted:${val}`,+ decrypt: (val: string) => `decrypted:${val}`,+}))+// Mock nanoid to return predictable IDslet nanoidCounter = 0vi.mock("nanoid", () => ({@@ -12,6 +34,7 @@ const mockGetAgentByHandle = vi.fn<(db: unknown, handle: unknown) => unknown>()const mockGetAgent = vi.fn<(db: unknown, id: unknown, workspaceId: unknown) => unknown>()const mockIsWhitelisted = vi.fn<(db: unknown, agentId: unknown, workspaceId: unknown, email: unknown) => unknown>()const mockGetUser = vi.fn<(db: unknown, id: unknown) => unknown>()+const mockGetEmailAccount = vi.fn()const mockCreateDb = vi.fn<(d1: unknown) => Record<string, unknown>>().mockReturnValue({})vi.mock("@alook/shared", () => {@@ -37,6 +60,7 @@ vi.mock("@alook/shared", () => {},whitelist: { isWhitelisted: (db: unknown, agentId: unknown, workspaceId: unknown, email: unknown) => mockIsWhitelisted(db, agentId, workspaceId, email) },user: { getUser: (db: unknown, id: unknown) => mockGetUser(db, id) },+ emailAccount: { getEmailAccount: (...args: unknown[]) => mockGetEmailAccount(...args), getEmailAccountById: (...args: unknown[]) => mockGetEmailAccount(...args) },},}})@@ -84,7 +108,7 @@ function setup(overrides?: {})- const env = { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail }+ const env = { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail, IMAP_POLLER: {} as DurableObjectNamespace, ENCRYPTION_KEY: "test-secret" }return { env, message, put, wsFetch, setReject, forward, rawText }}@@ -299,7 +323,7 @@ describe("POST /send/otp", () => {const { fetcher } = createMockFetcher()const { sendEmail, send } = createMockSendEmail()return {- env: { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail },+ env: { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail, IMAP_POLLER: {} as DurableObjectNamespace, ENCRYPTION_KEY: "test-secret" },send,}}@@ -358,7 +382,7 @@ describe("POST /send/agent", () => {const { fetcher } = createMockFetcher()const { sendEmail, send } = createMockSendEmail()return {- env: { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail },+ env: { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail, IMAP_POLLER: {} as DurableObjectNamespace, ENCRYPTION_KEY: "test-secret" },send,put,bucket,@@ -545,14 +569,144 @@ describe("POST /send/agent", () => {})})-// ─── Group 7: fetch() routing ───+// ─── Group 7: POST /send/agent with custom SMTP ───++describe("POST /send/agent with custom SMTP", () => {+ const CUSTOM_ACCOUNT = {+ id: "aea_1",+ agentId: "agent-1",+ workspaceId: "ws-1",+ emailAddress: "[email protected]",+ displayName: "Custom User",+ smtpHost: "smtp.gmail.com",+ smtpPort: 587,+ smtpUsername: "enc-user",+ smtpPassword: "enc-pass",+ smtpTls: 1,+ }++ function makeRequest(body: Record<string, unknown>) {+ return new Request("http://localhost/send/agent", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ })+ }++ function customSmtpEnv() {+ const { bucket, put } = createMockR2()+ const { fetcher } = createMockFetcher()+ const { sendEmail, send } = createMockSendEmail()+ return {+ env: { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail, IMAP_POLLER: {} as DurableObjectNamespace, ENCRYPTION_KEY: "test-secret" },+ send,+ put,+ }+ }++ it("sends via worker-mailer when customAccountId is provided", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })+ mockGetEmailAccount.mockResolvedValue(CUSTOM_ACCOUNT)+ const { env, send } = customSmtpEnv()++ const res = await handler.fetch(+ makeRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "Custom SMTP test",+ htmlBody: "<p>Hello</p>",+ customAccountId: "aea_1",+ }),+ env,+ )++ expect(res.status).toBe(200)+ expect(send).not.toHaveBeenCalled()+ expect(mockWorkerMailerSend).toHaveBeenCalledOnce()++ const [smtpOpts, emailOpts] = mockWorkerMailerSend.mock.calls[0]+ expect(smtpOpts.host).toBe("smtp.gmail.com")+ expect(smtpOpts.port).toBe(587)+ expect(smtpOpts.startTls).toBe(true)+ expect(smtpOpts.credentials.username).toBe("decrypted:enc-user")+ expect(smtpOpts.credentials.password).toBe("decrypted:enc-pass")+ expect(emailOpts.from).toEqual({ name: "Custom User", email: "[email protected]" })+ expect(emailOpts.to).toBe("[email protected]")+ expect(emailOpts.subject).toBe("Custom SMTP test")+ })++ it("falls back to CF SendEmail when no customAccountId", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })+ const { env, send } = customSmtpEnv()++ const res = await handler.fetch(+ makeRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "Default path",+ htmlBody: "<p>Hi</p>",+ }),+ env,+ )++ expect(res.status).toBe(200)+ expect(send).toHaveBeenCalledOnce()+ expect(mockWorkerMailerSend).not.toHaveBeenCalled()+ })++ it("returns 404 when customAccountId not found", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })+ mockGetEmailAccount.mockResolvedValue(null)+ const { env } = customSmtpEnv()++ const res = await handler.fetch(+ makeRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "Test",+ customAccountId: "aea_nonexistent",+ }),+ env,+ )++ expect(res.status).toBe(404)+ })++ it("returns 500 when SMTP send fails", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })+ mockGetEmailAccount.mockResolvedValue(CUSTOM_ACCOUNT)+ mockWorkerMailerSend.mockRejectedValueOnce(new Error("SMTP auth failed"))+ const { env } = customSmtpEnv()++ const res = await handler.fetch(+ makeRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "Test",+ htmlBody: "<p>Hi</p>",+ customAccountId: "aea_1",+ }),+ env,+ )++ expect(res.status).toBe(500)+ const json = await res.json() as { error: string }+ expect(json.error).toContain("SMTP send failed")+ })+})++// ─── Group 8: fetch() routing ───describe("fetch() routing", () => {function routingEnv() {const { bucket } = createMockR2()const { fetcher } = createMockFetcher()const { sendEmail } = createMockSendEmail()- return { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail }+ return { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail, IMAP_POLLER: {} as DurableObjectNamespace, ENCRYPTION_KEY: "test-secret" }}it("returns 404 for unknown paths", async () => {@@ -571,3 +725,82 @@ describe("fetch() routing", () => {expect(res.status).toBe(405)})})++// ─── Group 8: IMAP management routes ───++describe("IMAP management routes", () => {+ function imapEnv() {+ const { bucket } = createMockR2()+ const { fetcher } = createMockFetcher()+ const { sendEmail } = createMockSendEmail()+ const doFetch = vi.fn().mockResolvedValue(Response.json({ ok: true }))+ const mockStub = { fetch: doFetch }+ const mockIdFromName = vi.fn().mockReturnValue("do-id-1")+ const mockGet = vi.fn().mockReturnValue(mockStub)+ const imapPoller = { idFromName: mockIdFromName, get: mockGet } as unknown as DurableObjectNamespace+ return {+ env: { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail, IMAP_POLLER: imapPoller, ENCRYPTION_KEY: "test-secret" },+ doFetch,+ mockIdFromName,+ mockGet,+ }+ }++ it("POST /imap/start forwards to DO with accountId", async () => {+ const { env, doFetch, mockIdFromName } = imapEnv()+ const res = await handler.fetch(+ new Request("http://localhost/imap/start?accountId=acc-1", { method: "POST" }),+ env,+ )+ expect(res.status).toBe(200)+ expect(mockIdFromName).toHaveBeenCalledWith("acc-1")+ expect(doFetch).toHaveBeenCalledOnce()+ const [req] = doFetch.mock.calls[0] as [Request]+ expect(new URL(req.url).pathname).toBe("/start")+ const body = await req.json()+ expect(body).toEqual({ accountId: "acc-1" })+ })++ it("POST /imap/stop forwards to DO", async () => {+ const { env, doFetch } = imapEnv()+ const res = await handler.fetch(+ new Request("http://localhost/imap/stop?accountId=acc-1", { method: "POST" }),+ env,+ )+ expect(res.status).toBe(200)+ const [req] = doFetch.mock.calls[0] as [Request]+ expect(new URL(req.url).pathname).toBe("/stop")+ })++ it("POST /imap/sync forwards to DO", async () => {+ const { env, doFetch } = imapEnv()+ const res = await handler.fetch(+ new Request("http://localhost/imap/sync?accountId=acc-1", { method: "POST" }),+ env,+ )+ expect(res.status).toBe(200)+ const [req] = doFetch.mock.calls[0] as [Request]+ expect(new URL(req.url).pathname).toBe("/sync")+ })++ it("GET /imap/status forwards to DO", async () => {+ const { env, doFetch } = imapEnv()+ const res = await handler.fetch(+ new Request("http://localhost/imap/status?accountId=acc-1", { method: "GET" }),+ env,+ )+ expect(res.status).toBe(200)+ const [req] = doFetch.mock.calls[0] as [Request]+ expect(new URL(req.url).pathname).toBe("/status")+ expect(req.method).toBe("GET")+ })++ it("returns 400 when accountId is missing", async () => {+ const { env } = imapEnv()+ const res = await handler.fetch(+ new Request("http://localhost/imap/start", { method: "POST" }),+ env,+ )+ expect(res.status).toBe(400)+ })+})diff --git a/src/email-worker/src/index.ts b/src/email-worker/src/index.tsindex 623cf2981..9e2b68733 100644--- a/src/email-worker/src/index.ts+++ b/src/email-worker/src/index.ts@@ -1,14 +1,12 @@import { nanoid } from "nanoid"import { createDb, queries, parseEmailHandle, DEV_WEB_URL, createLogger } from "@alook/shared"+import { decrypt } from "@alook/shared/crypto"+import { WorkerMailer } from "worker-mailer"+import type { EmailEnv } from "./types"-const log = createLogger({ service: "email" })+export { ImapPollerDO } from "./imap-poller-do"-interface EmailEnv {- DB: D1Database- EMAIL_BUCKET: R2Bucket- WEB_SERVICE: Fetcher- SEND_EMAIL: SendEmail-}+const log = createLogger({ service: "email" })function arrayBufferToBase64(buffer: ArrayBuffer): string {const bytes = new Uint8Array(buffer)@@ -26,20 +24,18 @@ async function notifyWeb(env: EmailEnv, payload: Record<string, unknown>, traceI"X-Trace-Id": traceId,}+ const init: RequestInit = { method: "POST", headers, body }+try {- const res = await env.WEB_SERVICE.fetch("http://internal/api/email/notify", {- method: "POST",- headers,- body,- })+ const res = await env.WEB_SERVICE.fetch("http://internal/api/email/notify", init)if (!res.ok) throw new Error(`WEB_SERVICE responded ${res.status}`)- } catch (err) {- log.warn("WEB_SERVICE notify failed, falling back to DEV_WEB_URL", { err })- await fetch(`${DEV_WEB_URL}/api/email/notify`, {- method: "POST",- headers,- body,- })+ } catch (serviceErr) {+ try {+ const fallback = await fetch(`${DEV_WEB_URL}/api/email/notify`, init)+ if (!fallback.ok) throw new Error(`fallback responded ${fallback.status}`)+ } catch {+ throw serviceErr instanceof Error ? serviceErr : new Error(String(serviceErr))+ }}}@@ -47,6 +43,10 @@ export default {async fetch(request: Request, env: EmailEnv): Promise<Response> {const url = new URL(request.url)+ if (url.pathname.startsWith("/imap/")) {+ return this.handleImap(request, env, url)+ }+if (request.method !== "POST") {return Response.json({ error: "method not allowed" }, { status: 405 })}@@ -89,6 +89,7 @@ export default {inReplyTo?: stringreferences?: stringattachmentKeys?: { key: string; filename: string; contentType: string }[]+ customAccountId?: string}if (!body.agentId || !body.workspaceId || !body.to || !body.subject) {@@ -101,11 +102,26 @@ export default {return Response.json({ error: "agent not found in workspace" }, { status: 404 })}- if (!agent.emailHandle) {- return Response.json({ error: "agent has no email handle configured" }, { status: 400 })+ let fromAddress: string+ let useCustomSmtp = false+ let customAccount: Awaited<ReturnType<typeof queries.emailAccount.getEmailAccount>> | null = null++ if (body.customAccountId) {+ customAccount = await queries.emailAccount.getEmailAccount(db, body.customAccountId, body.workspaceId)+ if (!customAccount) {+ return Response.json({ error: "custom email account not found" }, { status: 404 })+ }+ fromAddress = customAccount.displayName+ ? `${customAccount.displayName} <${customAccount.emailAddress}>`+ : customAccount.emailAddress+ useCustomSmtp = true+ } else {+ if (!agent.emailHandle) {+ return Response.json({ error: "agent has no email handle configured" }, { status: 400 })+ }+ fromAddress = `${agent.emailHandle}@alook.ai`}- const fromAddress = `${agent.emailHandle}@alook.ai`const htmlBody = body.htmlBody ?? ""const attachmentKeys = body.attachmentKeys ?? []@@ -123,17 +139,60 @@ export default {})}- // Send via CF builder overload (content as base64 string per CF docs)- const sendPayload: Record<string, unknown> = {- from: fromAddress,- to: body.to,- subject: body.subject,- html: htmlBody,- }- if (attachments.length > 0) {- sendPayload.attachments = attachments+ if (useCustomSmtp && customAccount) {+ const secret = env.ENCRYPTION_KEY+ if (!secret) {+ return Response.json({ error: "encryption key not configured" }, { status: 500 })+ }+ try {+ const smtpUsername = decrypt(customAccount.smtpUsername, secret)+ const smtpPassword = decrypt(customAccount.smtpPassword, secret)+ const smtpTls = customAccount.smtpTls as number++ const threadingHeaders: Record<string, string> = {}+ if (body.inReplyTo) threadingHeaders["In-Reply-To"] = body.inReplyTo+ if (body.references) threadingHeaders["References"] = body.references++ await WorkerMailer.send(+ {+ host: customAccount.smtpHost,+ port: customAccount.smtpPort,+ secure: smtpTls === 2,+ startTls: smtpTls === 1,+ credentials: { username: smtpUsername, password: smtpPassword },+ },+ {+ from: customAccount.displayName+ ? { name: customAccount.displayName, email: customAccount.emailAddress }+ : customAccount.emailAddress,+ to: body.to,+ subject: body.subject,+ html: htmlBody,+ headers: threadingHeaders,+ attachments: attachments.map(a => ({+ filename: a.filename,+ content: a.content,+ mimeType: a.type,+ })),+ }+ )+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err)+ log.error("custom SMTP send failed", { error: msg, accountId: body.customAccountId })+ return Response.json({ error: `SMTP send failed: ${msg}` }, { status: 500 })+ }+ } else {+ const sendPayload: Record<string, unknown> = {+ from: fromAddress,+ to: body.to,+ subject: body.subject,+ html: htmlBody,+ }+ if (attachments.length > 0) {+ sendPayload.attachments = attachments+ }+ await env.SEND_EMAIL.send(sendPayload as any)}- await env.SEND_EMAIL.send(sendPayload as any)// Build raw MIME for R2 archivalconst outMessageId = `<${nanoid()}@alook.ai>`@@ -198,6 +257,97 @@ export default {return Response.json({ ok: true, r2Key, messageId: outMessageId })},+ async handleImap(request: Request, env: EmailEnv, url: URL): Promise<Response> {+ const accountId = url.searchParams.get("accountId")+ if (!accountId) {+ return Response.json({ error: "accountId query parameter required" }, { status: 400 })+ }++ const doId = env.IMAP_POLLER.idFromName(accountId)+ const stub = env.IMAP_POLLER.get(doId)++ const action = url.pathname.replace("/imap/", "")++ if (action === "start" && request.method === "POST") {+ return stub.fetch(new Request("http://internal/start", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ accountId }),+ }))+ }++ if (action === "stop" && request.method === "POST") {+ return stub.fetch(new Request("http://internal/stop", { method: "POST" }))+ }++ if (action === "sync" && request.method === "POST") {+ return stub.fetch(new Request("http://internal/sync", { method: "POST" }))+ }++ if (action === "status" && request.method === "GET") {+ return stub.fetch(new Request("http://internal/status", { method: "GET" }))+ }++ if (action === "test" && request.method === "POST") {+ return this.handleTestConnection(accountId, env)+ }++ return Response.json({ error: "not found" }, { status: 404 })+ },++ async handleTestConnection(accountId: string, env: EmailEnv): Promise<Response> {+ const db = createDb(env.DB)+ const account = await queries.emailAccount.getEmailAccountById(db, accountId)+ if (!account) {+ return Response.json({ error: "account not found" }, { status: 404 })+ }++ const secret = env.ENCRYPTION_KEY+ if (!secret) {+ return Response.json({ error: "encryption key not configured" }, { status: 500 })+ }++ const result: { imap: string; smtp: string } = { imap: "untested", smtp: "untested" }++ try {+ const { CFImap } = await import("cf-imap")+ const imapClient = new CFImap({+ host: account.imapHost,+ port: account.imapPort,+ tls: account.imapTls as unknown as boolean,+ auth: {+ username: decrypt(account.imapUsername, secret),+ password: decrypt(account.imapPassword, secret),+ },+ })+ await imapClient.connect()+ await imapClient.logout()+ result.imap = "ok"+ } catch (err: unknown) {+ result.imap = `error: ${err instanceof Error ? err.message : String(err)}`+ }++ try {+ const smtpUsername = decrypt(account.smtpUsername, secret)+ const smtpPassword = decrypt(account.smtpPassword, secret)+ const smtpTls = account.smtpTls as number+ const mailer = await WorkerMailer.connect({+ host: account.smtpHost,+ port: account.smtpPort,+ secure: smtpTls === 2,+ startTls: smtpTls === 1,+ credentials: { username: smtpUsername, password: smtpPassword },+ })+ await mailer.close()+ result.smtp = "ok"+ } catch (err: unknown) {+ result.smtp = `error: ${err instanceof Error ? err.message : String(err)}`+ }++ const allOk = result.imap === "ok" && result.smtp === "ok"+ return Response.json(result, { status: allOk ? 200 : 422 })+ },+async email(message: ForwardableEmailMessage, env: EmailEnv): Promise<void> {const traceId = nanoid(12)const emailLog = log.child({ traceId, from: message.from, to: message.to })diff --git a/src/email-worker/src/types.ts b/src/email-worker/src/types.tsnew file mode 100644index 000000000..97111d783--- /dev/null+++ b/src/email-worker/src/types.ts@@ -0,0 +1,8 @@+export interface EmailEnv {+ DB: D1Database+ EMAIL_BUCKET: R2Bucket+ WEB_SERVICE: Fetcher+ SEND_EMAIL: SendEmail+ IMAP_POLLER: DurableObjectNamespace+ ENCRYPTION_KEY: string+}diff --git a/src/email-worker/wrangler.toml b/src/email-worker/wrangler.tomlindex 257d39556..c32d20d53 100644--- a/src/email-worker/wrangler.toml+++ b/src/email-worker/wrangler.toml@@ -28,3 +28,11 @@ service = "alook-web"[[send_email]]name = "SEND_EMAIL"++[[durable_objects.bindings]]+name = "IMAP_POLLER"+class_name = "ImapPollerDO"++[[migrations]]+tag = "v1"+new_sqlite_classes = ["ImapPollerDO"]diff --git a/src/shared/package.json b/src/shared/package.jsonindex fae90f611..03e047b8f 100644--- a/src/shared/package.json+++ b/src/shared/package.json@@ -2,7 +2,7 @@"name": "@alook/shared","version": "0.0.1","private": true,- "exports": { ".": "./src/index.ts" },+ "exports": { ".": "./src/index.ts", "./crypto": "./src/utils/crypto.ts" },"scripts": { "test": "vitest run", "typecheck": "tsc --noEmit" },"dependencies": {"drizzle-orm": "^0.45.2",diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex 90515978c..52b2505c0 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -14,3 +14,4 @@ export * as email from "./queries/email";export * as session from "./queries/session";export * as calendarEvent from "./queries/calendar-event";export * as artifact from "./queries/artifact";+export * as emailAccount from "./queries/email-account";diff --git a/src/shared/src/db/queries/email-account.ts b/src/shared/src/db/queries/email-account.tsnew file mode 100644index 000000000..3f50fa1f9--- /dev/null+++ b/src/shared/src/db/queries/email-account.ts@@ -0,0 +1,102 @@+import { eq, and } from "drizzle-orm";+import { agentEmailAccount } from "../schema";+import type { Database } from "../index";++export async function createEmailAccount(+ db: Database,+ data: {+ agentId: string;+ workspaceId: string;+ emailAddress: string;+ displayName?: string;+ imapHost: string;+ imapPort?: number;+ imapUsername: string;+ imapPassword: string;+ imapTls?: boolean;+ smtpHost: string;+ smtpPort?: number;+ smtpUsername: string;+ smtpPassword: string;+ smtpTls?: number;+ pollIntervalSeconds?: number;+ }+) {+ const rows = await db.insert(agentEmailAccount).values(data).returning();+ return rows[0]!;+}++export async function getEmailAccount(db: Database, id: string, workspaceId: string) {+ const rows = await db+ .select()+ .from(agentEmailAccount)+ .where(and(eq(agentEmailAccount.id, id), eq(agentEmailAccount.workspaceId, workspaceId)));+ return rows[0] ?? null;+}++export async function getEmailAccountScoped(db: Database, id: string, agentId: string, workspaceId: string) {+ const rows = await db+ .select()+ .from(agentEmailAccount)+ .where(and(+ eq(agentEmailAccount.id, id),+ eq(agentEmailAccount.agentId, agentId),+ eq(agentEmailAccount.workspaceId, workspaceId),+ ));+ return rows[0] ?? null;+}++export async function getEmailAccountById(db: Database, id: string) {+ const rows = await db+ .select()+ .from(agentEmailAccount)+ .where(eq(agentEmailAccount.id, id));+ return rows[0] ?? null;+}++export async function getEmailAccountsByAgent(db: Database, agentId: string, workspaceId: string) {+ return db+ .select()+ .from(agentEmailAccount)+ .where(and(eq(agentEmailAccount.agentId, agentId), eq(agentEmailAccount.workspaceId, workspaceId)));+}++export async function updateEmailAccount(+ db: Database,+ id: string,+ workspaceId: string,+ data: Partial<{+ emailAddress: string;+ displayName: string;+ imapHost: string;+ imapPort: number;+ imapUsername: string;+ imapPassword: string;+ imapTls: boolean;+ smtpHost: string;+ smtpPort: number;+ smtpUsername: string;+ smtpPassword: string;+ smtpTls: number;+ pollIntervalSeconds: number;+ lastSyncedUid: string;+ lastSyncedAt: string | null;+ status: string;+ errorMessage: string;+ }>+) {+ const rows = await db+ .update(agentEmailAccount)+ .set({ ...data, updatedAt: new Date().toISOString() })+ .where(and(eq(agentEmailAccount.id, id), eq(agentEmailAccount.workspaceId, workspaceId)))+ .returning();+ return rows[0] ?? null;+}++export async function deleteEmailAccount(db: Database, id: string, workspaceId: string) {+ const rows = await db+ .delete(agentEmailAccount)+ .where(and(eq(agentEmailAccount.id, id), eq(agentEmailAccount.workspaceId, workspaceId)))+ .returning();+ return rows[0] ?? null;+}diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex 2f4b875b0..ca484e25b 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -356,6 +356,46 @@ export const artifact = sqliteTable(]);+export const agentEmailAccount = sqliteTable(+ "agent_email_account",+ {+ id: text("id").primaryKey().$defaultFn(() => "aea_" + nanoid()),+ agentId: text("agent_id").notNull(),+ workspaceId: text("workspace_id").notNull(),+ emailAddress: text("email_address").notNull(),+ displayName: text("display_name").notNull().default(""),++ imapHost: text("imap_host").notNull(),+ imapPort: integer("imap_port").notNull().default(993),+ imapUsername: text("imap_username").notNull(),+ imapPassword: text("imap_password").notNull(),+ imapTls: integer("imap_tls", { mode: "boolean" }).notNull().default(true),++ smtpHost: text("smtp_host").notNull(),+ smtpPort: integer("smtp_port").notNull().default(587),+ smtpUsername: text("smtp_username").notNull(),+ smtpPassword: text("smtp_password").notNull(),+ smtpTls: integer("smtp_tls").notNull().default(1),++ pollIntervalSeconds: integer("poll_interval_seconds").notNull().default(60),+ lastSyncedUid: text("last_synced_uid").notNull().default("0"),+ lastSyncedAt: text("last_synced_at"),+ status: text("status").notNull().default("active"),+ errorMessage: text("error_message").notNull().default(""),++ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),+ },+ (t) => [+ index("idx_email_account_agent_ws").on(t.agentId, t.workspaceId),+ unique("email_account_agent_email").on(t.agentId, t.emailAddress),+ foreignKey({+ columns: [t.agentId, t.workspaceId],+ foreignColumns: [agent.id, agent.workspaceId],+ }).onDelete("cascade"),+ ]+);+export const machineToken = sqliteTable("machine_token",{diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 4fc861b6c..7ba02982c 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -12,6 +12,7 @@ export type {Email,EmailAttachment,Artifact,+ AgentEmailAccount,LoginResponse,CreateAgentRequest,CalendarEvent,@@ -107,6 +108,9 @@ export {UpdateEmailStatusRequestSchema,EmailNotifyRequestSchema,CreateWorkspaceRequestSchema,+ CreateEmailAccountSchema,+ UpdateEmailAccountSchema,+ TestEmailConnectionSchema,} from "./schemas";export type {@@ -131,6 +135,9 @@ export type {DeleteCalendarEventRequestInput,CalendarEventApi,AddWhitelistRequest,+ CreateEmailAccountRequest,+ UpdateEmailAccountRequest,+ TestEmailConnectionRequest,} from "./schemas";// Databasediff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 19b99af38..57baf4d53 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -49,6 +49,7 @@ export const TaskAgentDataApiSchema = z.object({name: z.string(),runtime_config: z.record(z.string(), z.unknown()).default({}),email_handle: z.string().nullable().optional(),+ email_addresses: z.array(z.string()).default([]),user_email: z.string().nullable().optional(),});export type TaskAgentDataApi = z.infer<typeof TaskAgentDataApiSchema>;@@ -384,6 +385,8 @@ export const SendEmailRequestSchema = z.object({inReplyTo: z.string().optional(),references: z.string().optional(),attachments: z.array(EmailAttachmentSchema).optional(),+ customAccountId: z.string().optional(),+ from: z.string().email().optional(),});export type SendEmailRequest = z.infer<typeof SendEmailRequestSchema>;@@ -409,6 +412,58 @@ export const EmailNotifyRequestSchema = z.object({});export type EmailNotifyRequest = z.infer<typeof EmailNotifyRequestSchema>;+// ---------------------------------------------------------------------------+// Custom Email Account schemas+// ---------------------------------------------------------------------------++export const CreateEmailAccountSchema = z.object({+ emailAddress: z.string().email("valid email required"),+ displayName: z.string().default(""),+ imapHost: z.string().min(1, "IMAP host is required"),+ imapPort: z.number().int().min(1).max(65535).default(993),+ imapUsername: z.string().min(1, "IMAP username is required"),+ imapPassword: z.string().min(1, "IMAP password is required"),+ imapTls: z.boolean().default(true),+ smtpHost: z.string().min(1, "SMTP host is required"),+ smtpPort: z.number().int().min(1).max(65535).default(587),+ smtpUsername: z.string().min(1, "SMTP username is required"),+ smtpPassword: z.string().min(1, "SMTP password is required"),+ smtpTls: z.number().int().min(0).max(2).default(1),+ pollIntervalSeconds: z.number().int().min(30).max(3600).default(60),+});+export type CreateEmailAccountRequest = z.infer<typeof CreateEmailAccountSchema>;++export const UpdateEmailAccountSchema = z.object({+ emailAddress: z.string().email().optional(),+ displayName: z.string().optional(),+ imapHost: z.string().min(1).optional(),+ imapPort: z.number().int().min(1).max(65535).optional(),+ imapUsername: z.string().min(1).optional(),+ imapPassword: z.string().min(1).optional(),+ imapTls: z.boolean().optional(),+ smtpHost: z.string().min(1).optional(),+ smtpPort: z.number().int().min(1).max(65535).optional(),+ smtpUsername: z.string().min(1).optional(),+ smtpPassword: z.string().min(1).optional(),+ smtpTls: z.number().int().min(0).max(2).optional(),+ pollIntervalSeconds: z.number().int().min(30).max(3600).optional(),+});+export type UpdateEmailAccountRequest = z.infer<typeof UpdateEmailAccountSchema>;++export const TestEmailConnectionSchema = z.object({+ imapHost: z.string().min(1),+ imapPort: z.number().int().min(1).max(65535).default(993),+ imapUsername: z.string().min(1),+ imapPassword: z.string().min(1),+ imapTls: z.boolean().default(true),+ smtpHost: z.string().min(1),+ smtpPort: z.number().int().min(1).max(65535).default(587),+ smtpUsername: z.string().min(1),+ smtpPassword: z.string().min(1),+ smtpTls: z.number().int().min(0).max(2).default(1),+});+export type TestEmailConnectionRequest = z.infer<typeof TestEmailConnectionSchema>;+// ---------------------------------------------------------------------------// Workspace request schemas// ---------------------------------------------------------------------------diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex fc7e271ac..c4a864750 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -139,6 +139,26 @@ export interface Email {created_at: string;}+export interface AgentEmailAccount {+ id: string;+ agent_id: string;+ workspace_id: string;+ email_address: string;+ display_name: string;+ imap_host: string;+ imap_port: number;+ imap_tls: boolean;+ smtp_host: string;+ smtp_port: number;+ smtp_tls: number;+ poll_interval_seconds: number;+ last_synced_at: string | null;+ status: string;+ error_message: string;+ created_at: string;+ updated_at: string;+}+export interface Artifact {id: string;conversation_id: string;diff --git a/src/shared/src/utils/crypto.ts b/src/shared/src/utils/crypto.tsnew file mode 100644index 000000000..0c6177693--- /dev/null+++ b/src/shared/src/utils/crypto.ts@@ -0,0 +1,29 @@+import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto"++const ALG = "aes-256-gcm"+const IV_LEN = 12+const TAG_LEN = 16++function deriveKey(secret: string): Buffer {+ return createHash("sha256").update(secret).digest()+}++export function encrypt(plaintext: string, secret: string): string {+ const key = deriveKey(secret)+ const iv = randomBytes(IV_LEN)+ const cipher = createCipheriv(ALG, key, iv)+ const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()])+ const tag = cipher.getAuthTag()+ return Buffer.concat([iv, tag, encrypted]).toString("base64")+}++export function decrypt(encrypted: string, secret: string): string {+ const key = deriveKey(secret)+ const buf = Buffer.from(encrypted, "base64")+ const iv = buf.subarray(0, IV_LEN)+ const tag = buf.subarray(IV_LEN, IV_LEN + TAG_LEN)+ const ciphertext = buf.subarray(IV_LEN + TAG_LEN)+ const decipher = createDecipheriv(ALG, key, iv)+ decipher.setAuthTag(tag)+ return decipher.update(ciphertext) + decipher.final("utf8")+}diff --git a/src/shared/test/schemas/email-account.test.ts b/src/shared/test/schemas/email-account.test.tsnew file mode 100644index 000000000..547d45992--- /dev/null+++ b/src/shared/test/schemas/email-account.test.ts@@ -0,0 +1,91 @@+import { describe, it, expect } from "vitest"+import { CreateEmailAccountSchema, UpdateEmailAccountSchema, TestEmailConnectionSchema } from "../../src/schemas"++describe("CreateEmailAccountSchema", () => {+ const valid = {+ emailAddress: "[email protected]",+ imapHost: "imap.gmail.com",+ imapUsername: "[email protected]",+ imapPassword: "app-password-123",+ smtpHost: "smtp.gmail.com",+ smtpUsername: "[email protected]",+ smtpPassword: "app-password-123",+ }++ it("accepts valid input with defaults", () => {+ const result = CreateEmailAccountSchema.parse(valid)+ expect(result.emailAddress).toBe("[email protected]")+ expect(result.imapPort).toBe(993)+ expect(result.smtpPort).toBe(587)+ expect(result.imapTls).toBe(true)+ expect(result.smtpTls).toBe(1)+ expect(result.pollIntervalSeconds).toBe(60)+ expect(result.displayName).toBe("")+ })++ it("accepts custom ports", () => {+ const result = CreateEmailAccountSchema.parse({ ...valid, imapPort: 143, smtpPort: 465 })+ expect(result.imapPort).toBe(143)+ expect(result.smtpPort).toBe(465)+ })++ it("rejects invalid email", () => {+ expect(() => CreateEmailAccountSchema.parse({ ...valid, emailAddress: "not-email" })).toThrow()+ })++ it("rejects missing required fields", () => {+ expect(() => CreateEmailAccountSchema.parse({ emailAddress: "[email protected]" })).toThrow()+ })++ it("rejects port out of range", () => {+ expect(() => CreateEmailAccountSchema.parse({ ...valid, imapPort: 0 })).toThrow()+ expect(() => CreateEmailAccountSchema.parse({ ...valid, smtpPort: 70000 })).toThrow()+ })++ it("rejects poll interval too short", () => {+ expect(() => CreateEmailAccountSchema.parse({ ...valid, pollIntervalSeconds: 10 })).toThrow()+ })++ it("rejects poll interval too long", () => {+ expect(() => CreateEmailAccountSchema.parse({ ...valid, pollIntervalSeconds: 7200 })).toThrow()+ })+})++describe("UpdateEmailAccountSchema", () => {+ it("accepts partial update", () => {+ const result = UpdateEmailAccountSchema.parse({ displayName: "New Name" })+ expect(result.displayName).toBe("New Name")+ expect(result.imapHost).toBeUndefined()+ })++ it("accepts empty object", () => {+ const result = UpdateEmailAccountSchema.parse({})+ expect(Object.keys(result).length).toBe(0)+ })++ it("rejects invalid email when provided", () => {+ expect(() => UpdateEmailAccountSchema.parse({ emailAddress: "bad" })).toThrow()+ })+})++describe("TestEmailConnectionSchema", () => {+ const valid = {+ imapHost: "imap.gmail.com",+ imapUsername: "[email protected]",+ imapPassword: "pass",+ smtpHost: "smtp.gmail.com",+ smtpUsername: "[email protected]",+ smtpPassword: "pass",+ }++ it("accepts valid input", () => {+ const result = TestEmailConnectionSchema.parse(valid)+ expect(result.imapPort).toBe(993)+ expect(result.smtpPort).toBe(587)+ })++ it("rejects missing IMAP host", () => {+ const { imapHost, ...rest } = valid+ expect(() => TestEmailConnectionSchema.parse(rest)).toThrow()+ })+})diff --git a/src/shared/test/utils/crypto.test.ts b/src/shared/test/utils/crypto.test.tsnew file mode 100644index 000000000..080b620dd--- /dev/null+++ b/src/shared/test/utils/crypto.test.ts@@ -0,0 +1,47 @@+import { describe, it, expect } from "vitest"+import { encrypt, decrypt } from "../../src/utils/crypto"++const SECRET = "test-secret-key-for-encryption"++describe("encrypt / decrypt", () => {+ it("round-trips a normal string", () => {+ const plain = "hello world"+ expect(decrypt(encrypt(plain, SECRET), SECRET)).toBe(plain)+ })++ it("round-trips an empty string", () => {+ expect(decrypt(encrypt("", SECRET), SECRET)).toBe("")+ })++ it("round-trips unicode", () => {+ const plain = "こんにちは 🌍 café"+ expect(decrypt(encrypt(plain, SECRET), SECRET)).toBe(plain)+ })++ it("round-trips a long string (>1KB)", () => {+ const plain = "a".repeat(2000)+ expect(decrypt(encrypt(plain, SECRET), SECRET)).toBe(plain)+ })++ it("produces different ciphertext each time (random IV)", () => {+ const plain = "deterministic?"+ const a = encrypt(plain, SECRET)+ const b = encrypt(plain, SECRET)+ expect(a).not.toBe(b)+ expect(decrypt(a, SECRET)).toBe(plain)+ expect(decrypt(b, SECRET)).toBe(plain)+ })++ it("fails to decrypt with wrong key", () => {+ const enc = encrypt("secret", SECRET)+ expect(() => decrypt(enc, "wrong-key")).toThrow()+ })++ it("fails on tampered ciphertext (GCM auth tag)", () => {+ const enc = encrypt("secret", SECRET)+ const buf = Buffer.from(enc, "base64")+ buf[buf.length - 1] ^= 0xff+ const tampered = buf.toString("base64")+ expect(() => decrypt(tampered, SECRET)).toThrow()+ })+})diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.exampleindex 25661c053..bc482d72b 100644--- a/src/web/.dev.vars.example+++ b/src/web/.dev.vars.example@@ -10,6 +10,9 @@BETTER_AUTH_SECRET=BETTER_AUTH_URL=http://localhost:3000+# Encryption key for IMAP/SMTP credentials (generate with: openssl rand -base64 32)+ENCRYPTION_KEY=+# GitHub OAuth App (https://github.com/settings/developers)GITHUB_CLIENT_ID=GITHUB_CLIENT_SECRET=diff --git a/src/web/migrations/0004_agent_email_account.sql b/src/web/migrations/0004_agent_email_account.sqlnew file mode 100644index 000000000..7c65cca44--- /dev/null+++ b/src/web/migrations/0004_agent_email_account.sql@@ -0,0 +1,32 @@+CREATE TABLE IF NOT EXISTS agent_email_account (+ id TEXT PRIMARY KEY,+ agent_id TEXT NOT NULL,+ workspace_id TEXT NOT NULL,+ email_address TEXT NOT NULL,+ display_name TEXT NOT NULL DEFAULT '',++ imap_host TEXT NOT NULL,+ imap_port INTEGER NOT NULL DEFAULT 993,+ imap_username TEXT NOT NULL,+ imap_password TEXT NOT NULL,+ imap_tls INTEGER NOT NULL DEFAULT 1,++ smtp_host TEXT NOT NULL,+ smtp_port INTEGER NOT NULL DEFAULT 587,+ smtp_username TEXT NOT NULL,+ smtp_password TEXT NOT NULL,+ smtp_tls INTEGER NOT NULL DEFAULT 1,++ poll_interval_seconds INTEGER NOT NULL DEFAULT 60,+ last_synced_uid TEXT NOT NULL DEFAULT '0',+ last_synced_at TEXT,+ status TEXT NOT NULL DEFAULT 'active',+ error_message TEXT NOT NULL DEFAULT '',++ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),+ FOREIGN KEY (agent_id, workspace_id) REFERENCES agent(id, workspace_id) ON DELETE CASCADE+);++CREATE INDEX IF NOT EXISTS idx_email_account_agent_ws ON agent_email_account(agent_id, workspace_id);+CREATE UNIQUE INDEX IF NOT EXISTS email_account_agent_email ON agent_email_account(agent_id, email_address);diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsxindex 33318592b..c97949c50 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx@@ -4,15 +4,15 @@ import { useEffect, useState, useCallback } from "react";import { useParams } from "next/navigation";import { useWorkspace } from "@/contexts/workspace-context";import { useAgentContext } from "@/contexts/agent-context";-import { listEmails, getEmailBody, getEmailThread, deleteEmail, sendEmail } from "@/lib/api";-import type { Email, EmailAttachment } from "@alook/shared";+import { listEmails, getEmailBody, getEmailThread, deleteEmail, sendEmail, listEmailAccounts } from "@/lib/api";+import type { Email, EmailAttachment, AgentEmailAccount } from "@alook/shared";import { Button } from "@/components/ui/button";import { ConfirmDialog } from "@/components/ui/confirm-dialog";import { EmailCompose } from "@/components/email-compose";import { cn } from "@/lib/utils";import { toast } from "sonner";import { Skeleton } from "@/components/ui/skeleton";-import { ArrowLeft, Loader2, Mail, Inbox, Send, Plus, Trash2, Forward, Reply, Paperclip, File as FileIcon, Copy, Check, ShieldX } from "lucide-react";+import { ArrowLeft, Loader2, Mail, Inbox, Send, Plus, Trash2, Forward, Reply, Paperclip, File as FileIcon, Copy, Check, ShieldX, ChevronDown } from "lucide-react";import { useIsMobile } from "@/hooks/use-mobile";import { ResizablePanels } from "@/components/ui/resizable-panels";import { EmailBodyFrame } from "@/components/email-body-frame";@@ -62,6 +62,20 @@ export default function AgentEmailPage() {const [deleteTarget, setDeleteTarget] = useState<string | null>(null);const [deleting, setDeleting] = useState(false);+ const [emailAccounts, setEmailAccounts] = useState<AgentEmailAccount[]>([]);+ const [mailboxOpen, setMailboxOpen] = useState(false);++ type Mailbox = { type: "alook"; address: string } | { type: "custom"; address: string; accountId: string };+ const alookAddress = agent?.email_handle ? `${agent.email_handle}@alook.ai` : "";+ const mailboxes: Mailbox[] = [+ ...(alookAddress ? [{ type: "alook" as const, address: alookAddress }] : []),+ ...emailAccounts.map((a) => ({ type: "custom" as const, address: a.email_address, accountId: a.id })),+ ];+ const [activeMailboxIdx, setActiveMailboxIdx] = useState(0);+ const activeMailbox = mailboxes[activeMailboxIdx] ?? mailboxes[0] ?? null;+ const activeAddress = activeMailbox?.address ?? "";+ const activeAccountId = activeMailbox?.type === "custom" ? activeMailbox.accountId : undefined;+const selected = emails.find((e) => e.id === selectedId) ?? null;const loadEmails = useCallback(async (dir: string) => {@@ -76,6 +90,10 @@ export default function AgentEmailPage() {}}, [agentId, workspaceId]);+ useEffect(() => {+ listEmailAccounts(agentId, workspaceId).then(setEmailAccounts).catch(() => {});+ }, [agentId, workspaceId]);+useEffect(() => {setSelectedId(null);setBody(null);@@ -151,7 +169,7 @@ export default function AgentEmailPage() {const handleSend = async (to: string, subject: string, htmlBody: string, attachments: EmailAttachment[], threading?: { inReplyTo?: string; references?: string }): Promise<boolean> => {try {- await sendEmail(agentId, to, subject, htmlBody, workspaceId, attachments.length > 0 ? attachments : undefined, threading);+ await sendEmail(agentId, to, subject, htmlBody, workspaceId, attachments.length > 0 ? attachments : undefined, threading, activeAccountId);toast.success("Email sent");setComposing(false);setFolder("sent");@@ -203,13 +221,12 @@ export default function AgentEmailPage() {setComposing(true);};- const fromAddress = agent?.email_handle ? `${agent.email_handle}@alook.ai` : "";const [copied, setCopied] = useState(false);const handleCopyAddress = async () => {- if (!fromAddress) return;+ if (!activeAddress) return;try {- await navigator.clipboard.writeText(fromAddress);+ await navigator.clipboard.writeText(activeAddress);setCopied(true);setTimeout(() => setCopied(false), 1500);} catch {@@ -219,23 +236,73 @@ export default function AgentEmailPage() {const sidebarContent = (<div className="flex h-full flex-col">- {fromAddress ? (- <button- type="button"- onClick={handleCopyAddress}- className="group flex items-center gap-1.5 px-3 pt-3 pb-1 text-left cursor-pointer"- title="Click to copy"- >- <span className="text-xs text-muted-foreground truncate">{fromAddress}</span>- {copied ? (- <Check className="size-2.5 text-green-500 shrink-0" />+ {mailboxes.length > 0 ? (+ <div className="px-3 pt-3 pb-1 relative">+ {mailboxes.length === 1 ? (+ <button+ type="button"+ onClick={handleCopyAddress}+ className="group flex items-center gap-1.5 text-left cursor-pointer w-full"+ title="Click to copy"+ >+ <span className="text-xs text-muted-foreground truncate">{activeAddress}</span>+ {copied ? (+ <Check className="size-2.5 text-green-500 shrink-0" />+ ) : (+ <Copy className="size-2.5 text-muted-foreground/0 group-hover:text-muted-foreground/60 shrink-0 transition-colors" />+ )}+ </button>) : (- <Copy className="size-2.5 text-muted-foreground/0 group-hover:text-muted-foreground/60 shrink-0 transition-colors" />+ <>+ <div className="flex items-center gap-1 w-full">+ <button+ type="button"+ onClick={() => setMailboxOpen(!mailboxOpen)}+ className="flex items-center gap-1 text-left cursor-pointer min-w-0 flex-1"+ >+ <span className="text-xs text-muted-foreground truncate">{activeAddress}</span>+ <ChevronDown className="size-2.5 text-muted-foreground shrink-0" />+ </button>+ <button+ type="button"+ onClick={handleCopyAddress}+ className="shrink-0 p-0.5"+ title="Copy address"+ >+ {copied ? (+ <Check className="size-2.5 text-green-500" />+ ) : (+ <Copy className="size-2.5 text-muted-foreground/40 hover:text-muted-foreground/80 transition-colors" />+ )}+ </button>+ </div>+ {mailboxOpen && (+ <div className="absolute left-2 right-2 top-full mt-0.5 z-10 rounded-lg border border-border bg-popover shadow-md py-1">+ {mailboxes.map((mb, i) => (+ <button+ key={mb.address}+ type="button"+ onClick={() => { setActiveMailboxIdx(i); setMailboxOpen(false); }}+ className={cn(+ "flex items-center gap-2 w-full px-2.5 py-1.5 text-left text-xs transition-colors",+ i === activeMailboxIdx ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50"+ )}+ >+ <Mail className="size-3 shrink-0" />+ <span className="truncate">{mb.address}</span>+ {mb.type === "custom" && (+ <span className="text-[9px] text-muted-foreground/60 shrink-0">IMAP</span>+ )}+ </button>+ ))}+ </div>+ )}+ </>)}- </button>+ </div>) : (<div className="px-3 pt-3 pb-1">- <p className="text-xs text-muted-foreground/60">No email handle configured</p>+ <p className="text-xs text-muted-foreground/60">No email configured</p></div>)}<div className="p-2">@@ -243,8 +310,8 @@ export default function AgentEmailPage() {size="sm"className="w-full justify-start text-xs h-8 gap-1.5"onClick={() => { setComposeInitial({}); setComposing(true); setSelectedId(null); }}- disabled={!agent?.email_handle}- title={!agent?.email_handle ? "Configure an email handle in agent settings to send emails" : "Compose new email"}+ disabled={mailboxes.length === 0}+ title={mailboxes.length === 0 ? "Configure an email in agent settings to send emails" : "Compose new email"}><Plus className="size-3.5" />New Email@@ -351,7 +418,7 @@ export default function AgentEmailPage() {{composing ? (<EmailComposekey={JSON.stringify(composeInitial)}- fromAddress={fromAddress}+ fromAddress={activeAddress}onSend={handleSend}onDiscard={() => { setComposing(false); setComposeInitial({}); }}initialTo={composeInitial.to}@@ -578,7 +645,7 @@ export default function AgentEmailPage() {size="icon-sm"variant="ghost"onClick={() => { setComposeInitial({}); setComposing(true); setSelectedId(null); }}- disabled={!agent?.email_handle}+ disabled={mailboxes.length === 0}><Plus className="size-4" /></Button>diff --git a/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/new/page.tsxindex dff4cdb19..45d051e88 100644--- a/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx@@ -5,12 +5,13 @@ import { useRouter } from "next/navigation";import { useAgentContext } from "@/contexts/agent-context";import { useWorkspace } from "@/contexts/workspace-context";import { AgentEditForm } from "@/components/agent-edit-form";-import { fetchModelOptions } from "@/lib/api";+import { fetchModelOptions, createEmailAccount } from "@/lib/api";+import { toast } from "sonner";import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";export default function CreateAgentPage() {const router = useRouter();- const { slug } = useWorkspace();+ const { slug, workspaceId } = useWorkspace();const {runtimes,handleCreateAgent,@@ -51,6 +52,14 @@ export default function CreateAgentPage() {runtime_config: data.runtime_config,});if (agent) {+ if (data.custom_email) {+ try {+ await createEmailAccount(agent.id, data.custom_email, workspaceId);+ toast.success("Custom email connected");+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Failed to connect custom email");+ }+ }router.push(`/w/${slug}/agents/${agent.id}/chat`);}return !!agent;diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.tsnew file mode 100644index 000000000..c64871f6f--- /dev/null+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts@@ -0,0 +1,107 @@+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { createDb, queries, UpdateEmailAccountSchema, DEV_EMAIL_WORKER_URL } from "@alook/shared"+import { encrypt } from "@alook/shared/crypto"+import { withAuth } from "@/lib/middleware/auth"+import { withWorkspaceMember } from "@/lib/middleware/workspace"+import { writeJSON, writeError, parseBody, formatTimestamp, formatTimestampNullable } from "@/lib/middleware/helpers"++function accountToResponse(a: any) {+ return {+ id: a.id,+ agent_id: a.agentId,+ workspace_id: a.workspaceId,+ email_address: a.emailAddress,+ display_name: a.displayName,+ imap_host: a.imapHost,+ imap_port: a.imapPort,+ imap_tls: !!a.imapTls,+ smtp_host: a.smtpHost,+ smtp_port: a.smtpPort,+ smtp_tls: a.smtpTls,+ poll_interval_seconds: a.pollIntervalSeconds,+ last_synced_at: formatTimestampNullable(a.lastSyncedAt),+ status: a.status,+ error_message: a.errorMessage,+ created_at: formatTimestamp(a.createdAt),+ updated_at: formatTimestamp(a.updatedAt),+ }+}++async function callEmailWorker(cfEnv: Env, path: string, method = "POST") {+ try {+ await cfEnv.EMAIL_WORKER.fetch(`http://internal${path}`, { method })+ } catch {+ await fetch(`${DEV_EMAIL_WORKER_URL}${path}`, { method }).catch(() => {})+ }+}++export const PATCH = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx)+ if (ws instanceof Response) return ws++ const { env } = getCloudflareContext()+ const cfEnv = env as Env+ const db = createDb(cfEnv.DB)++ const agentId = ctx.params?.id+ const accountId = ctx.params?.accountId+ if (!agentId || !accountId) return writeError("missing params", 400)++ const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)+ if (!existing) return writeError("not found", 404)++ const [body, err] = await parseBody(req, UpdateEmailAccountSchema)+ if (err) return err++ const secret = cfEnv.ENCRYPTION_KEY+ if (!secret) return writeError("encryption not configured", 500)++ const data: Record<string, unknown> = {}+ if (body.emailAddress !== undefined) data.emailAddress = body.emailAddress+ if (body.displayName !== undefined) data.displayName = body.displayName+ if (body.imapHost !== undefined) data.imapHost = body.imapHost+ if (body.imapPort !== undefined) data.imapPort = body.imapPort+ if (body.imapUsername !== undefined) data.imapUsername = encrypt(body.imapUsername, secret)+ if (body.imapPassword !== undefined) data.imapPassword = encrypt(body.imapPassword, secret)+ if (body.imapTls !== undefined) data.imapTls = body.imapTls+ if (body.smtpHost !== undefined) data.smtpHost = body.smtpHost+ if (body.smtpPort !== undefined) data.smtpPort = body.smtpPort+ if (body.smtpUsername !== undefined) data.smtpUsername = encrypt(body.smtpUsername, secret)+ if (body.smtpPassword !== undefined) data.smtpPassword = encrypt(body.smtpPassword, secret)+ if (body.smtpTls !== undefined) data.smtpTls = body.smtpTls+ if (body.pollIntervalSeconds !== undefined) data.pollIntervalSeconds = body.pollIntervalSeconds++ const updated = await queries.emailAccount.updateEmailAccount(db, accountId, ws.workspaceId, data as any)+ if (!updated) return writeError("update failed", 500)++ const hasCredentialChange = body.imapUsername || body.imapPassword || body.smtpUsername || body.smtpPassword || body.imapHost || body.smtpHost+ if (hasCredentialChange) {+ await callEmailWorker(cfEnv, `/imap/stop?accountId=${accountId}`)+ await callEmailWorker(cfEnv, `/imap/start?accountId=${accountId}`)+ }++ return writeJSON(accountToResponse(updated))+})++export const DELETE = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx)+ if (ws instanceof Response) return ws++ const { env } = getCloudflareContext()+ const cfEnv = env as Env+ const db = createDb(cfEnv.DB)++ const agentId = ctx.params?.id+ const accountId = ctx.params?.accountId+ if (!agentId || !accountId) return writeError("missing params", 400)++ const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)+ if (!existing) return writeError("not found", 404)++ await callEmailWorker(cfEnv, `/imap/stop?accountId=${accountId}`)++ const deleted = await queries.emailAccount.deleteEmailAccount(db, accountId, ws.workspaceId)+ if (!deleted) return writeError("delete failed", 500)++ return writeJSON({ ok: true })+})diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.tsnew file mode 100644index 000000000..5a73a899f--- /dev/null+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts@@ -0,0 +1,33 @@+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { createDb, queries, DEV_EMAIL_WORKER_URL } from "@alook/shared"+import { withAuth } from "@/lib/middleware/auth"+import { withWorkspaceMember } from "@/lib/middleware/workspace"+import { writeJSON, writeError } from "@/lib/middleware/helpers"++export const POST = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx)+ if (ws instanceof Response) return ws++ const { env } = getCloudflareContext()+ const cfEnv = env as Env+ const db = createDb(cfEnv.DB)++ const agentId = ctx.params?.id+ const accountId = ctx.params?.accountId+ if (!agentId || !accountId) return writeError("missing params", 400)++ const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)+ if (!existing) return writeError("not found", 404)++ try {+ await cfEnv.EMAIL_WORKER.fetch(`http://internal/imap/sync?accountId=${accountId}`, {+ method: "POST",+ })+ } catch {+ await fetch(`${DEV_EMAIL_WORKER_URL}/imap/sync?accountId=${accountId}`, {+ method: "POST",+ }).catch(() => {})+ }++ return writeJSON({ ok: true })+})diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.tsnew file mode 100644index 000000000..548b5e804--- /dev/null+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.ts@@ -0,0 +1,35 @@+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { createDb, queries, DEV_EMAIL_WORKER_URL } from "@alook/shared"+import { withAuth } from "@/lib/middleware/auth"+import { withWorkspaceMember } from "@/lib/middleware/workspace"+import { writeJSON, writeError } from "@/lib/middleware/helpers"++export const POST = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx)+ if (ws instanceof Response) return ws++ const { env } = getCloudflareContext()+ const cfEnv = env as Env+ const db = createDb(cfEnv.DB)++ const agentId = ctx.params?.id+ const accountId = ctx.params?.accountId+ if (!agentId || !accountId) return writeError("missing params", 400)++ const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)+ if (!existing) return writeError("not found", 404)++ let testRes: Response+ try {+ testRes = await cfEnv.EMAIL_WORKER.fetch(`http://internal/imap/test?accountId=${accountId}`, {+ method: "POST",+ })+ } catch {+ testRes = await fetch(`${DEV_EMAIL_WORKER_URL}/imap/test?accountId=${accountId}`, {+ method: "POST",+ })+ }++ const result = await testRes.json()+ return writeJSON(result, testRes.status)+})diff --git a/src/web/src/app/api/agents/[id]/email-accounts/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/route.tsnew file mode 100644index 000000000..fa20b8715--- /dev/null+++ b/src/web/src/app/api/agents/[id]/email-accounts/route.ts@@ -0,0 +1,96 @@+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { createDb, queries, CreateEmailAccountSchema, DEV_EMAIL_WORKER_URL } from "@alook/shared"+import { encrypt } from "@alook/shared/crypto"+import { withAuth } from "@/lib/middleware/auth"+import { withWorkspaceMember } from "@/lib/middleware/workspace"+import { writeJSON, writeError, parseBody, formatTimestamp, formatTimestampNullable } from "@/lib/middleware/helpers"++function accountToResponse(a: any) {+ return {+ id: a.id,+ agent_id: a.agentId,+ workspace_id: a.workspaceId,+ email_address: a.emailAddress,+ display_name: a.displayName,+ imap_host: a.imapHost,+ imap_port: a.imapPort,+ imap_tls: !!a.imapTls,+ smtp_host: a.smtpHost,+ smtp_port: a.smtpPort,+ smtp_tls: a.smtpTls,+ poll_interval_seconds: a.pollIntervalSeconds,+ last_synced_at: formatTimestampNullable(a.lastSyncedAt),+ status: a.status,+ error_message: a.errorMessage,+ created_at: formatTimestamp(a.createdAt),+ updated_at: formatTimestamp(a.updatedAt),+ }+}++export const GET = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx)+ if (ws instanceof Response) return ws++ const { env } = getCloudflareContext()+ const db = createDb((env as Env).DB)++ const agentId = ctx.params?.id+ if (!agentId) return writeError("agent id is required", 400)++ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId)+ if (!agent) return writeError("agent not found", 404)++ const accounts = await queries.emailAccount.getEmailAccountsByAgent(db, agentId, ws.workspaceId)+ return writeJSON(accounts.map(accountToResponse))+})++export const POST = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx)+ if (ws instanceof Response) return ws++ const { env } = getCloudflareContext()+ const cfEnv = env as Env+ const db = createDb(cfEnv.DB)++ const agentId = ctx.params?.id+ if (!agentId) return writeError("agent id is required", 400)++ const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId)+ if (!agent) return writeError("agent not found", 404)++ const [body, err] = await parseBody(req, CreateEmailAccountSchema)+ if (err) return err++ const secret = cfEnv.ENCRYPTION_KEY+ if (!secret) return writeError("encryption not configured", 500)++ const account = await queries.emailAccount.createEmailAccount(db, {+ agentId,+ workspaceId: ws.workspaceId,+ emailAddress: body.emailAddress,+ displayName: body.displayName,+ imapHost: body.imapHost,+ imapPort: body.imapPort,+ imapUsername: encrypt(body.imapUsername, secret),+ imapPassword: encrypt(body.imapPassword, secret),+ imapTls: body.imapTls,+ smtpHost: body.smtpHost,+ smtpPort: body.smtpPort,+ smtpUsername: encrypt(body.smtpUsername, secret),+ smtpPassword: encrypt(body.smtpPassword, secret),+ smtpTls: body.smtpTls,+ pollIntervalSeconds: body.pollIntervalSeconds,+ })++ try {+ await cfEnv.EMAIL_WORKER.fetch(`http://internal/imap/start?accountId=${account.id}`, {+ method: "POST",+ })+ } catch {+ await fetch(`${DEV_EMAIL_WORKER_URL}/imap/start?accountId=${account.id}`, {+ method: "POST",+ }).catch(() => {})+ }++ return writeJSON(accountToResponse(account), 201)+})diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.tsindex 1e4ef85dd..4e5dbe36a 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts@@ -31,6 +31,9 @@ vi.mock("@alook/shared", async () => {agent: {getAgent: (...args: unknown[]) => mockGetAgent(...args),},+ emailAccount: {+ getEmailAccountsByAgent: vi.fn().mockResolvedValue([]),+ },},};});@@ -168,6 +171,7 @@ describe("POST /api/daemon/tasks/poll", () => {name: "Bot",runtime_config: { model: "gpt-4" },email_handle: null,+ email_addresses: [],user_email: "[email protected]",});});diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex 8de6ba6c9..58cf925d1 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -77,6 +77,14 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const tasks = [];for (const task of claimed) {const agent = await queries.agent.getAgent(db, task.agentId, task.workspaceId);+ let emailAddresses: string[] = [];+ if (agent) {+ if (agent.emailHandle) emailAddresses.push(`${agent.emailHandle}@alook.ai`);+ const customAccounts = await queries.emailAccount.getEmailAccountsByAgent(db, agent.id, task.workspaceId);+ for (const acc of customAccounts) {+ emailAddresses.push(acc.emailAddress);+ }+ }tasks.push({...taskToResponse(task),agent: agent@@ -85,6 +93,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {name: agent.name,runtime_config: agent.runtimeConfig || {},email_handle: agent.emailHandle || null,+ email_addresses: emailAddresses,user_email: ctx.email || null,}: null,diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsindex 14cdfb071..7d95de20c 100644--- a/src/web/src/app/api/email/send/route.ts+++ b/src/web/src/app/api/email/send/route.ts@@ -20,8 +20,33 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const agent = await queries.agent.getAgent(db, body.agentId, ws.workspaceId);if (!agent) return writeError("agent not found in workspace", 404);- if (!agent.emailHandle) {- return writeError("agent has no email handle configured", 400);+ let customAccountId = body.customAccountId;+ let fromAddress: string;++ if (body.from && !customAccountId) {+ const alookAddr = agent.emailHandle ? `${agent.emailHandle}@alook.ai` : null;+ if (body.from === alookAddr) {+ fromAddress = alookAddr;+ } else {+ const accounts = await queries.emailAccount.getEmailAccountsByAgent(db, body.agentId, ws.workspaceId);+ const match = accounts.find((a) => a.emailAddress === body.from);+ if (!match) {+ return writeError(`email address '${body.from}' is not configured for this agent`, 400);+ }+ customAccountId = match.id;+ fromAddress = match.emailAddress;+ }+ } else if (customAccountId) {+ const account = await queries.emailAccount.getEmailAccountScoped(db, customAccountId, body.agentId, ws.workspaceId);+ if (!account) {+ return writeError("custom email account not found", 404);+ }+ fromAddress = account.emailAddress;+ } else {+ if (!agent.emailHandle) {+ return writeError("agent has no email handle configured", 400);+ }+ fromAddress = `${agent.emailHandle}@alook.ai`;}const attachments = body.attachments ?? [];@@ -35,6 +60,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {htmlBody: body.htmlBody || "",inReplyTo: body.inReplyTo || "",references: body.references || "",+ customAccountId: customAccountId || undefined,attachmentKeys: attachments.length > 0? attachments.map((a) => ({ key: a.key, filename: a.filename, contentType: a.contentType })): undefined,@@ -64,7 +90,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const emailResult = await emailRes.json() as { ok: boolean; r2Key: string; messageId?: string };// Create DB record- const fromAddress = `${agent.emailHandle}@alook.ai`;const email = await queries.email.createEmail(db, {agentId: body.agentId,workspaceId: ws.workspaceId,diff --git a/src/web/src/components/agent-edit-form.tsx b/src/web/src/components/agent-edit-form.tsxindex 1d1db0f55..b80e70527 100644--- a/src/web/src/components/agent-edit-form.tsx+++ b/src/web/src/components/agent-edit-form.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect } from "react";+import { useState, useEffect, useRef } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -19,6 +19,7 @@ import type { AgentRuntime as Runtime } from "@alook/shared";import { cn } from "@/lib/utils";import { LockIcon, XIcon, ChevronRightIcon } from "lucide-react";import { useWorkspace } from "@/contexts/workspace-context";+import { CustomEmailForm, type CustomEmailData } from "@/components/custom-email-form";import {listWhitelist,addWhitelistEmail,@@ -46,6 +47,7 @@ interface AgentEditFormProps {runtime_id: string;email_handle?: string;runtime_config?: Record<string, unknown>;+ custom_email?: CustomEmailData;}) => Promise<boolean>;onCancel: () => void;saving: boolean;@@ -64,6 +66,7 @@ export function AgentEditForm({submitLabel = "Save",savingLabel = "Saving...",}: AgentEditFormProps) {+ const { workspaceId } = useWorkspace();const [name, setName] = useState(agent?.name ?? "");const [description, setDescription] = useState(agent?.description ?? "");const [instructions, setInstructions] = useState(agent?.instructions ?? "");@@ -71,6 +74,8 @@ export function AgentEditForm({agent?.runtime_id ?? defaultRuntimeId);const [emailHandle, setEmailHandle] = useState(agent?.email_handle ?? "");+ const [customEmailData, setCustomEmailData] = useState<CustomEmailData | null>(null);+ const customEmailGetDataRef = useRef<(() => CustomEmailData | null) | null>(null);const [model, setModel] = useState(() => {const rc = agent?.runtime_config;@@ -99,6 +104,7 @@ export function AgentEditForm({runtime_id: runtimeId,email_handle: emailHandle || derivedHandle || undefined,runtime_config: model ? { model } : {},+ custom_email: customEmailGetDataRef.current?.() ?? customEmailData ?? undefined,});};@@ -155,6 +161,14 @@ export function AgentEditForm({</div>)}+ {!agent && (+ <CustomEmailForm+ workspaceId={workspaceId}+ onDataChange={setCustomEmailData}+ getDataRef={customEmailGetDataRef}+ />+ )}+<div className="space-y-1.5"><Label htmlFor="agent-instructions">Instructions</Label><Textarea@@ -222,6 +236,13 @@ export function AgentEditForm({</div>)}+ {agent && (+ <CustomEmailForm+ agentId={agent.id}+ workspaceId={workspaceId}+ />+ )}+<div className="flex items-center gap-2 pt-2"><Buttontype="button"diff --git a/src/web/src/components/custom-email-form.tsx b/src/web/src/components/custom-email-form.tsxnew file mode 100644index 000000000..2f0a406be--- /dev/null+++ b/src/web/src/components/custom-email-form.tsx@@ -0,0 +1,352 @@+"use client";++import { useState, useEffect, useCallback } from "react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Sheet,+ SheetTrigger,+ SheetContent,+ SheetTitle,+ SheetBody,+} from "@/components/ui/sheet";+import { cn } from "@/lib/utils";+import {+ listEmailAccounts,+ createEmailAccount,+ deleteEmailAccount,+ syncEmailAccount,+} from "@/lib/api";+import type { AgentEmailAccount, CreateEmailAccountRequest } from "@alook/shared";+import {+ Loader2, Mail, RefreshCw, Trash2, AlertCircle, CheckCircle2,+ ChevronRight, XIcon,+} from "lucide-react";+import { toast } from "sonner";++const PRESETS: Record<string, { imapHost: string; imapPort: number; smtpHost: string; smtpPort: number }> = {+ Gmail: { imapHost: "imap.gmail.com", imapPort: 993, smtpHost: "smtp.gmail.com", smtpPort: 587 },+ Outlook: { imapHost: "outlook.office365.com", imapPort: 993, smtpHost: "smtp.office365.com", smtpPort: 587 },+ Yahoo: { imapHost: "imap.mail.yahoo.com", imapPort: 993, smtpHost: "smtp.mail.yahoo.com", smtpPort: 587 },+};++export type CustomEmailData = CreateEmailAccountRequest;++interface Props {+ agentId?: string;+ workspaceId: string;+ onDataChange?: (data: CustomEmailData | null) => void;+ getDataRef?: React.MutableRefObject<(() => CustomEmailData | null) | null>;+}++function useEmailFields() {+ const [emailAddress, setEmailAddress] = useState("");+ const [displayName, setDisplayName] = useState("");+ const [imapHost, setImapHost] = useState("");+ const [imapPort, setImapPort] = useState(993);+ const [imapUsername, setImapUsername] = useState("");+ const [imapPassword, setImapPassword] = useState("");+ const [smtpHost, setSmtpHost] = useState("");+ const [smtpPort, setSmtpPort] = useState(587);+ const [smtpUsername, setSmtpUsername] = useState("");+ const [smtpPassword, setSmtpPassword] = useState("");++ function applyPreset(name: string) {+ const preset = PRESETS[name];+ if (!preset) return;+ setImapHost(preset.imapHost);+ setImapPort(preset.imapPort);+ setSmtpHost(preset.smtpHost);+ setSmtpPort(preset.smtpPort);+ }++ const effectiveImapUsername = imapUsername || emailAddress;+ const effectiveSmtpUsername = smtpUsername || emailAddress;++ function buildData(): CustomEmailData | null {+ if (!emailAddress || !imapHost || !effectiveImapUsername || !imapPassword || !smtpHost || !effectiveSmtpUsername || !smtpPassword) {+ return null;+ }+ return {+ emailAddress, displayName, imapHost, imapPort,+ imapUsername: effectiveImapUsername, imapPassword,+ imapTls: true, smtpHost, smtpPort,+ smtpUsername: effectiveSmtpUsername, smtpPassword,+ smtpTls: 1, pollIntervalSeconds: 60,+ };+ }++ const fields = {+ emailAddress, setEmailAddress, displayName, setDisplayName,+ imapHost, setImapHost, imapPort, setImapPort,+ imapUsername, setImapUsername, imapPassword, setImapPassword,+ smtpHost, setSmtpHost, smtpPort, setSmtpPort,+ smtpUsername, setSmtpUsername, smtpPassword, setSmtpPassword,+ };++ return { fields, applyPreset, buildData };+}++function EmailFieldsForm({ fields, applyPreset }: {+ fields: ReturnType<typeof useEmailFields>["fields"];+ applyPreset: (name: string) => void;+}) {+ return (+ <>+ <div className="flex gap-1.5">+ {Object.keys(PRESETS).map((name) => (+ <Button key={name} type="button" variant="outline" size="sm" className="h-6 text-[10px] px-2"+ onClick={() => applyPreset(name)}>+ {name}+ </Button>+ ))}+ </div>++ <div className="grid gap-3">+ <div>+ <Label className="text-xs">Email Address *</Label>+ <Input placeholder="[email protected]" value={fields.emailAddress}+ onChange={(e) => fields.setEmailAddress(e.target.value)} className="h-8 text-sm" />+ </div>+ <div>+ <Label className="text-xs">Display Name</Label>+ <Input placeholder="My Agent" value={fields.displayName}+ onChange={(e) => fields.setDisplayName(e.target.value)} className="h-8 text-sm" />+ </div>+ </div>++ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-2">+ <Label className="text-xs font-medium">IMAP (Receive)</Label>+ <Input placeholder="imap.gmail.com" value={fields.imapHost}+ onChange={(e) => fields.setImapHost(e.target.value)} className="h-8 text-sm" />+ <Input type="number" placeholder="993" value={fields.imapPort}+ onChange={(e) => fields.setImapPort(Number(e.target.value))} className="h-8 text-sm" />+ <Input placeholder={fields.emailAddress || "Username (defaults to email)"} value={fields.imapUsername}+ onChange={(e) => fields.setImapUsername(e.target.value)} className="h-8 text-sm" />+ <Input type="password" placeholder="App Password" value={fields.imapPassword}+ onChange={(e) => fields.setImapPassword(e.target.value)} className="h-8 text-sm" />+ </div>+ <div className="space-y-2">+ <Label className="text-xs font-medium">SMTP (Send)</Label>+ <Input placeholder="smtp.gmail.com" value={fields.smtpHost}+ onChange={(e) => fields.setSmtpHost(e.target.value)} className="h-8 text-sm" />+ <Input type="number" placeholder="587" value={fields.smtpPort}+ onChange={(e) => fields.setSmtpPort(Number(e.target.value))} className="h-8 text-sm" />+ <Input placeholder={fields.emailAddress || "Username (defaults to email)"} value={fields.smtpUsername}+ onChange={(e) => fields.setSmtpUsername(e.target.value)} className="h-8 text-sm" />+ <Input type="password" placeholder="App Password" value={fields.smtpPassword}+ onChange={(e) => fields.setSmtpPassword(e.target.value)} className="h-8 text-sm" />+ </div>+ </div>+ </>+ );+}++export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef }: Props) {+ const isCreateMode = !agentId;+ const [open, setOpen] = useState(false);+ const [accounts, setAccounts] = useState<AgentEmailAccount[]>([]);+ const [loading, setLoading] = useState(!isCreateMode);+ const [saving, setSaving] = useState(false);+ const [syncing, setSyncing] = useState(false);+ const [deleting, setDeleting] = useState(false);++ const { fields, applyPreset, buildData } = useEmailFields();++ useEffect(() => {+ if (getDataRef) getDataRef.current = buildData;+ });++ useEffect(() => {+ if (!isCreateMode) return;+ onDataChange?.(buildData());+ }, [+ isCreateMode,+ fields.emailAddress, fields.displayName,+ fields.imapHost, fields.imapPort, fields.imapUsername, fields.imapPassword,+ fields.smtpHost, fields.smtpPort, fields.smtpUsername, fields.smtpPassword,+ ]);++ const load = useCallback(async () => {+ if (isCreateMode) return;+ try {+ const list = await listEmailAccounts(agentId!, workspaceId);+ setAccounts(list);+ } catch {+ // silent+ } finally {+ setLoading(false);+ }+ }, [agentId, workspaceId, isCreateMode]);++ useEffect(() => { load(); }, [load]);++ const existing = accounts[0] ?? null;++ async function handleCreate() {+ const data = buildData();+ if (!data) {+ toast.error("Please fill in all required fields");+ return;+ }+ if (!agentId) return;+ setSaving(true);+ try {+ await createEmailAccount(agentId, data, workspaceId);+ toast.success("Custom email configured");+ setOpen(false);+ await load();+ } catch (err: any) {+ toast.error(err?.message ?? "Failed to save");+ } finally {+ setSaving(false);+ }+ }++ async function handleDelete() {+ if (!existing || !agentId) return;+ setDeleting(true);+ try {+ await deleteEmailAccount(agentId, existing.id, workspaceId);+ toast.success("Custom email removed");+ setAccounts([]);+ } catch (err: any) {+ toast.error(err?.message ?? "Failed to remove");+ } finally {+ setDeleting(false);+ }+ }++ async function handleSync() {+ if (!existing || !agentId) return;+ setSyncing(true);+ try {+ await syncEmailAccount(agentId, existing.id, workspaceId);+ toast.success("Sync triggered");+ setTimeout(() => load(), 2000);+ } catch (err: any) {+ toast.error(err?.message ?? "Sync failed");+ } finally {+ setSyncing(false);+ }+ }++ const triggerDesc = isCreateMode+ ? (fields.emailAddress+ ? fields.emailAddress+ : "Connect your own mailbox via IMAP/SMTP")+ : loading+ ? "Loading..."+ : existing+ ? existing.email_address+ : "Connect your own mailbox via IMAP/SMTP";++ return (+ <Sheet open={open} onOpenChange={setOpen}>+ <SheetTrigger+ render={+ <button+ type="button"+ className="flex w-full items-center justify-between rounded-lg border border-border/50 bg-muted/30 px-4 py-3 text-left transition-colors hover:bg-muted/50"+ />+ }+ >+ <div>+ <span className="text-sm font-medium">Custom Email</span>+ <p className="text-xs text-muted-foreground">{triggerDesc}</p>+ </div>+ {!isCreateMode && existing ? (+ <span className={cn(+ "inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full font-medium shrink-0",+ existing.status === "active" ? "bg-green-500/10 text-green-600" :+ existing.status === "error" ? "bg-red-500/10 text-red-600" :+ "bg-yellow-500/10 text-yellow-600"+ )}>+ {existing.status === "active" ? <CheckCircle2 className="size-2.5" /> :+ existing.status === "error" ? <AlertCircle className="size-2.5" /> : null}+ {existing.status}+ </span>+ ) : (+ <ChevronRight className="size-4 text-muted-foreground shrink-0" />+ )}+ </SheetTrigger>+ <SheetContent+ side="right"+ className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border"+ >+ <SheetTitle className="sr-only">Custom Email</SheetTitle>+ <SheetBody className="px-8 pt-10 pb-6">+ <div className="space-y-4">+ <div>+ <h2 className="font-heading text-lg font-semibold">Custom Email</h2>+ <p className="text-sm text-muted-foreground mt-1">+ Connect your own mailbox to send and receive email as your identity.+ </p>+ </div>++ {!isCreateMode && existing ? (+ <div className="space-y-4">+ <div className="flex items-center justify-between rounded-md border border-border/50 px-3 py-2.5">+ <div className="flex items-center gap-2 min-w-0">+ <Mail className="size-3.5 text-muted-foreground shrink-0" />+ <span className="text-sm truncate">{existing.email_address}</span>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button+ type="button"+ onClick={handleSync}+ disabled={syncing}+ title="Sync now"+ className="rounded-full p-1 text-muted-foreground hover:bg-muted transition-colors"+ >+ <RefreshCw className={cn("size-3.5", syncing && "animate-spin")} />+ </button>+ <button+ type="button"+ onClick={handleDelete}+ disabled={deleting}+ title="Remove"+ className="rounded-full p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"+ >+ {deleting ? <Loader2 className="size-3.5 animate-spin" /> : <XIcon className="size-3.5" />}+ </button>+ </div>+ </div>+ {existing.error_message && (+ <p className="text-xs text-destructive">{existing.error_message}</p>+ )}+ {existing.last_synced_at && (+ <p className="text-xs text-muted-foreground">+ Last synced: {new Date(existing.last_synced_at).toLocaleString()}+ </p>+ )}+ <div className="rounded-md border border-border/50 px-3 py-2 text-xs text-muted-foreground space-y-1">+ <div className="flex justify-between"><span>IMAP</span><span>{existing.imap_host}:{existing.imap_port}</span></div>+ <div className="flex justify-between"><span>SMTP</span><span>{existing.smtp_host}:{existing.smtp_port}</span></div>+ <div className="flex justify-between"><span>Poll interval</span><span>{existing.poll_interval_seconds}s</span></div>+ </div>+ </div>+ ) : (+ <div className="space-y-4">+ <EmailFieldsForm fields={fields} applyPreset={applyPreset} />+ {!isCreateMode && (+ <Button type="button" size="sm" className="w-full" onClick={handleCreate} disabled={saving}>+ {saving && <Loader2 className="size-3 animate-spin mr-1" />}+ Save & Connect+ </Button>+ )}+ {isCreateMode && (+ <p className="text-xs text-muted-foreground">+ Will be connected after creating the agent.+ </p>+ )}+ </div>+ )}+ </div>+ </SheetBody>+ </SheetContent>+ </Sheet>+ );+}diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex 9208f2c21..ed552dbc5 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -13,6 +13,7 @@ declare namespace Cloudflare {GOOGLE_CLIENT_SECRET: stringBETTER_AUTH_SECRET: stringBETTER_AUTH_URL: string+ ENCRYPTION_KEY: stringRATE_LIMIT_KV: KVNamespaceAUTH_OTP_RATE_LIMIT_MAX?: stringAUTH_OTP_RATE_LIMIT_WINDOW_SEC?: stringdiff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 0b85db8f6..3f986099d 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -1,12 +1,15 @@import type {Agent,+ AgentEmailAccount,AgentRuntime,Artifact,CalendarEvent,Conversation,CreateAgentRequest,CreateCalendarEventRequest,+ CreateEmailAccountRequest,UpdateCalendarEventRequest,+ UpdateEmailAccountRequest,DeleteCalendarEventRequest,UpdateAgentRequest,Email,@@ -307,10 +310,11 @@ export const sendEmail = (workspaceId: string,attachments?: { key: string; filename: string; size: number; contentType: string }[],threading?: { inReplyTo?: string; references?: string },+ customAccountId?: string,) =>apiFetch<Email>(`/api/email/send${wsQuery(workspaceId)}`, {method: "POST",- body: JSON.stringify({ agentId, to, subject, htmlBody, attachments, ...threading }),+ body: JSON.stringify({ agentId, to, subject, htmlBody, attachments, ...threading, customAccountId }),});// Calendar events@@ -380,6 +384,37 @@ export const removeWhitelistEmail = (agentId: string, whitelistId: string, worksmethod: "DELETE",});+// Email Accounts+export const listEmailAccounts = (agentId: string, workspaceId: string) =>+ apiFetch<AgentEmailAccount[]>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`);++export const createEmailAccount = (agentId: string, data: CreateEmailAccountRequest, workspaceId: string) =>+ apiFetch<AgentEmailAccount>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify(data),+ });++export const updateEmailAccount = (agentId: string, accountId: string, data: UpdateEmailAccountRequest, workspaceId: string) =>+ apiFetch<AgentEmailAccount>(`/api/agents/${agentId}/email-accounts/${accountId}${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify(data),+ });++export const deleteEmailAccount = (agentId: string, accountId: string, workspaceId: string) =>+ apiFetch<{ ok: boolean }>(`/api/agents/${agentId}/email-accounts/${accountId}${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });++export const testEmailConnection = (agentId: string, accountId: string, workspaceId: string) =>+ apiFetch<{ imap: string; smtp: string }>(`/api/agents/${agentId}/email-accounts/${accountId}/test${wsQuery(workspaceId)}`, {+ method: "POST",+ });++export const syncEmailAccount = (agentId: string, accountId: string, workspaceId: string) =>+ apiFetch<{ ok: boolean }>(`/api/agents/${agentId}/email-accounts/${accountId}/sync${wsQuery(workspaceId)}`, {+ method: "POST",+ });+// Artifactsexport const listArtifacts = (conversationId: string, workspaceId: string) =>apiFetch<Artifact[]>(`/api/artifacts${wsQuery(workspaceId, { conversation_id: conversationId })}`);