Skip to content

Agent Zero AI framework

feat(email): add file attachment support for email replies via RFC

linuztx6ab8680bf880
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
index 9cf047f85..0375f9f02 100644
--- a/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py
+++ b/plugins/_email_integration/extensions/python/job_loop/_10_email_poll.py
@@ -1,3 +1,5 @@
+"""Per-handler email poll loop with configurable seconds/cron intervals."""
+
import asyncio
from crontab import CronTab
@@ -15,6 +17,10 @@ MIN_INTERVAL = 5
_poll_tasks: dict[str, asyncio.Task] = {}
+# ------------------------------------------------------------------
+# Poll interval
+# ------------------------------------------------------------------
+
def _get_sleep_seconds(handler_cfg: dict) -> float:
mode = handler_cfg.get("poll_mode", "seconds")
if mode == "cron":
@@ -26,6 +32,10 @@ def _get_sleep_seconds(handler_cfg: dict) -> float:
return max(handler_cfg.get("poll_interval_seconds", DEFAULT_INTERVAL), MIN_INTERVAL)
+# ------------------------------------------------------------------
+# Per-handler poll loop
+# ------------------------------------------------------------------
+
async def _handler_poll_loop(handler_name: str):
from plugins._email_integration.helpers.handler import (
_poll_single_handler,
@@ -56,6 +66,10 @@ async def _handler_poll_loop(handler_name: str):
await asyncio.sleep(sleep_sec)
+# ------------------------------------------------------------------
+# Extension entry point
+# ------------------------------------------------------------------
+
class EmailAutoPoll(Extension):
async def execute(self, **kwargs):
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
index b1a14a4ba..9eeed9b5c 100644
--- 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
@@ -1,7 +1,10 @@
+"""Auto-send email reply when agent responds in an email session."""
+
import asyncio
from helpers.extension import Extension
+from helpers.print_style import PrintStyle
from agent import AgentContext, LoopData
-from plugins._email_integration.helpers.dispatcher import CTX_EMAIL_HANDLER
+from plugins._email_integration.helpers.dispatcher import CTX_EMAIL_HANDLER, CTX_EMAIL_ATTACHMENTS
class EmailAutoReply(Extension):
@@ -14,17 +17,25 @@ class EmailAutoReply(Extension):
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))
+ attachments = context.data.pop(CTX_EMAIL_ATTACHMENTS, [])
+ if attachments:
+ PrintStyle.info(f"Email: sending reply with {len(attachments)} attachment(s)")
+ asyncio.create_task(self._send_reply(context, response_text, attachments))
- async def _send_reply(self, context: AgentContext, response_text: str):
+ async def _send_reply(
+ self, context: AgentContext, response_text: str, attachments: list[str],
+ ):
from plugins._email_integration.helpers.handler import send_email_reply
- await send_email_reply(context, response_text)
+ await send_email_reply(context, response_text, attachments)
+
+# ------------------------------------------------------------------
+# Helpers
+# ------------------------------------------------------------------
def _extract_last_response(context: AgentContext) -> str:
with context.log._lock:
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
index 039534443..b2a8798f5 100644
--- a/plugins/_email_integration/extensions/python/system_prompt/_20_email_context.py
+++ b/plugins/_email_integration/extensions/python/system_prompt/_20_email_context.py
@@ -1,3 +1,5 @@
+"""Inject email conversation context into system prompt for email sessions."""
+
from helpers.extension import Extension
from agent import LoopData
from plugins._email_integration.helpers.dispatcher import CTX_EMAIL_HANDLER
@@ -14,7 +16,6 @@ class EmailContextPrompt(Extension):
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("fw.email.system_context_reply.md")
system_prompt.append(prompt)
diff --git a/plugins/_email_integration/extensions/python/tool_execute_after/_50_email_attachments.py b/plugins/_email_integration/extensions/python/tool_execute_after/_50_email_attachments.py
new file mode 100644
index 000000000..e7f37bd91
--- /dev/null
+++ b/plugins/_email_integration/extensions/python/tool_execute_after/_50_email_attachments.py
@@ -0,0 +1,25 @@
+"""Intercept response tool to capture email attachments."""
+
+from helpers.extension import Extension
+from helpers.print_style import PrintStyle
+from plugins._email_integration.helpers.dispatcher import CTX_EMAIL_HANDLER, CTX_EMAIL_ATTACHMENTS
+
+
+class EmailResponseAttachments(Extension):
+
+ async def execute(self, tool_name: str = "", **kwargs):
+ if tool_name != "response":
+ return
+ if not self.agent:
+ return
+ if not self.agent.context.data.get(CTX_EMAIL_HANDLER):
+ return
+
+ tool = self.agent.loop_data.current_tool
+ if not tool:
+ return
+
+ attachments = tool.args.get("attachments", [])
+ if attachments:
+ self.agent.context.data[CTX_EMAIL_ATTACHMENTS] = attachments
+ PrintStyle.info(f"Email: queued {len(attachments)} attachment(s)")
diff --git a/plugins/_email_integration/helpers/attachment_reader.py b/plugins/_email_integration/helpers/attachment_reader.py
new file mode 100644
index 000000000..4d7ca109f
--- /dev/null
+++ b/plugins/_email_integration/helpers/attachment_reader.py
@@ -0,0 +1,40 @@
+"""
+Read attachment files from execution runtime.
+
+No agent/tool dependencies.
+"""
+
+import base64
+import os
+from typing import TypedDict
+
+
+# ------------------------------------------------------------------
+# Data models
+# ------------------------------------------------------------------
+
+class AttachmentData(TypedDict):
+ name: str
+ content_b64: str
+ error: str
+
+
+# ------------------------------------------------------------------
+# File reader
+# ------------------------------------------------------------------
+
+def read_attachment(path: str) -> AttachmentData:
+ try:
+ if not os.path.isfile(path):
+ return AttachmentData(
+ name="", content_b64="", error=f"file not found: {path}")
+ name = os.path.basename(path)
+ with open(path, "rb") as f:
+ content = f.read()
+ return AttachmentData(
+ name=name,
+ content_b64=base64.b64encode(content).decode(),
+ error="",
+ )
+ except Exception as e:
+ return AttachmentData(name="", content_b64="", error=str(e))
diff --git a/plugins/_email_integration/helpers/dispatcher.py b/plugins/_email_integration/helpers/dispatcher.py
index b04d7924c..1923a8192 100644
--- a/plugins/_email_integration/helpers/dispatcher.py
+++ b/plugins/_email_integration/helpers/dispatcher.py
@@ -1,4 +1,8 @@
-"""Email dispatch logic — routes inbound emails to chats. No agent deps in pure helpers."""
+"""
+Email dispatch logic — routes inbound emails to chats.
+
+No agent deps in pure helpers.
+"""
import re
from dataclasses import dataclass
@@ -15,6 +19,7 @@ CTX_EMAIL_THREAD_ID = "_email_thread_id"
CTX_EMAIL_SUBJECT = "_email_subject"
CTX_EMAIL_MESSAGE_ID = "_email_message_id"
CTX_EMAIL_REFERENCES = "_email_references"
+CTX_EMAIL_ATTACHMENTS = "_email_response_attachments"
DispatchAction = Literal["new_chat", "continue_chat", "intervene_soft", "intervene_hard"]
diff --git a/plugins/_email_integration/helpers/handler.py b/plugins/_email_integration/helpers/handler.py
index 332ea5cdf..e20c5d29b 100644
--- a/plugins/_email_integration/helpers/handler.py
+++ b/plugins/_email_integration/helpers/handler.py
@@ -1,11 +1,16 @@
-"""Email handler — orchestrates poll, dispatch, and reply. Requires agent context."""
+"""
+Email handler — orchestrates poll, dispatch, and reply.
+
+Requires agent context.
+"""
import asyncio
+import base64
import json
import os
from agent import Agent, AgentContext, UserMessage
-from helpers import guids, plugins, files
+from helpers import guids, plugins, files, runtime
from helpers import message_queue as mq
from helpers.persist_chat import save_tmp_chat
from helpers.print_style import PrintStyle
@@ -349,7 +354,11 @@ def _build_user_message(agent: Agent, msg: InboundMessage, handler_cfg: dict) ->
# Reply sending (called from process_chain_end extension)
# ------------------------------------------------------------------
-async def send_email_reply(context: AgentContext, response_text: str):
+async def send_email_reply(
+ context: AgentContext,
+ response_text: str,
+ attachments: list[str] | None = None,
+):
handler_name = context.data.get(disp.CTX_EMAIL_HANDLER)
if not handler_name:
return
@@ -374,6 +383,9 @@ async def send_email_reply(context: AgentContext, response_text: str):
password=cfg.get("password", ""),
)
+ # Read attachment files via RFC (they live in the execution runtime)
+ attachment_data = await _read_attachments_via_rfc(attachments)
+
await send_reply(
config=smtp_cfg,
to=sender,
@@ -381,9 +393,36 @@ async def send_email_reply(context: AgentContext, response_text: str):
body=response_text,
in_reply_to=original_msg_id,
references=references,
+ attachments=attachment_data or None,
)
+# ------------------------------------------------------------------
+# Attachment reading (via RFC into execution runtime)
+# ------------------------------------------------------------------
+
+async def _read_attachments_via_rfc(
+ paths: list[str] | None,
+) -> list[tuple[str, bytes]]:
+ if not paths:
+ return []
+
+ from plugins._email_integration.helpers.attachment_reader import read_attachment
+
+ results: list[tuple[str, bytes]] = []
+ for path in paths:
+ data = await runtime.call_development_function(read_attachment, path)
+ if data["error"]:
+ PrintStyle.error(f"Email attachment: {data['error']}")
+ continue
+ results.append((data["name"], base64.b64decode(data["content_b64"])))
+ return results
+
+
+# ------------------------------------------------------------------
+# Config lookup
+# ------------------------------------------------------------------
+
def _get_handler_config(handler_name: str) -> dict | None:
config = plugins.get_plugin_config(PLUGIN_NAME) or {}
handlers = config.get("handlers", [])
diff --git a/plugins/_email_integration/helpers/smtp_client.py b/plugins/_email_integration/helpers/smtp_client.py
index 58beb7066..c7a3b53a5 100644
--- a/plugins/_email_integration/helpers/smtp_client.py
+++ b/plugins/_email_integration/helpers/smtp_client.py
@@ -1,4 +1,8 @@
-"""SMTP email sender. No agent/tool dependencies."""
+"""
+SMTP email sender.
+
+No agent/tool dependencies.
+"""
import asyncio
import smtplib
@@ -7,12 +11,15 @@ 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
+# ------------------------------------------------------------------
+# Data models
+# ------------------------------------------------------------------
+
@dataclass
class SmtpConfig:
server: str
@@ -22,6 +29,10 @@ class SmtpConfig:
use_tls: bool = True
+# ------------------------------------------------------------------
+# Send reply
+# ------------------------------------------------------------------
+
async def send_reply(
config: SmtpConfig,
to: str,
@@ -29,7 +40,7 @@ async def send_reply(
body: str,
in_reply_to: str = "",
references: str = "",
- attachments: list[str] | None = None,
+ attachments: list[tuple[str, bytes]] | None = None,
) -> bool:
loop = asyncio.get_event_loop()
@@ -38,16 +49,13 @@ async def send_reply(
if attachments:
msg.attach(MIMEText(body, "plain", "utf-8"))
- for path in attachments:
- if not os.path.isfile(path):
- continue
+ for filename, content in attachments:
part = MIMEBase("application", "octet-stream")
- with open(path, "rb") as f:
- part.set_payload(f.read())
+ part.set_payload(content)
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
- f"attachment; filename={os.path.basename(path)}",
+ f"attachment; filename={filename}",
)
msg.attach(part)
diff --git a/plugins/_email_integration/prompts/fw.email.system_context_reply.md b/plugins/_email_integration/prompts/fw.email.system_context_reply.md
index 8d43c4632..d53d39a40 100644
--- a/plugins/_email_integration/prompts/fw.email.system_context_reply.md
+++ b/plugins/_email_integration/prompts/fw.email.system_context_reply.md
@@ -4,3 +4,16 @@ 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
+
+### Sending file attachments
+to attach files to your email reply, add `attachments` list with absolute file paths to the response tool:
+~~~json
+{
+ ...
+ "tool_name": "response",
+ "tool_args": {
+ "text": "Here is the file you requested.",
+ "attachments": ["/path/to/file.txt"]
+ }
+}
+~~~