Skip to content

Agent Zero AI framework

feat: Add email integration plugin with IMAP/Exchange polling and SMTP reply

linuztx34f2354cb160
diff --git a/helpers/job_loop.py b/helpers/job_loop.py
index 184858b18..c5fdf86fe 100644
--- a/helpers/job_loop.py
+++ b/helpers/job_loop.py
@@ -40,6 +40,10 @@ async def scheduler_tick():
# Run the scheduler tick
await scheduler.tick()
+ # Run job_loop extensions (e.g. email polling)
+ from helpers.extension import call_extensions_async
+ await call_extensions_async("job_loop")
+
def pause_loop():
global keep_running, pause_time
diff --git a/plugins/_email_integration/default_config.yaml b/plugins/_email_integration/default_config.yaml
new file mode 100644
index 000000000..b3879e4fe
--- /dev/null
+++ b/plugins/_email_integration/default_config.yaml
@@ -0,0 +1,18 @@
+handlers: []
+# Example handler:
+# - name: support
+# enabled: true
+# account_type: imap
+# imap_server: imap.gmail.com
+# imap_port: 993
+# smtp_server: smtp.gmail.com
+# smtp_port: 587
+# username: ""
+# password: ""
+# poll_mode: seconds
+# poll_interval_seconds: 15
+# poll_interval_cron: "*/2 * * * *"
+# sender_whitelist: []
+# project: ""
+# dispatcher_instructions: ""
+# agent_instructions: ""
diff --git a/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py b/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py
new file mode 100644
index 000000000..9cf047f85
--- /dev/null
+++ b/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py
@@ -0,0 +1,76 @@
+import asyncio
+
+from crontab import CronTab
+
+from helpers.extension import Extension
+from helpers.errors import format_error
+from helpers.print_style import PrintStyle
+from helpers import plugins
+
+
+PLUGIN_NAME = "_email_integration"
+DEFAULT_INTERVAL = 15
+MIN_INTERVAL = 5
+
+_poll_tasks: dict[str, asyncio.Task] = {}
+
+
+def _get_sleep_seconds(handler_cfg: dict) -> float:
+ mode = handler_cfg.get("poll_mode", "seconds")
+ if mode == "cron":
+ expr = handler_cfg.get("poll_interval_cron", "*/2 * * * *")
+ try:
+ return max(CronTab(expr).next(default_utc=True), MIN_INTERVAL)
+ except Exception:
+ return DEFAULT_INTERVAL
+ return max(handler_cfg.get("poll_interval_seconds", DEFAULT_INTERVAL), MIN_INTERVAL)
+
+
+async def _handler_poll_loop(handler_name: str):
+ from plugins._email_integration.helpers.handler import (
+ _poll_single_handler,
+ _load_state,
+ _save_state,
+ _state_lock,
+ )
+
+ while True:
+ config = plugins.get_plugin_config(PLUGIN_NAME) or {}
+ handlers = config.get("handlers", [])
+ handler_cfg = next(
+ (h for h in handlers if h.get("name") == handler_name and h.get("enabled")),
+ None,
+ )
+ if handler_cfg is None:
+ break
+
+ try:
+ async with _state_lock:
+ state = _load_state()
+ await _poll_single_handler(handler_cfg, state)
+ _save_state(state)
+ except Exception as e:
+ PrintStyle.error(f"Email poll error ({handler_name}): {format_error(e)}")
+
+ sleep_sec = _get_sleep_seconds(handler_cfg)
+ await asyncio.sleep(sleep_sec)
+
+
+class EmailAutoPoll(Extension):
+
+ async def execute(self, **kwargs):
+ config = plugins.get_plugin_config(PLUGIN_NAME) or {}
+ handlers = config.get("handlers", [])
+ enabled_names = {
+ h["name"] for h in handlers if h.get("enabled") and h.get("name")
+ }
+
+ for name in list(_poll_tasks):
+ if name not in enabled_names or _poll_tasks[name].done():
+ task = _poll_tasks.pop(name, None)
+ if task and not task.done():
+ task.cancel()
+
+ for name in enabled_names:
+ if name not in _poll_tasks or _poll_tasks[name].done():
+ _poll_tasks[name] = asyncio.create_task(_handler_poll_loop(name))
diff --git a/plugins/_email_integration/extensions/python/process_chain_end/_55_email_reply.py b/plugins/_email_integration/extensions/python/process_chain_end/_55_email_reply.py
new file mode 100644
index 000000000..b1a14a4ba
--- /dev/null
+++ b/plugins/_email_integration/extensions/python/process_chain_end/_55_email_reply.py
@@ -0,0 +1,37 @@
+import asyncio
+from helpers.extension import Extension
+from agent import AgentContext, LoopData
+from plugins._email_integration.helpers.dispatcher import CTX_EMAIL_HANDLER
+
+
+class EmailAutoReply(Extension):
+
+ async def execute(self, loop_data: LoopData = LoopData(), **kwargs):
+ if not self.agent or self.agent.number != 0:
+ return
+
+ context = self.agent.context
+ if not context.data.get(CTX_EMAIL_HANDLER):
+ return
+
+ # Extract response from last log item
+ response_text = _extract_last_response(context)
+ if not response_text:
+ return
+
+ asyncio.create_task(self._send_reply(context, response_text))
+
+ async def _send_reply(self, context: AgentContext, response_text: str):
+ from plugins._email_integration.helpers.handler import send_email_reply
+ await send_email_reply(context, response_text)
+
+
+def _extract_last_response(context: AgentContext) -> str:
+ with context.log._lock:
+ logs = list(context.log.logs)
+ if not logs:
+ return ""
+ for item in reversed(logs):
+ if item.type == "response":
+ return item.content or ""
+ return ""
diff --git a/plugins/_email_integration/extensions/python/system_prompt/_20_email_context.py b/plugins/_email_integration/extensions/python/system_prompt/_20_email_context.py
new file mode 100644
index 000000000..d55dba89b
--- /dev/null
+++ b/plugins/_email_integration/extensions/python/system_prompt/_20_email_context.py
@@ -0,0 +1,20 @@
+from helpers.extension import Extension
+from agent import LoopData
+from plugins._email_integration.helpers.dispatcher import CTX_EMAIL_HANDLER
+
+
+class EmailContextPrompt(Extension):
+
+ async def execute(
+ self,
+ system_prompt: list[str] = [],
+ loop_data: LoopData = LoopData(),
+ **kwargs,
+ ):
+ if not self.agent:
+ return
+
+ # Only inject email conversation context if this chat was started by email
+ if self.agent.context.data.get(CTX_EMAIL_HANDLER):
+ prompt = self.agent.read_prompt("agent.system.tool.email_reply.md")
+ system_prompt.append(prompt)
diff --git a/plugins/_email_integration/helpers/__init__.py b/plugins/_email_integration/helpers/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/plugins/_email_integration/helpers/dispatcher.py b/plugins/_email_integration/helpers/dispatcher.py
new file mode 100644
index 000000000..b04d7924c
--- /dev/null
+++ b/plugins/_email_integration/helpers/dispatcher.py
@@ -0,0 +1,85 @@
+"""Email dispatch logic — routes inbound emails to chats. No agent deps in pure helpers."""
+
+import re
+from dataclasses import dataclass
+from typing import Literal
+
+# Pattern for extracting chat thread ID from email subject
+# Matches: [a0-xxxxxxxx] at end of subject
+_THREAD_ID_RE = re.compile(r"\[a0-([a-zA-Z0-9]+)\]")
+
+# Context data keys
+CTX_EMAIL_HANDLER = "_email_handler"
+CTX_EMAIL_SENDER = "_email_sender"
+CTX_EMAIL_THREAD_ID = "_email_thread_id"
+CTX_EMAIL_SUBJECT = "_email_subject"
+CTX_EMAIL_MESSAGE_ID = "_email_message_id"
+CTX_EMAIL_REFERENCES = "_email_references"
+
+DispatchAction = Literal["new_chat", "continue_chat", "intervene_soft", "intervene_hard"]
+
+
+@dataclass
+class DispatchDecision:
+ action: DispatchAction
+ context_id: str = ""
+ reason: str = ""
+
+
+def extract_thread_id(subject: str) -> str:
+ match = _THREAD_ID_RE.search(subject)
+ return match.group(1) if match else ""
+
+
+def build_reply_subject(original_subject: str, thread_id: str) -> str:
+ clean = _THREAD_ID_RE.sub("", original_subject).strip()
+ if not clean.lower().startswith("re:"):
+ clean = f"Re: {clean}"
+ return f"{clean} [a0-{thread_id}]"
+
+
+def build_chat_summary(context_id: str, data: dict) -> dict:
+ return {
+ "context_id": context_id,
+ "thread_id": data.get(CTX_EMAIL_THREAD_ID, ""),
+ "sender": data.get(CTX_EMAIL_SENDER, ""),
+ "subject": data.get(CTX_EMAIL_SUBJECT, ""),
+ "handler": data.get(CTX_EMAIL_HANDLER, ""),
+ }
+
+
+# ------------------------------------------------------------------
+# Dispatcher prompt builders
+# ------------------------------------------------------------------
+
+def format_chats_list(existing_chats: list[dict]) -> str:
+ if not existing_chats:
+ return "No existing chats for this handler."
+ lines = []
+ for c in existing_chats[:20]:
+ lines.append(
+ f"- context_id={c['context_id']} thread_id={c.get('thread_id', '')} "
+ f"sender={c.get('sender', '')} subject={c.get('subject', '')}"
+ )
+ return "\n".join(lines)
+
+
+def parse_dispatcher_response(response: str) -> DispatchDecision:
+ line = response.strip().split("\n")[0].strip()
+ parts = line.split(None, 2)
+
+ if len(parts) < 2:
+ return DispatchDecision(action="new_chat", reason="unparseable response")
+
+ action_raw = parts[0].upper()
+ ctx_id = parts[1] if parts[1] != "_" else ""
+ reason = parts[2] if len(parts) > 2 else ""
+
+ action_map: dict[str, DispatchAction] = {
+ "NEW_CHAT": "new_chat",
+ "CONTINUE": "continue_chat",
+ "INTERVENE_SOFT": "intervene_soft",
+ "INTERVENE_HARD": "intervene_hard",
+ }
+ action = action_map.get(action_raw, "new_chat")
+ return DispatchDecision(action=action, context_id=ctx_id, reason=reason)
diff --git a/plugins/_email_integration/helpers/handler.py b/plugins/_email_integration/helpers/handler.py
new file mode 100644
index 000000000..332ea5cdf
--- /dev/null
+++ b/plugins/_email_integration/helpers/handler.py
@@ -0,0 +1,393 @@
+"""Email handler — orchestrates poll, dispatch, and reply. Requires agent context."""
+
+import asyncio
+import json
+import os
+
+from agent import Agent, AgentContext, UserMessage
+from helpers import guids, plugins, files
+from helpers import message_queue as mq
+from helpers.persist_chat import save_tmp_chat
+from helpers.print_style import PrintStyle
+from helpers.errors import format_error
+from initialize import initialize_agent
+
+from plugins._email_integration.helpers import dispatcher as disp
+from plugins._email_integration.helpers.imap_client import (
+ InboundMessage,
+ connect_imap,
+ disconnect_imap,
+ fetch_new,
+ get_highest_uid,
+ connect_exchange,
+ fetch_unread_exchange,
+)
+from plugins._email_integration.helpers.smtp_client import SmtpConfig, send_reply
+
+
+PLUGIN_NAME = "_email_integration"
+DOWNLOAD_FOLDER = "usr/email/attachments"
+STATE_FILE = "usr/email/state.json"
+
+_PROMPTS_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "prompts")
+
+
+def _read_fw(filename: str, **kwargs: str) -> str:
+ return files.read_prompt_file(filename, _directories=[_PROMPTS_DIR], **kwargs)
+
+
+# ------------------------------------------------------------------
+# UID state persistence
+# ------------------------------------------------------------------
+
+_state_lock = asyncio.Lock()
+
+def _load_state() -> dict:
+ path = files.get_abs_path(STATE_FILE)
+ if os.path.isfile(path):
+ try:
+ return json.loads(files.read_file(path))
+ except Exception:
+ return {}
+ return {}
+
+
+def _save_state(state: dict):
+ path = files.get_abs_path(STATE_FILE)
+ files.make_dirs(path)
+ files.write_file(path, json.dumps(state))
+
+
+# ------------------------------------------------------------------
+# Main auto-poll entry point (called from job_loop extension)
+# ------------------------------------------------------------------
+
+async def poll_all_handlers():
+ config = plugins.get_plugin_config(PLUGIN_NAME) or {}
+ handlers = config.get("handlers", [])
+ enabled = [h for h in handlers if h.get("enabled", False)]
+
+ if not enabled:
+ return
+
+ state = _load_state()
+
+ for handler_cfg in enabled:
+ try:
+ await _poll_single_handler(handler_cfg, state)
+ except Exception as e:
+ name = handler_cfg.get("name", "?")
+ PrintStyle.error(f"Email poll error ({name}): {format_error(e)}")
+
+ _save_state(state)
+
+
+async def _poll_single_handler(handler_cfg: dict, state: dict):
+ name = handler_cfg.get("name", "default")
+ account_type = handler_cfg.get("account_type", "imap")
+ whitelist = handler_cfg.get("sender_whitelist") or []
+ last_uid = state.get(name, {}).get("last_uid", 0)
+
+ if account_type == "exchange":
+ messages = await _fetch_exchange(handler_cfg, whitelist)
+ if messages:
+ await _dispatch_all(handler_cfg, messages)
+ return
+
+ client = await connect_imap(
+ server=handler_cfg.get("imap_server", ""),
+ port=int(handler_cfg.get("imap_port", 993)),
+ username=handler_cfg.get("username", ""),
+ password=handler_cfg.get("password", ""),
+ )
+ try:
+ # First run: record current highest UID, don't process old emails
+ if last_uid == 0:
+ highest = await get_highest_uid(client)
+ state[name] = {"last_uid": highest}
+ PrintStyle.info(f"Email ({name}): initialized, tracking from UID {highest}")
+ return
+
+ messages, new_uid = await fetch_new(
+ client, DOWNLOAD_FOLDER, last_uid, whitelist or None,
+ )
+
+ if new_uid > last_uid:
+ state[name] = {"last_uid": new_uid}
+
+ if messages:
+ PrintStyle.info(f"Email ({name}): {len(messages)} new messages")
+ await _dispatch_all(handler_cfg, messages)
+
+ finally:
+ await disconnect_imap(client)
+
+
+async def _fetch_exchange(cfg: dict, whitelist: list[str]) -> list[InboundMessage]:
+ account = await connect_exchange(
+ server=cfg.get("imap_server", ""),
+ username=cfg.get("username", ""),
+ password=cfg.get("password", ""),
+ )
+ return await fetch_unread_exchange(account, DOWNLOAD_FOLDER, whitelist or None)
+
+
+async def _dispatch_all(handler_cfg: dict, messages: list[InboundMessage]):
+ # Need an agent for dispatcher AI calls — use first available or create temp
+ ctx = AgentContext.first()
+ if not ctx:
+ agent_config = initialize_agent()
+ ctx = AgentContext(agent_config, name="Email Dispatcher")
+ agent = ctx.agent0
+
+ for msg in messages:
+ try:
+ await _dispatch_message(agent, handler_cfg, msg)
+ except Exception as e:
+ PrintStyle.error(f"Email dispatch error: {format_error(e)}")
+
+
+# ------------------------------------------------------------------
+# Dispatch a single inbound message
+# ------------------------------------------------------------------
+
+async def _dispatch_message(agent: Agent, handler_cfg: dict, msg: InboundMessage):
+ handler_name = handler_cfg.get("name", "default")
+ thread_id = disp.extract_thread_id(msg.subject)
+
+ existing = _find_handler_chats(handler_name, msg.sender)
+
+ # Fast path: thread ID in subject matches a known chat
+ if thread_id:
+ for chat in existing:
+ if chat["thread_id"] == thread_id:
+ await _route_to_chat(
+ agent, handler_cfg, msg, chat["context_id"], "continue_chat",
+ )
+ return
+
+ # Dispatcher AI decides
+ decision = await _call_dispatcher(agent, handler_cfg, msg, existing)
+
+ if decision.action == "new_chat":
+ await _start_new_chat(agent, handler_cfg, msg)
+ elif decision.action in ("continue_chat", "intervene_soft", "intervene_hard"):
+ ctx = AgentContext.get(decision.context_id)
+ if not ctx:
+ PrintStyle.warning(
+ f"Dispatcher referenced unknown context {decision.context_id}, starting new chat"
+ )
+ await _start_new_chat(agent, handler_cfg, msg)
+ else:
+ await _route_to_chat(
+ agent, handler_cfg, msg, decision.context_id, decision.action,
+ )
+ else:
+ await _start_new_chat(agent, handler_cfg, msg)
+
+
+async def _call_dispatcher(
+ agent: Agent,
+ handler_cfg: dict,
+ msg: InboundMessage,
+ existing_chats: list[dict],
+) -> disp.DispatchDecision:
+ body_preview = msg.body[:2000] if len(msg.body) > 2000 else msg.body
+ chats_text = disp.format_chats_list(existing_chats)
+
+ prompt = agent.read_prompt(
+ "fw.email.dispatcher_prompt.md",
+ sender=msg.sender,
+ subject=msg.subject,
+ body=body_preview,
+ chats=chats_text,
+ )
+
+ extra = handler_cfg.get("dispatcher_instructions", "")
+ if extra:
+ prompt += agent.read_prompt(
+ "fw.email.dispatcher_extra.md", instructions=extra,
+ )
+
+ system = agent.read_prompt("fw.email.dispatcher_system.md")
+
+ try:
+ response = await agent.call_utility_model(system=system, message=prompt)
+ return disp.parse_dispatcher_response(str(response))
+ except Exception as e:
+ PrintStyle.error(f"Dispatcher error: {format_error(e)}")
+ return disp.DispatchDecision(action="new_chat", reason="dispatcher error")
+
+
+# ------------------------------------------------------------------
+# Chat creation and routing
+# ------------------------------------------------------------------
+
+async def _start_new_chat(agent: Agent, handler_cfg: dict, msg: InboundMessage):
+ from helpers import projects
+
+ handler_name = handler_cfg.get("name", "default")
+ thread_id = guids.generate_id()
+
+ config = initialize_agent()
+ context = AgentContext(config, name=f"Email: {msg.subject[:50]}")
+
+ context.data[disp.CTX_EMAIL_HANDLER] = handler_name
+ context.data[disp.CTX_EMAIL_SENDER] = msg.sender
+ context.data[disp.CTX_EMAIL_THREAD_ID] = thread_id
+ context.data[disp.CTX_EMAIL_SUBJECT] = msg.subject
+ context.data[disp.CTX_EMAIL_MESSAGE_ID] = msg.message_id
+ context.data[disp.CTX_EMAIL_REFERENCES] = msg.references
+
+ project = handler_cfg.get("project", "")
+ if project:
+ projects.activate_project(context.id, project)
+
+ save_tmp_chat(context)
+
+ user_msg = _build_user_message(agent, msg, handler_cfg)
+ system_ctx = agent.read_prompt("fw.email.system_context.md")
+
+ mq.log_user_message(context, user_msg, msg.attachments or [], source=" (email)")
+ context.communicate(UserMessage(
+ message=user_msg,
+ system_message=[system_ctx],
+ attachments=msg.attachments,
+ ))
+
+ PrintStyle.success(f"Email: new chat {context.id} for '{msg.subject}' from {msg.sender}")
+
+
+async def _route_to_chat(
+ agent: Agent,
+ handler_cfg: dict,
+ msg: InboundMessage,
+ context_id: str,
+ action: disp.DispatchAction,
+):
+ context = AgentContext.get(context_id)
+ if not context:
+ return
+
+ context.data[disp.CTX_EMAIL_MESSAGE_ID] = msg.message_id
+ if msg.references:
+ context.data[disp.CTX_EMAIL_REFERENCES] = msg.references
+
+ if action == "intervene_soft":
+ soft_msg = agent.read_prompt(
+ "fw.email.intervene_soft.md",
+ sender=msg.sender,
+ subject=msg.subject,
+ body=msg.body,
+ )
+ mq.add(context, soft_msg, msg.attachments)
+ PrintStyle.info(f"Email: queued soft intervention for chat {context_id}")
+
+ elif action == "intervene_hard":
+ user_msg = _build_user_message(agent, msg, handler_cfg)
+ system_ctx = agent.read_prompt("fw.email.system_context.md")
+ mq.log_user_message(context, user_msg, msg.attachments or [], source=" (email)")
+ context.communicate(UserMessage(
+ message=user_msg,
+ system_message=[system_ctx],
+ attachments=msg.attachments,
+ ))
+ PrintStyle.info(f"Email: hard intervention on chat {context_id}")
+
+ else:
+ user_msg = _build_user_message(agent, msg, handler_cfg)
+ mq.log_user_message(context, user_msg, msg.attachments or [], source=" (email)")
+ context.communicate(UserMessage(
+ message=user_msg,
+ attachments=msg.attachments,
+ ))
+ PrintStyle.info(f"Email: continuing chat {context_id}")
+
+ save_tmp_chat(context)
+
+
+# ------------------------------------------------------------------
+# Chat discovery
+# ------------------------------------------------------------------
+
+def _find_handler_chats(handler_name: str, sender: str) -> list[dict]:
+ results = []
+ for ctx_id, ctx in AgentContext._contexts.items():
+ if not isinstance(ctx, AgentContext):
+ continue
+ data = ctx.data
+ if data.get(disp.CTX_EMAIL_HANDLER) != handler_name:
+ continue
+ if data.get(disp.CTX_EMAIL_SENDER, "").lower() != sender.lower():
+ continue
+ results.append(disp.build_chat_summary(ctx_id, data))
+
+ results.sort(key=lambda c: c["context_id"], reverse=True)
+ return results[:20]
+
+
+# ------------------------------------------------------------------
+# Message builders
+# ------------------------------------------------------------------
+
+def _build_user_message(agent: Agent, msg: InboundMessage, handler_cfg: dict) -> str:
+ text = agent.read_prompt(
+ "fw.email.user_message.md",
+ sender=msg.sender,
+ subject=msg.subject,
+ body=msg.body,
+ )
+ instructions = handler_cfg.get("agent_instructions", "")
+ if instructions:
+ text += agent.read_prompt(
+ "fw.email.user_message_instructions.md", instructions=instructions,
+ )
+ return text
+
+
+# ------------------------------------------------------------------
+# Reply sending (called from process_chain_end extension)
+# ------------------------------------------------------------------
+
+async def send_email_reply(context: AgentContext, response_text: str):
+ handler_name = context.data.get(disp.CTX_EMAIL_HANDLER)
+ if not handler_name:
+ return
+
+ cfg = _get_handler_config(handler_name)
+ if not cfg:
+ PrintStyle.error(f"Email: handler config not found for '{handler_name}'")
+ return
+
+ sender = context.data.get(disp.CTX_EMAIL_SENDER, "")
+ original_subject = context.data.get(disp.CTX_EMAIL_SUBJECT, "")
+ thread_id = context.data.get(disp.CTX_EMAIL_THREAD_ID, "")
+ original_msg_id = context.data.get(disp.CTX_EMAIL_MESSAGE_ID, "")
+ references = context.data.get(disp.CTX_EMAIL_REFERENCES, "")
+
+ subject = disp.build_reply_subject(original_subject, thread_id)
+
+ smtp_cfg = SmtpConfig(
+ server=cfg.get("smtp_server", cfg.get("imap_server", "")),
+ port=int(cfg.get("smtp_port", 587)),
+ username=cfg.get("username", ""),
+ password=cfg.get("password", ""),
+ )
+
+ await send_reply(
+ config=smtp_cfg,
+ to=sender,
+ subject=subject,
+ body=response_text,
+ in_reply_to=original_msg_id,
+ references=references,
+ )
+
+
+def _get_handler_config(handler_name: str) -> dict | None:
+ config = plugins.get_plugin_config(PLUGIN_NAME) or {}
+ handlers = config.get("handlers", [])
+ for h in handlers:
+ if h.get("name") == handler_name:
+ return h
+ return None
diff --git a/plugins/_email_integration/helpers/imap_client.py b/plugins/_email_integration/helpers/imap_client.py
new file mode 100644
index 000000000..a4dd02d50
--- /dev/null
+++ b/plugins/_email_integration/helpers/imap_client.py
@@ -0,0 +1,370 @@
+"""IMAP/Exchange email reader. No agent/tool dependencies."""
+
+import asyncio
+import email
+import os
+import re
+import uuid
+from dataclasses import dataclass, field
+from email.header import decode_header
+from email.message import Message as EmailMessage
+from fnmatch import fnmatch
+
+import html2text
+from bs4 import BeautifulSoup
+from imapclient import IMAPClient
+
+from helpers import files
+from helpers.errors import format_error
+from helpers.print_style import PrintStyle
+
+
+# ------------------------------------------------------------------
+# Data models
+# ------------------------------------------------------------------
+
+@dataclass
+class InboundMessage:
+ sender: str
+ subject: str
+ body: str
+ attachments: list[str] = field(default_factory=list)
+ message_id: str = ""
+ in_reply_to: str = ""
+ references: str = ""
+
+
+# ------------------------------------------------------------------
+# IMAP connection
+# ------------------------------------------------------------------
+
+async def connect_imap(
+ server: str,
+ port: int = 993,
+ username: str = "",
+ password: str = "",
+ ssl: bool = True,
+ timeout: int = 30,
+) -> IMAPClient:
+ loop = asyncio.get_event_loop()
+
+ def _sync():
+ client = IMAPClient(server, port=port, ssl=ssl, timeout=timeout)
+ client._imap._maxline = 100000
+ client.login(username, password)
+ return client
+
+ return await loop.run_in_executor(None, _sync)
+
+
+async def disconnect_imap(client: IMAPClient) -> None:
+ try:
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(None, client.logout)
+ except Exception as e:
+ PrintStyle.error(f"IMAP disconnect error: {format_error(e)}")
+
+
+# ------------------------------------------------------------------
+# Fetch messages
+# ------------------------------------------------------------------
+
+async def fetch_new(
+ client: IMAPClient,
+ download_folder: str,
+ last_uid: int = 0,
+ sender_whitelist: list[str] | None = None,
+ max_messages: int = 10,
+) -> tuple[list[InboundMessage], int]:
+ """Fetch emails newer than last_uid. Returns (messages, new_last_uid)."""
+ loop = asyncio.get_event_loop()
+
+ def _search():
+ client.select_folder("INBOX")
+ # Use Gmail category filter if supported, otherwise plain UNSEEN
+ try:
+ return client.gmail_search("category:primary is:unread")
+ except Exception:
+ return client.search(["UNSEEN"])
+
+ msg_ids = await loop.run_in_executor(None, _search)
+ if not msg_ids:
+ return [], last_uid
+
+ # Filter out already-seen UIDs
+ if last_uid > 0:
+ msg_ids = [uid for uid in msg_ids if uid > last_uid]
+
+ if not msg_ids:
+ return [], last_uid
+
+ new_last_uid = max(msg_ids)
+
+ # Cap to most recent
+ if len(msg_ids) > max_messages:
+ PrintStyle.standard(
+ f"Email: {len(msg_ids)} new, processing latest {max_messages}"
+ )
+ msg_ids = msg_ids[-max_messages:]
+ else:
+ PrintStyle.standard(f"Email: found {len(msg_ids)} new messages")
+
+ results: list[InboundMessage] = []
+
+ for msg_id in msg_ids:
+ try:
+ msg = await _fetch_single(client, msg_id, download_folder, sender_whitelist)
+ if msg:
+ results.append(msg)
+ except Exception as e:
+ PrintStyle.error(f"Email: error processing message {msg_id}: {format_error(e)}")
+ return results, new_last_uid
+
+
+async def get_highest_uid(client: IMAPClient) -> int:
+ """Get the highest UID in inbox without fetching any messages."""
+ loop = asyncio.get_event_loop()
+
+ def _search():
+ client.select_folder("INBOX")
+ uids = client.search(["ALL"])
+ return max(uids) if uids else 0
+
+ return await loop.run_in_executor(None, _search)
+
+
+async def _fetch_single(
+ client: IMAPClient,
+ msg_id: int,
+ download_folder: str,
+ sender_whitelist: list[str] | None,
+) -> InboundMessage | None:
+ loop = asyncio.get_event_loop()
+
+ def _sync_fetch():
+ data = client.fetch([msg_id], ["RFC822"])[msg_id]
+ # Explicitly mark as read — RFC822 fetch doesn't always set \Seen on all servers
+ client.add_flags([msg_id], [b"\\Seen"])
+ return data
+
+ raw = await loop.run_in_executor(None, _sync_fetch)
+ email_data = raw.get(b"RFC822")
+ if not email_data:
+ return None
+
+ email_msg = email.message_from_bytes(email_data)
+
+ sender = _decode_header(email_msg.get("From", ""))
+ if sender_whitelist and not _matches_whitelist(sender, sender_whitelist):
+ return None
+
+ subject = _decode_header(email_msg.get("Subject", ""))
+ message_id = email_msg.get("Message-ID", "")
+ in_reply_to = email_msg.get("In-Reply-To", "")
+ references = email_msg.get("References", "")
+
+ body, attachments = await _parse_body(email_msg, download_folder)
+
+ return InboundMessage(
+ sender=sender,
+ subject=subject,
+ body=body,
+ attachments=attachments,
+ message_id=message_id,
+ in_reply_to=in_reply_to,
+ references=references,
+ )
+
+
+# ------------------------------------------------------------------
+# Exchange connection
+# ------------------------------------------------------------------
+
+async def connect_exchange(
+ server: str,
+ username: str,
+ password: str,
+):
+ from exchangelib import Account, Configuration, Credentials, DELEGATE
+
+ loop = asyncio.get_event_loop()
+
+ def _sync():
+ creds = Credentials(username=username, password=password)
+ config = Configuration(server=server, credentials=creds)
+ return Account(
+ primary_smtp_address=username,
+ config=config,
+ autodiscover=False,
+ access_type=DELEGATE,
+ )
+
+ return await loop.run_in_executor(None, _sync)
+
+
+async def fetch_unread_exchange(
+ account,
+ download_folder: str,
+ sender_whitelist: list[str] | None = None,
+) -> list[InboundMessage]:
+ from exchangelib import Q
+
+ loop = asyncio.get_event_loop()
+
+ def _sync():
+ return list(account.inbox.filter(Q(is_read=False)))
+
+ items = await loop.run_in_executor(None, _sync)
+ results: list[InboundMessage] = []
+
+ for item in items:
+ sender = str(item.sender.email_address) if item.sender else ""
+ if sender_whitelist and not _matches_whitelist(sender, sender_whitelist):
+ continue
+
+ body = str(item.text_body or item.body or "")
+ if item.body and str(item.body).strip().startswith("<"):
+ body = _html_to_text(str(item.body))
+
+ attachment_paths: list[str] = []
+ if item.attachments:
+ for att in item.attachments:
+ if hasattr(att, "content") and att.name:
+ path = await _save_attachment(att.name, att.content, download_folder)
+ attachment_paths.append(path)
+
+ results.append(InboundMessage(
+ sender=sender,
+ subject=str(item.subject or ""),
+ body=body,
+ attachments=attachment_paths,
+ message_id=str(getattr(item, "message_id", "") or ""),
+ in_reply_to=str(getattr(item, "in_reply_to", "") or ""),
+ references="",
+ ))
+
+ return results
+
+
+# ------------------------------------------------------------------
+# Parsing helpers
+# ------------------------------------------------------------------
+
+async def _parse_body(
+ email_msg: EmailMessage,
+ download_folder: str,
+) -> tuple[str, list[str]]:
+ body = ""
+ attachments: list[str] = []
+ cid_map: dict[str, str] = {}
+
+ if email_msg.is_multipart():
+ for part in email_msg.walk():
+ content_type = part.get_content_type()
+ disposition = str(part.get("Content-Disposition", ""))
+
+ if part.get_content_maintype() == "multipart":
+ continue
+
+ if "attachment" in disposition or part.get("Content-ID"):
+ filename = part.get_filename()
+ if filename:
+ filename = _decode_header(filename)
+ content = part.get_payload(decode=True)
+ if content:
+ path = await _save_attachment(filename, content, download_folder)
+ attachments.append(path)
+ cid = part.get("Content-ID")
+ if cid:
+ cid_map[cid.strip("<>")] = path
+
+ elif content_type == "text/plain" and not body:
+ charset = part.get_content_charset() or "utf-8"
+ body = part.get_payload(decode=True).decode(charset, errors="ignore")
+
+ elif content_type == "text/html" and not body:
+ charset = part.get_content_charset() or "utf-8"
+ html = part.get_payload(decode=True).decode(charset, errors="ignore")
+ body = _html_to_text(html, cid_map)
+ else:
+ content_type = email_msg.get_content_type()
+ charset = email_msg.get_content_charset() or "utf-8"
+ content = email_msg.get_payload(decode=True)
+ if content:
+ if content_type == "text/html":
+ body = _html_to_text(content.decode(charset, errors="ignore"))
+ else:
+ body = content.decode(charset, errors="ignore")
+
+ body = _strip_quoted_reply(body)
+ return body, attachments
+
+
+def _strip_quoted_reply(text: str) -> str:
+ """Remove quoted reply chains (e.g. 'On ... wrote:' + '>' lines)."""
+ if not text:
+ return text
+ lines = text.splitlines()
+ cut = len(lines)
+ for i, line in enumerate(lines):
+ # Match "On <date> <someone> wrote:" pattern
+ if re.match(r"^On .+ wrote:\s*$", line.strip()):
+ # Verify next non-empty lines are quoted
+ rest = [l for l in lines[i + 1:] if l.strip()]
+ if not rest or rest[0].strip().startswith(">"):
+ cut = i
+ break
+ # Also strip trailing blank lines before the cut
+ while cut > 0 and not lines[cut - 1].strip():
+ cut -= 1
+ return "\n".join(lines[:cut]).strip()
+
+
+def _html_to_text(html_content: str, cid_map: dict[str, str] | None = None) -> str:
+ if cid_map:
+ soup = BeautifulSoup(html_content, "html.parser")
+ for img in soup.find_all("img"):
+ src = img.get("src", "")
+ if src.startswith("cid:"):
+ cid = src[4:]
+ if cid in cid_map:
+ img.replace_with(soup.new_string(f"[file://{cid_map[cid]}]"))
+ html_content = str(soup)
+
+ h = html2text.HTML2Text()
+ h.ignore_links = False
+ h.ignore_images = False
+ h.ignore_emphasis = False
+ h.body_width = 0
+ text = h.handle(html_content)
+ text = re.sub(r"\n{3,}", "\n\n", text).strip()
+ return text
+
+
+async def _save_attachment(filename: str, content: bytes, download_folder: str) -> str:
+ filename = files.safe_file_name(filename)
+ name, ext = os.path.splitext(filename)
+ unique = f"{name}_{uuid.uuid4().hex[:8]}{ext}"
+ rel_path = os.path.join(download_folder, unique)
+ files.write_file_bin(rel_path, content)
+ return files.get_abs_path(rel_path)
+
+
+def _decode_header(header: str) -> str:
+ if not header:
+ return ""
+ parts = []
+ for part, encoding in decode_header(header):
+ if isinstance(part, bytes):
+ parts.append(part.decode(encoding or "utf-8", errors="ignore"))
+ else:
+ parts.append(str(part))
+ return " ".join(parts)
+
+
+def _matches_whitelist(sender: str, whitelist: list[str]) -> bool:
+ sender_lower = sender.lower()
+ for pattern in whitelist:
+ if fnmatch(sender_lower, pattern.lower()):
+ return True
+ return False
diff --git a/plugins/_email_integration/helpers/smtp_client.py b/plugins/_email_integration/helpers/smtp_client.py
new file mode 100644
index 000000000..58beb7066
--- /dev/null
+++ b/plugins/_email_integration/helpers/smtp_client.py
@@ -0,0 +1,80 @@
+"""SMTP email sender. No agent/tool dependencies."""
+
+import asyncio
+import smtplib
+from email.mime.text import MIMEText
+from email.mime.multipart import MIMEMultipart
+from email.mime.base import MIMEBase
+from email import encoders
+from dataclasses import dataclass
+import os
+
+from helpers.errors import format_error
+from helpers.print_style import PrintStyle
+
+
+@dataclass
+class SmtpConfig:
+ server: str
+ port: int = 587
+ username: str = ""
+ password: str = ""
+ use_tls: bool = True
+
+
+async def send_reply(
+ config: SmtpConfig,
+ to: str,
+ subject: str,
+ body: str,
+ in_reply_to: str = "",
+ references: str = "",
+ attachments: list[str] | None = None,
+) -> bool:
+ loop = asyncio.get_event_loop()
+
+ def _sync_send():
+ msg = MIMEMultipart() if attachments else MIMEText(body, "plain", "utf-8")
+
+ if attachments:
+ msg.attach(MIMEText(body, "plain", "utf-8"))
+ for path in attachments:
+ if not os.path.isfile(path):
+ continue
+ part = MIMEBase("application", "octet-stream")
+ with open(path, "rb") as f:
+ part.set_payload(f.read())
+ encoders.encode_base64(part)
+ part.add_header(
+ "Content-Disposition",
+ f"attachment; filename={os.path.basename(path)}",
+ )
+ msg.attach(part)
+
+ msg["From"] = config.username
+ msg["To"] = to
+ msg["Subject"] = subject
+
+ if in_reply_to:
+ msg["In-Reply-To"] = in_reply_to
+ msg["References"] = references or in_reply_to
+
+ if config.use_tls:
+ with smtplib.SMTP(config.server, config.port) as server:
+ server.ehlo()
+ server.starttls()
+ server.ehlo()
+ server.login(config.username, config.password)
+ server.send_message(msg)
+ else:
+ with smtplib.SMTP_SSL(config.server, config.port) as server:
+ server.login(config.username, config.password)
+ server.send_message(msg)
+
+ try:
+ await loop.run_in_executor(None, _sync_send)
+ PrintStyle.success(f"Email sent to {to}: {subject}")
+ return True
+ except Exception as e:
+ PrintStyle.error(f"Email send failed: {format_error(e)}")
+ return False
diff --git a/plugins/_email_integration/plugin.yaml b/plugins/_email_integration/plugin.yaml
new file mode 100644
index 000000000..e2d84ee3f
--- /dev/null
+++ b/plugins/_email_integration/plugin.yaml
@@ -0,0 +1,8 @@
+name: _email_integration
+title: Email Integration
+description: Communicate with Agent Zero via email. Supports IMAP/Exchange inbox polling with SMTP replies.
+version: 0.1.0
+settings_sections:
+ - external
+per_project_config: true
+per_agent_config: false
diff --git a/plugins/_email_integration/prompts/agent.system.tool.email_reply.md b/plugins/_email_integration/prompts/agent.system.tool.email_reply.md
new file mode 100644
index 000000000..8d43c4632
--- /dev/null
+++ b/plugins/_email_integration/prompts/agent.system.tool.email_reply.md
@@ -0,0 +1,6 @@
+## Email conversation
+you are in an email conversation, user communicates via email
+your response (via response tool) will be sent as email reply automatically
+be concise, professional, clear
+do not include email headers or signatures — they are added automatically
+if task requires extended processing, provide brief status then continue work
diff --git a/plugins/_email_integration/prompts/fw.email.dispatcher_extra.md b/plugins/_email_integration/prompts/fw.email.dispatcher_extra.md
new file mode 100644
index 000000000..f3b12512e
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.dispatcher_extra.md
@@ -0,0 +1,3 @@
+
+## Additional Instructions
+{{instructions}}
diff --git a/plugins/_email_integration/prompts/fw.email.dispatcher_prompt.md b/plugins/_email_integration/prompts/fw.email.dispatcher_prompt.md
new file mode 100644
index 000000000..d8cc08972
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.dispatcher_prompt.md
@@ -0,0 +1,8 @@
+## New Email
+From: {{sender}}
+Subject: {{subject}}
+
+{{body}}
+
+## Existing Chats
+{{chats}}
diff --git a/plugins/_email_integration/prompts/fw.email.dispatcher_system.md b/plugins/_email_integration/prompts/fw.email.dispatcher_system.md
new file mode 100644
index 000000000..2276d9fbf
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.dispatcher_system.md
@@ -0,0 +1,19 @@
+You route inbound emails to agent chats.
+You receive: the new email (sender, subject, body) and a list of existing chats for this email handler.
+
+Rules:
+- If the email subject contains a thread ID marker [a0-XXXX] AND a matching chat exists, reply with CONTINUE and that chat's context_id
+- If no thread ID but the email content clearly relates to an existing chat (same topic, same sender), reply with CONTINUE and the best matching context_id
+- If the email is a status question or low-priority follow-up on a running chat, reply with INTERVENE_SOFT and the context_id — the agent will receive it after current step
+- If the email is urgent and requires immediate attention on a running chat, reply with INTERVENE_HARD and the context_id
+- Otherwise reply with NEW_CHAT
+
+Respond with EXACTLY one line in this format:
+ACTION context_id reason
+
+Examples:
+NEW_CHAT _ new request from user
+CONTINUE ctx_abc123 thread ID matches
+CONTINUE ctx_def456 same sender discussing AWS deployment
+INTERVENE_SOFT ctx_abc123 user asking for status update
+INTERVENE_HARD ctx_abc123 urgent correction needed
diff --git a/plugins/_email_integration/prompts/fw.email.intervene_soft.md b/plugins/_email_integration/prompts/fw.email.intervene_soft.md
new file mode 100644
index 000000000..b3115d890
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.intervene_soft.md
@@ -0,0 +1,5 @@
+[Email from {{sender}}] user following up, respond and continue current work
+
+Subject: {{subject}}
+
+{{body}}
diff --git a/plugins/_email_integration/prompts/fw.email.poll_error.md b/plugins/_email_integration/prompts/fw.email.poll_error.md
new file mode 100644
index 000000000..4f4ab59d9
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.poll_error.md
@@ -0,0 +1 @@
+email poll error: {{error}}
diff --git a/plugins/_email_integration/prompts/fw.email.poll_ok.md b/plugins/_email_integration/prompts/fw.email.poll_ok.md
new file mode 100644
index 000000000..410c45a19
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.poll_ok.md
@@ -0,0 +1 @@
+email poll complete: {{result}}
diff --git a/plugins/_email_integration/prompts/fw.email.system_context.md b/plugins/_email_integration/prompts/fw.email.system_context.md
new file mode 100644
index 000000000..3b2da2fdf
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.system_context.md
@@ -0,0 +1,3 @@
+you are communicating via email, user sent email message
+use response tool to send reply — response sent as email reply automatically
+be concise, professional, clear
diff --git a/plugins/_email_integration/prompts/fw.email.user_message.md b/plugins/_email_integration/prompts/fw.email.user_message.md
new file mode 100644
index 000000000..4d70251fb
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.user_message.md
@@ -0,0 +1,4 @@
+[Email from {{sender}}]
+Subject: {{subject}}
+
+{{body}}
diff --git a/plugins/_email_integration/prompts/fw.email.user_message_instructions.md b/plugins/_email_integration/prompts/fw.email.user_message_instructions.md
new file mode 100644
index 000000000..580f1a54e
--- /dev/null
+++ b/plugins/_email_integration/prompts/fw.email.user_message_instructions.md
@@ -0,0 +1,2 @@
+
+[Handler instructions: {{instructions}}]
diff --git a/plugins/_email_integration/test_connection.py b/plugins/_email_integration/test_connection.py
new file mode 100644
index 000000000..ed7ab8b15
--- /dev/null
+++ b/plugins/_email_integration/test_connection.py
@@ -0,0 +1,111 @@
+"""
+Email integration connection test.
+Usage: [email protected] EMAIL_PASS=xxxx python plugins/_email_integration/test_connection.py
+
+Tests:
+ 1. IMAP connect + get highest UID (baseline)
+ 2. Fetch new emails since that UID (should be 0 on first run)
+ 3. SMTP send test email to self
+ 4. Fetch again (should find the test email)
+"""
+
+import asyncio
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../..")
+
+from plugins._email_integration.helpers.imap_client import (
+ connect_imap,
+ disconnect_imap,
+ fetch_new,
+ get_highest_uid,
+)
+from plugins._email_integration.helpers.smtp_client import SmtpConfig, send_reply
+
+
+async def test_full_flow(user: str, password: str):
+ print(f"\n--- Full Flow Test ({user}) ---\n")
+
+ # Step 1: Connect and get baseline UID
+ client = await connect_imap(
+ server="imap.gmail.com", port=993,
+ username=user, password=password,
+ )
+ print("[OK] IMAP login")
+
+ baseline_uid = await get_highest_uid(client)
+ print(f"[OK] Baseline UID: {baseline_uid}")
+
+ # Step 2: Fetch new since baseline — should be 0
+ messages, new_uid = await fetch_new(
+ client, "/tmp/email_test_attachments",
+ last_uid=baseline_uid, max_messages=5,
+ )
+ print(f"[OK] Fetch new since UID {baseline_uid}: {len(messages)} messages (expected 0)")
+
+ await disconnect_imap(client)
+
+ # Step 3: Send test email to self
+ print("\n--- Sending test email to self ---")
+ cfg = SmtpConfig(
+ server="smtp.gmail.com", port=587,
+ username=user, password=password,
+ )
+ ok = await send_reply(
+ config=cfg, to=user,
+ subject="A0 Email Test [a0-test123]",
+ body="Test email from Agent Zero. If you see this, SMTP works.",
+ )
+ print(f"[{'OK' if ok else 'FAIL'}] SMTP send")
+
+ if not ok:
+ return
+
+ # Step 4: Wait for email to arrive, then fetch
+ print("\n--- Waiting 5s for email delivery ---")
+ await asyncio.sleep(5)
+
+ client2 = await connect_imap(
+ server="imap.gmail.com", port=993,
+ username=user, password=password,
+ )
+
+ messages2, new_uid2 = await fetch_new(
+ client2, "/tmp/email_test_attachments",
+ last_uid=baseline_uid, max_messages=5,
+ )
+ print(f"[OK] Fetch new since UID {baseline_uid}: {len(messages2)} messages")
+ for msg in messages2:
+ print(f" From: {msg.sender}")
+ print(f" Subject: {msg.subject}")
+ print(f" Body: {msg.body[:80]}...")
+ print()
+
+ print(f"[OK] New last_uid: {new_uid2}")
+
+ # Step 5: Fetch again with updated UID — should be 0
+ messages3, _ = await fetch_new(
+ client2, "/tmp/email_test_attachments",
+ last_uid=new_uid2, max_messages=5,
+ )
+ print(f"[OK] Re-fetch since UID {new_uid2}: {len(messages3)} messages (expected 0)")
+
+ await disconnect_imap(client2)
+ print("\n--- ALL TESTS PASSED ---")
+
+
+async def main():
+ user = os.environ.get("EMAIL_USER", "")
+ password = os.environ.get("EMAIL_PASS", "")
+
+ if not user or not password:
+ print("Set EMAIL_USER and EMAIL_PASS environment variables")
+ print("Example: [email protected] EMAIL_PASS=xxxx python ...")
+ sys.exit(1)
+
+ await test_full_flow(user, password)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/plugins/_email_integration/webui/config.html b/plugins/_email_integration/webui/config.html
new file mode 100644
index 000000000..9d5b54cac
--- /dev/null
+++ b/plugins/_email_integration/webui/config.html
@@ -0,0 +1,234 @@
+<html>
+<head>
+ <title>Email Integration</title>
+</head>
+
+<body>
+ <div x-data="{
+ get handlers() { return config?.handlers || [] },
+ editing: null,
+ add_handler() {
+ if (!config.handlers) config.handlers = [];
+ config.handlers.push({
+ name: 'handler_' + (config.handlers.length + 1),
+ enabled: false,
+ account_type: 'imap',
+ imap_server: '',
+ imap_port: 993,
+ smtp_server: '',
+ smtp_port: 587,
+ username: '',
+ password: '',
+ poll_mode: 'seconds',
+ poll_interval_seconds: 15,
+ poll_interval_cron: '*/2 * * * *',
+ sender_whitelist: [],
+ project: '',
+ dispatcher_instructions: '',
+ agent_instructions: ''
+ });
+ this.editing = config.handlers.length - 1;
+ },
+ remove_handler(idx) {
+ config.handlers.splice(idx, 1);
+ this.editing = null;
+ },
+ whitelist_text(handler) {
+ return (handler.sender_whitelist || []).join(', ');
+ },
+ set_whitelist(handler, val) {
+ handler.sender_whitelist = val.split(',').map(s => s.trim()).filter(s => s);
+ }
+ }">
+ <template x-if="config">
+ <div>
+ <div class="section-title">Email Integration</div>
+ <div class="section-description">
+ Configure email handlers to communicate with Agent Zero via email.
+ Each handler connects to an email account and polls for new messages.
+ </div>
+
+ <!-- Handler list -->
+ <template x-for="(handler, idx) in handlers" :key="idx">
+ <div style="border: 1px solid var(--border-color, #333); border-radius: 8px; padding: 12px; margin-bottom: 8px; margin-top: 8px;">
+
+ <!-- Header row -->
+ <div style="display: flex; justify-content: space-between; align-items: center; cursor: pointer;"
+ @click="editing = editing === idx ? null : idx">
+ <div>
+ <span style="font-weight: bold;" x-text="handler.name"></span>
+ <span style="opacity: 0.6; margin-left: 8px;" x-text="handler.enabled ? 'Enabled' : 'Disabled'"></span>
+ </div>
+ <div style="display: flex; gap: 8px; align-items: center;">
+ <label @click.stop style="display: flex; align-items: center; gap: 4px;">
+ <input type="checkbox" x-model="handler.enabled" />
+ </label>
+ <button class="btn-cancel" @click.stop="remove_handler(idx)" style="padding: 2px 10px; font-size: 0.8rem;">Remove</button>
+ </div>
+ </div>
+
+ <!-- Expanded editor -->
+ <template x-if="editing === idx">
+ <div style="margin-top: 16px;">
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Handler Name</div>
+ </div>
+ <div class="field-control">
+ <input type="text" x-model="handler.name" placeholder="e.g. support" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Account Type</div>
+ </div>
+ <div class="field-control">
+ <select x-model="handler.account_type">
+ <option value="imap">IMAP</option>
+ <option value="exchange">Exchange</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">IMAP Server</div>
+ </div>
+ <div class="field-control">
+ <input type="text" x-model="handler.imap_server" placeholder="imap.gmail.com" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">IMAP Port</div>
+ </div>
+ <div class="field-control">
+ <input type="number" x-model.number="handler.imap_port" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">SMTP Server</div>
+ </div>
+ <div class="field-control">
+ <input type="text" x-model="handler.smtp_server" placeholder="smtp.gmail.com" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">SMTP Port</div>
+ </div>
+ <div class="field-control">
+ <input type="number" x-model.number="handler.smtp_port" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Username</div>
+ </div>
+ <div class="field-control">
+ <input type="text" x-model="handler.username" placeholder="[email protected]" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Password</div>
+ </div>
+ <div class="field-control">
+ <input type="password" x-model="handler.password" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Poll Mode</div>
+ </div>
+ <div class="field-control">
+ <select x-model="handler.poll_mode">
+ <option value="seconds">Interval (seconds)</option>
+ <option value="cron">Cron expression</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="field" x-show="handler.poll_mode === 'seconds'">
+ <div class="field-label">
+ <div class="field-title">Poll Interval (seconds)</div>
+ <div class="field-description">How often to check for new emails</div>
+ </div>
+ <div class="field-control">
+ <input type="number" x-model.number="handler.poll_interval_seconds" min="5" placeholder="15" />
+ </div>
+ </div>
+
+ <div class="field" x-show="handler.poll_mode !== 'seconds'">
+ <div class="field-label">
+ <div class="field-title">Cron Expression</div>
+ <div class="field-description">e.g. */2 * * * * for every 2 minutes</div>
+ </div>
+ <div class="field-control">
+ <input type="text" x-model="handler.poll_interval_cron" placeholder="*/2 * * * *" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Sender Whitelist</div>
+ <div class="field-description">Comma-separated. Empty = allow all. Wildcards supported (e.g. *@company.com)</div>
+ </div>
+ <div class="field-control">
+ <input type="text" :value="whitelist_text(handler)" @input="set_whitelist(handler, $event.target.value)" placeholder="*@company.com, [email protected]" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Project</div>
+ <div class="field-description">Project to activate for email chats (optional)</div>
+ </div>
+ <div class="field-control">
+ <input type="text" x-model="handler.project" placeholder="my-project" />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Dispatcher Instructions</div>
+ <div class="field-description">Extra instructions for the AI that routes emails to chats</div>
+ </div>
+ <div class="field-control">
+ <textarea x-model="handler.dispatcher_instructions" rows="3" placeholder="e.g. Always start a new chat for emails from support@..."></textarea>
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Agent Instructions</div>
+ <div class="field-description">Extra instructions for the agent in email chats</div>
+ </div>
+ <div class="field-control">
+ <textarea x-model="handler.agent_instructions" rows="3" placeholder="e.g. Always respond in formal English..."></textarea>
+ </div>
+ </div>
+
+ </div>
+ </template>
+ </div>
+ </template>
+
+ <button class="btn-ok" @click="add_handler()" style="margin-top: 8px;">
+ Add Handler
+ </button>
+ </div>
+ </template>
+ </div>
+</body>
+
+</html>