Skip to content
Back to search

agenticmail

Email, SMS & phone-call infrastructure for AI agents — send and receive real email and text messages, and place agent-driven outbound voice calls, all programmatically

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/agenticmail/agenticmail with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/agenticmail/agenticmail'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/agenticmail--agenticmail/badge.svg)](/listings/agenticmail--agenticmail)

HTML

<a href="/listings/agenticmail--agenticmail"><img src="/api/listings/agenticmail--agenticmail/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

> **Heads-up for anyone running `agenticmail setup-email` (or telling Claude / Codex to do it for them).** Once that command succeeds, your sub-agents are reachable from the public internet via Gmail / Outlook plus-addressing. This is *the design* — not a bug — but the implications surprise some operators:

- **Every sub-agent has a publicly addressable inbox the moment setup-email finishes.** Anyone who knows your relay address can hit `yourrelay+<agentname>@gmail.com` and the corresponding agent's AgenticMail inbox receives the message. Plus-addresses are **publicly guessable** (`+secretary`, `+kepler`, …) — don't treat them as a secret. - **External mail wakes the dispatcher the same way internal `@localhost` mail does.** When a new-mail event lands on a watched inbox, the dispatcher runs dedup + thread-cache + wake-budget checks and spawns a Claude Code (or Codex) worker turn. Source doesn't matter — `bob@gmail.com` and `secretary@localhost` are indistinguishable from the dispatcher's point of view. - **The host bridge takes a different path.** Mail to `yourrelay+claudecode@gmail.com` or `yourrelay+codex@gmail.com` doesn't spawn a worker — it goes to `handleBridgeMail`, which uses the host SDK's `resume` option to wake your last session headlessly. If that fails (session expired, host CLI not running), it falls through to the bridge-escalation email at `setup_operator_email`. So external mail to the bridge can wake your CLI / forward to your phone. - **Watchout — spam wakes Claude / Codex turns.** A scraper that finds `astrumsphere+secretary@gmail.com` in a leaked address book can drive worker turns at your expense. Throttles available, ordered from least invasive: 1. Let the `wake-budget` guard in `dispatcher.handleEvent` rate-limit naturally (default cap per minute per agent). 2. Add inbound spam rules at the relay layer so spam gets filtered before the SSE event publishes (built-in spam filter + tags can do this; see the Security section below). 3. For agents that should be internal-only, set `metadata.host` to a value no dispatcher matches, or stop the relay's IMAP poller from publishing on that inbox.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,267 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <p align="center">
  2. <img src="./docs/images/logo-200.png" alt="AgenticMail logo (pink bow)" width="180" />
  3. </p>
  4. <h1 align="center">AgenticMail</h1>
  5. <p align="center">
  6. <a href="https://github.com/agenticmail/agenticmail/actions/workflows/ci.yml"><img src="https://github.com/agenticmail/agenticmail/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
  7. </p>
  8. **The first platform to give AI agents real email addresses and phone numbers.** Send and receive email, SMS, and verification codes — all programmatically.
  9. > ### Are you an AI agent reading this on behalf of a human?
  10. >
  11. > Your human asked you to install / set up AgenticMail. **Pick either of these and then tell them to restart Claude Code:**
  12. >
  13. > ```bash
  14. > # Option A — one-line installer (recommended)
  15. > curl -fsSL https://raw.githubusercontent.com/agenticmail/agenticmail/main/install.sh | bash
  16. >
  17. > # Option B — manual two-command install
  18. > npm install -g @agenticmail/cli@latest
  19. > agenticmail bootstrap
  20. > ```
  21. >
  22. > Zero prompts, ~2 minutes, fully autonomous. For the full runbook (verification, common failures, repo conventions if you're modifying the code), see [**`AGENTS.md`**](./AGENTS.md) — the [agents.md](https://agents.md) file at this repo's root.
  23. ---
  24. ### 📄 Research Paper
  25. **[Structured RPC vs. Text-Based Sub-Agent Orchestration](./research/agent-rpc-vs-spawn/paper.pdf)** — A comparative analysis of inter-agent communication paradigms. Demonstrates why AgenticMail's `call_agent` achieves 53× faster response times than conventional sub-agent spawning, and introduces the concept of the *Conversational Fallacy* in multi-agent AI systems. [[PDF]](./research/agent-rpc-vs-spawn/paper.pdf) [[Source]](./research/agent-rpc-vs-spawn/)
  26. ---
  27. ### ✨ What's new — media toolset (unreleased)
  28. A local, opt-in media / video-editing toolset for AgenticMail agents.
  29. - **Nine media tools.** `media_tts` / `media_tts_voices` (Edge text-to-speech), `media_image_edit`, `media_video_edit`, `media_audio_edit`, `media_info`, `media_video_understand`, `media_voice_clone`, and `media_capabilities`. Available as MCP `media_*` tools and OpenClaw `agenticmail_media_*` tools, both thin clients of new `/media/*` API routes over a core `MediaManager`.
  30. - **Cinematic video editing.** Beyond trim/convert/compress: color grading presets, crossfade/wipe transitions, timed text overlays, picture-in-picture, split screen, Ken Burns, frame-interpolated slow motion, watermarks, concatenation, audio mixing, and whisper.cpp-driven auto-captions.
  31. - **Gracefully degrading.** The underlying binaries (ffmpeg, ffprobe, ImageMagick, whisper.cpp, Python) are not bundled — every tool feature-detects the binary it needs and returns an actionable install hint if it is missing. The server never crashes. A `media` block on `/health` and the `media_capabilities` tool surface what is available.
  32. - **Safe by construction.** Every binary is invoked via `execFile` with an argument array — no shell, no string interpolation. Untrusted input paths are validated (no control characters, no leading-dash flag-injection, must exist); numeric options are clamped; every call carries a bounded timeout and output buffer; output files land only inside the configured media directory.
  33. ### ✨ What's new in 0.9.54
  34. Twilio joins 46elks as a phone transport provider.
  35. - **Pick your carrier.** `PhoneTransportProvider` is now `46elks` or `twilio` — chosen at phone setup. 46elks behaviour is unchanged; Twilio is at full parity (outbound call-control + realtime voice).
  36. - **Twilio call-control.** Outbound calls via the Twilio `Calls.json` REST API, TwiML webhooks, status-callback cost tracking. Inbound webhooks are verified with the `X-Twilio-Signature` header (HMAC-SHA1, timing-safe, fail-closed) on top of the per-mission token.
  37. - **Twilio realtime voice.** A Twilio Media Streams ↔ OpenAI Realtime bridge. `RealtimeVoiceBridge` was generalised behind a `RealtimeTransportAdapter` seam — one bridge serves both carriers, function-calling / barge-in / transcript logic written once. Twilio audio is G.711 µ-law @ 8 kHz and the OpenAI session uses `audio/pcmu`, so a Twilio call needs no transcoding. A `<Connect><Stream>` connects to `/api/agenticmail/calls/twilio-stream`.
  38. 1038 tests pass; full build green. The live Twilio ↔ OpenAI call path still needs an operator smoke-test before the npm publish.
  39. ### ✨ Earlier — 0.9.53
  40. Realtime voice tools + a Telegram channel.
  41. - **The voice agent can now use tools mid-call.** The OpenAI Realtime session declares `session.tools`; `RealtimeVoiceBridge` dispatches the model's function calls through an injected `ToolExecutor`, returns `function_call_output`, and keeps the phone line warm during slow tools with a safety-net timeout + an in-flight call cap.
  42. - **`ask_operator` — human-in-the-loop on a live call.** The agent records an operator query on the mission, notifies the operator (channel-agnostic; default email), polls up to ~5 min, and resumes with the answer. If the caller hangs up while a query is pending, the mission is flagged for **callback-on-disconnect** — once the operator answers, it re-dials with a continuity task.
  43. - **Lookup tools.** `web_search` (keyless DuckDuckGo, results fenced as untrusted content), `recall_memory` (the agent's universal memory), `get_datetime`. Plus agent-key-scoped operator-query API endpoints.
  44. - **Telegram channel.** A user registers a Telegram bot token, links a chat, and can message their AgenticMail agent — and get replies — over Telegram. The inbound webhook authenticates with a constant-time secret-token compare; it also carries `ask_operator` notifications and approvals.
  45. - **Security.** web_search output is fenced as untrusted before it reaches the model; operator email replies are verified against `operatorEmail`; Telegram bot tokens are encrypted at rest and redacted from logs; new SQL is parameterized.
  46. 996 tests pass; full build green. The live OpenAI ⇄ 46elks call path and live Telegram delivery still need an operator smoke-test before the npm publish.
  47. ### ✨ Earlier — 0.9.52
  48. Realtime voice + OpenClaw memory.
  49. - **Realtime voice bridge.** A phone mission can now hold a live conversation. `RealtimeVoiceBridge` (`@agenticmail/core`) wires an OpenAI Realtime (`gpt-realtime`) session to a 46elks realtime-media WebSocket: caller audio (PCM16 @ 24 kHz) is relayed to OpenAI, synthesised speech comes back as `response.output_audio.delta` and is relayed to 46elks, server-side VAD handles turn-taking, and caller barge-in fires a 46elks `interrupt`. 46elks streams a call to the new `/api/agenticmail/calls/realtime` WebSocket endpoint, which matches the connection to its mission by 46elks `callid` and runs the bridge. Set `OPENAI_API_KEY` (env or `config.json`) to enable it.
  50. - **Memory in the voice session.** Before the call starts, the agent's persistent memory is rendered with `generateMemoryContext()` and folded into the Realtime session `instructions` — the model is told to treat it as its *own* long-term knowledge, so the call is continuous with everything the agent has learned elsewhere.
  51. - **OpenClaw memory tools.** `agenticmail_memory`, `agenticmail_memory_reflect`, `agenticmail_memory_context`, and `agenticmail_memory_stats` bring the universal per-agent memory to OpenClaw agents — 69 → 73 tools.
  52. - **Bridge hardening.** Per-frame audio size cap (an oversized frame is dropped, never forwarded), bounded pre-connect buffer, fail-closed connection auth (timing-safe token compare; no unknown-mission-vs-wrong-token oracle), and a terminal-state guard so a late event can't resurrect a finished mission.
  53. The end-to-end voice path needs a live `OPENAI_API_KEY` and a provisioned 46elks websocket number — the bridge logic, memory injection, and the WebSocket upgrade/auth glue are unit-tested with mocked sockets, but the live call must be smoke-tested by the operator.
  54. ### ✨ Earlier — 0.9.51
  55. The universal memory release. Every agent now has a persistent, evolving memory — categorised, confidence-decaying, BM25F-searchable knowledge that survives across every conversation, the way a human employee learns on the job.
  56. - **`AgentMemoryManager`** (`@agenticmail/core`) — CRUD, text recall, 9 memory categories, importance levels, confidence that decays for unaccessed entries, access tracking, pruning, and `generateMemoryContext()` which ranks + renders memory as a markdown block for prompt injection. Backed by a zero-dependency BM25F search index and an `agent_memory` table. Ported from the AgenticMail Enterprise memory engine, org-stripped — memory is personal to each agent.
  57. - **Memory API** — `/memory` (set / list / search / get / delete), `/memory/reflect`, `/memory/context`, `/memory/stats`. Every endpoint is scoped to the authenticated agent; an agent can only ever read or write its own memory.
  58. - **MCP tools** — `memory`, `memory_reflect`, `memory_context`, `memory_stats` so any MCP client can give its agent durable memory.
  59. - **Agent-deletion cleanup** — deleting an agent purges its `agent_memory` rows; no orphaned memory is left behind.
  60. ### ✨ Earlier — 0.9.1
  61. The visibility release — closes every "what just happened?" gap from 0.9.0.
  62. - **Lone wakes fire immediately.** 0.9.0's debounce window blocked even single replies for 30 s, making the dispatcher look dead. Leading-edge fire + trailing-edge coalesce now: first event for a `(agent, thread)` spawns instantly; bursts within the window collapse into one trailing wake.
  63. - **Dispatcher process heartbeat.** `check_activity` now shows `dispatcher: { state: 'alive' | 'unhealthy' | 'missing', uptimeMs, channels, coalesceQueueSize, ... }`. The host can finally answer "is the dispatcher up?" in one query.
  64. - **Skipped-wake ring buffer.** Every filter decision (thread-closed, allowlist-excluded, wake-on-cc, budget-exhausted) is posted with a reason; `check_activity` surfaces the last 100. No more "did my mail land? did it skip?" guessing.
  65. - **Per-agent `wake_on_cc: false` flag.** Coder agents can register a preference: never wake when only on Cc, regardless of sender. `PATCH /accounts/:id/wake-on-cc`.
  66. - **Display-name regex fix in `deriveDefaultWakeList`.** Senders using `"Vesper <vesper@localhost>"` form no longer fall through to "no allowlist → wake everyone".
  67. - **Web UI shows To / Cc / Bcc as separate labeled rows** in the message view (previously lumped under one `to:` line).
  68. - **`docs/wake-patterns.md`** documents every wake shape + 5 recommended patterns.
  69. ### ✨ Earlier — 0.9.0
  70. The wake-context release. Multi-agent thread cost goes from linear-in-thread-length to roughly flat.
  71. - **Layered wake-context system.** Every wake used to re-read the entire thread from scratch (12 messages × ~1 KB = 12 KB of token spend just to rehydrate, before any reasoning). Now the dispatcher prepends two blocks to every wake prompt: **Layer 1 — ThreadCache** (envelopes + previews of the last 10 messages, shared across CC'd agents) and **Layer 2 — AgentMemory** (a markdown file each agent writes at end-of-wake describing its own commitments and last actions). Agents read the new event + these two blocks and decide; they don't `read_email` prior history. New MCP tools `save_thread_memory` and `get_thread_id`.
  72. - **`wake` default flipped from "everyone CC'd" → "To: only".** Mirrors the email convention: To is for action, CC is for awareness. CC'd local agents still receive the mail in their inbox but don't get a Claude turn unless explicitly named in `wake`. Opt back into the old behaviour with `wake: 'all'`.
  73. - **Wake coalescing.** Within 30 s for the same `(agent, thread)`, multiple wake events collapse into ONE Claude turn. A burst of 4 quick replies becomes one Claude wake that sees all four in a `coalesced` batch prompt. Wake-budget charges once. Configurable via `wakeCoalesceMs`.
  74. Together these eliminate the "wake-thrash" failure mode where an agent fired 4 near-identical status reports because a designer sent 4 replies in 2 minutes.
  75. ### ✨ Earlier — 0.8.31
  76. - **Compact-and-continue** — workers can now run across multiple SDK turns. On a context-overflow error the dispatcher synthesises a breadcrumb checkpoint from the captured log, builds a "resuming after context reset" continuation prompt, and loops (capped at 4 iterations).
  77. - **Typed task contracts** — `call_agent` / `POST /tasks/assign` accept an `outputSchema` (JSON Schema, draft-7 subset). `submit_result` validates against it; mismatches return 400 with the validator errors so the worker can retry with a corrected shape.
  78. - **Delete + Move-to-Spam buttons** in the message view; **Compose auto-saves to Drafts** every 2s.
  79. - **`All Mail` folder hides itself** on servers that don't have one (Stalwart, most non-Gmail). Select-all checkbox now wires through.
  80. - **Logo background stripped** — bow PNG is now RGBA with proper transparency.
  81. ### ✨ Earlier — 0.8.29
  82. - **Star button wired** — clicking the star toggles IMAP's `\Flagged` flag via the new `POST /mail/messages/:uid/star` endpoint. Backed by `MailReceiver.setStarred` in `@agenticmail/core`. Optimistic UI; revert on failure.
  83. - **Gmail-compact list UX** — single 36 px rows (was 64 px stacked), subject + preview on one truncated line separated by an em-dash, leading checkbox column, sticky list-toolbar with select-all + refresh + count. Same layout for every folder.
  84. - **Compose button** down to 48 px (Gmail's actual size); the giant pink pill is gone.
  85. ### ✨ Earlier — 0.8.27
  86. - **Folder bug fix** — Sent / Drafts / Spam / Trash were returning empty in the web UI because hard-coded folder names didn't match Stalwart's actual IMAP names (e.g. `Sent Items` not `Sent`). Now auto-discovered per agent and matched against every common server convention (Stalwart, Gmail, Outlook, macOS Mail).
  87. - **Two-line preview** on every list row — web UI uses `/mail/digest?folder=…` everywhere instead of `/mail/inbox` (no preview) + `/mail/folders/:folder` (no preview).
  88. - **URL reflects current folder** — hash router now uses `#/folder/<id>` (sent, drafts, spam, …). Back/forward works, URLs are shareable, refresh stays put.
  89. - **Stop hook output rewritten** — terser, audience-neutral, includes body preview. Drops the instruction-leakage from 0.8.25/26.
  90. ### ✨ Earlier — 0.8.25
  91. - **Workers can now run for hours** — dropped the 30-min hard timeout. Each worker writes a per-turn log at `~/.agenticmail/worker-logs/<id>.log`, posts heartbeats every 30 s, and runs in its own isolated cwd so parallel agents don't clobber each other's output. New MCP tool **`tail_worker`** to read a running worker's log live; `check_activity` now shows last tool used, turn count, and a `stale` flag (no auto-eviction).
  92. - **Autonomous-mode awareness** — the mail hook now registers on the **Stop** event too. Long headless Claude Code runs (no user prompts firing for hours) finally see teammate replies — the hook returns `decision: 'block'` at turn boundaries when the bridge inbox has new mail, forcing Claude to continue with the new-mail summary in context. Closes the follow-up that 0.8.23 filed.
  93. - **Fixed `agenticmail-mail-hook: command not found` errors** — hook is now registered with an absolute path resolved at install time. Resilient to any `$PATH` configuration; old installs auto-heal on the next `agenticmail claudecode` run.
  94. - **Web UI fixes** — `(m.flags ?? []).includes is not a function` crash gone; sidebar folders (Sent / Drafts / Spam / Trash) now load their real IMAP mailboxes instead of all hitting `/mail/inbox`; Cmd+C no longer pops the compose modal; full mobile-responsive layout with an off-canvas sidebar.
  95. - **Official logos** — Claude starburst (from Wikipedia) and the AgenticMail `@` mark from `branding/` now ship bundled and render as the host avatar + topbar / favicon.
  96. - **Selective wake** — `wake: ["alice", "bob"]` on `send_email` / `reply_email` / `forward_email` / `template_send` / `manage_drafts(send)` tells the dispatcher to give a Claude turn only to named agents. The other CC'd recipients still receive the mail but stay asleep. Cuts token cost on large threads by ~10× when used.
  97. - **Thread-close markers** — `[FINAL]`, `[DONE]`, `[CLOSED]`, or `[WRAP]` in a subject tells the dispatcher this thread is done; no more wakes on any reply.
  98. - **`check_activity` MCP tool** — see which agents the dispatcher has woken right now, how long they've been running, and a preview of recent completions. The answer to "did the agent I just emailed actually start working?"
  99. - **Comprehensive markdown rendering** in the shell's email viewer — bold, italic, headings, lists, task lists, tables, fenced code, links, images, HTML entities, depth-colored quote stripes (instead of literal `>>>>`).
  100. - **LLM-tolerant tool inputs** — `batch_mark_read({ uids: "[1,2,3]" })` and other common stringification mistakes now just work; coerced before validation.
  101. - **Wake-budget circuit breaker** — caps per-(agent, thread) wakes at 10 per 24h to stop reply loops and storms.
  102. - **Dedup guidance** — wake prompts now tell agents to check their prior contributions before redoing work.
  103. See [CHANGELOG.md](./CHANGELOG.md) for the full release history.
  104. ---
  105. AgenticMail is a self-hosted communication platform purpose-built for AI agents. It runs a local [Stalwart](https://stalw.art) mail server via Docker, integrates SMS/phone access via Google Voice or 46elks, exposes a REST API with 75+ endpoints, ships a lightweight Gmail-style web UI for human oversight, and works with any MCP-compatible AI client and [OpenClaw](https://github.com/openclaw/openclaw) via plugin. Each agent gets its own email address, phone number, inbox, and API key.
  106. [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
  107. [![Node.js](https://img.shields.io/badge/Node.js-22%2B-green)](https://nodejs.org)
  108. [![agenticmail MCP server](https://glama.ai/mcp/servers/agenticmail/agenticmail/badges/card.svg)](https://glama.ai/mcp/servers/agenticmail/agenticmail)
  109. ---
  110. ## Table of Contents
  111. - [Why AgenticMail?](#why-agenticmail)
  112. - [Features](#features)
  113. - [Architecture](#architecture)
  114. - [Quick Start](#quick-start)
  115. - [CLI Commands](#cli-commands)
  116. - [Gateway Modes](#gateway-modes)
  117. - [Packages](#packages)
  118. - [API Overview](#api-overview)
  119. - [MCP Integration](#mcp-integration)
  120. - [Host Integrations](#host-integrations)
  121. - [OpenClaw Integration](#openclaw-integration)
  122. - [Interactive Shell](#interactive-shell)
  123. - [Security](#security)
  124. - [Configuration](#configuration)
  125. - [Development](#development)
  126. - [License](#license)
  127. ---
  128. ## Why 🎀 AgenticMail?
  129. AI agents need to communicate with the real world. Email is the universal communication protocol — every person and business has an email address. AgenticMail bridges the gap between AI agents and email by providing:
  130. - **Isolated mailboxes** — each agent has its own email address, inbox, and credentials. Agents can't read each other's mail.
  131. - **Internet email connectivity** — two gateway modes to send/receive real email (Gmail relay or custom domain with DKIM/SPF/DMARC).
  132. - **Security guardrails** — outbound scanning prevents agents from leaking API keys, passwords, or PII. Blocked emails require human approval.
  133. - **Agent collaboration** — agents can email each other, assign tasks, and make synchronous RPC calls.
  134. - **SMS / Phone number access** — integrate Google Voice or 46elks for SMS receive/send, verification code extraction, and phone number access for AI agents.
  135. - **Realtime voice calls** — bridge a phone mission to an OpenAI Realtime (`gpt-realtime`) session so an agent can hold a live two-way conversation, with its persistent memory folded into the call.
  136. - **Persistent agent memory** — every agent has a categorised, confidence-decaying, searchable long-term memory that survives across conversations and is injected into prompts and voice sessions.
  137. - **Smart orchestration** — `call_agent` replaces basic sub-agent spawning with auto mode detection, dynamic timeouts, runtime tool discovery, and async execution for long-running tasks.
  138. - **Tool integrations** — 100 MCP tools for any AI client, 89 OpenClaw tools, and a 44-command interactive shell.
  139. - **Self-updating** — `agenticmail update` checks npm, verifies OpenClaw compatibility, and updates both packages automatically.
  140. ---
  141. ## Features
  142. ### Email Operations
  143. - **Send email** with text, HTML, attachments, CC/BCC, reply-to, and custom headers
  144. - **Receive email** via IMAP with real-time SSE event streaming (IMAP IDLE)
  145. - **Reply and forward** with proper In-Reply-To and References headers for threading
  146. - **Search** by sender, subject, body text, date range, read/unread status
  147. - **Folders** — create, list, move messages between folders
  148. - **Batch operations** — mark read/unread, delete, move multiple messages at once
  149. - **Drafts** — save, edit, and send draft emails
  150. - **Templates** — reusable email templates with variable substitution
  151. - **Scheduled sending** — queue emails for future delivery
  152. - **Signatures** — per-agent email signatures
  153. - **Tags** — label and categorize messages
  154. - **Contacts** — manage address book per agent
  155. ### Multi-Agent
  156. - **Account management** — create, list, delete agents with unique email addresses
  157. - **Agent-to-agent email** — agents can email each other directly via `@localhost`
  158. - **Task system** — assign tasks to agents, claim, submit results, track status
  159. - **RPC calls** — synchronous agent-to-agent calls with timeout (long-poll + SSE notification)
  160. - **Agent directory** — discover other agents by name
  161. **You can watch the whole team work in one place with `agenticmail shell`:**
  162. ![agenticmail shell — Solène (QA) and Cassian (developer) coordinating on a build, all visible from the claudecode bridge inbox](./docs/images/shell-inbox.png)
  163. That's a real multi-agent thread captured in the REPL — the host kicked off one email, Solène verified the file Cassian shipped to disk, and every step is sitting there as ordinary mail. No custom orchestration code. Type `agenticmail shell` any time you want to see what your agents have been up to.
  164. ### Gateway (Internet Email)
  165. - **Relay mode** (beginner) — use your existing Gmail or Outlook as a relay. Emails appear as `you+agentname@gmail.com`. Setup takes 2 minutes.
  166. - **Domain mode** (advanced) — custom domain via Cloudflare. Agents send from `agent@yourdomain.com` with full DKIM signing, SPF, and DMARC records.
  167. - Automatic DNS configuration (MX, SPF, DKIM TXT, DMARC, tunnel CNAME)
  168. - Cloudflare Tunnel for secure inbound traffic without exposing ports
  169. - Cloudflare Email Worker for Email Routing (catch-all → worker → AgenticMail)
  170. - Optional Gmail SMTP outbound relay for residential IPs without PTR records
  171. - Domain purchase via Cloudflare Registrar
  172. - DNS backup before any modifications
  173. - Automatic `@domain` email alias for all existing agents
  174. ### What `setup-email` actually exposes — read before connecting a relay
  175. > **Heads-up for anyone running `agenticmail setup-email` (or telling Claude / Codex to do it for them).** Once that command succeeds, your sub-agents are reachable from the public internet via Gmail / Outlook plus-addressing. This is *the design* — not a bug — but the implications surprise some operators:
  176. - **Every sub-agent has a publicly addressable inbox the moment setup-email finishes.** Anyone who knows your relay address can hit `yourrelay+<agentname>@gmail.com` and the corresponding agent's AgenticMail inbox receives the message. Plus-addresses are **publicly guessable** (`+secretary`, `+kepler`, …) — don't treat them as a secret.
  177. - **External mail wakes the dispatcher the same way internal `@localhost` mail does.** When a new-mail event lands on a watched inbox, the dispatcher runs dedup + thread-cache + wake-budget checks and spawns a Claude Code (or Codex) worker turn. Source doesn't matter — `bob@gmail.com` and `secretary@localhost` are indistinguishable from the dispatcher's point of view.
  178. - **The host bridge takes a different path.** Mail to `yourrelay+claudecode@gmail.com` or `yourrelay+codex@gmail.com` doesn't spawn a worker — it goes to `handleBridgeMail`, which uses the host SDK's `resume` option to wake your last session headlessly. If that fails (session expired, host CLI not running), it falls through to the bridge-escalation email at `setup_operator_email`. So external mail to the bridge can wake your CLI / forward to your phone.
  179. - **Watchout — spam wakes Claude / Codex turns.** A scraper that finds `astrumsphere+secretary@gmail.com` in a leaked address book can drive worker turns at your expense. Throttles available, ordered from least invasive:
  180. 1. Let the `wake-budget` guard in `dispatcher.handleEvent` rate-limit naturally (default cap per minute per agent).
  181. 2. Add inbound spam rules at the relay layer so spam gets filtered before the SSE event publishes (built-in spam filter + tags can do this; see the Security section below).
  182. 3. For agents that should be internal-only, set `metadata.host` to a value no dispatcher matches, or stop the relay's IMAP poller from publishing on that inbox.
  183. ### Security
  184. - **Outbound guard** — scans every outgoing email for sensitive data patterns:
  185. - API keys and tokens (AWS, OpenAI, Stripe, GitHub, etc.)
  186. - Passwords and credentials
  187. - Private keys (SSH, PGP, RSA)
  188. - PII patterns (SSN, credit card numbers)
  189. - Internal URLs and configuration data
  190. - Blocked emails are held for human-only approval (agents cannot self-approve)
  191. - **Spam filter** — rule-based scoring engine for inbound email:
  192. - Categories: phishing, scam, malware, commercial spam, social engineering, lottery scam
  193. - Configurable threshold (default: 40)
  194. - Skips internal agent-to-agent emails
  195. - Runs on both relay inbound and SSE event streams
  196. - **Human-only approval flow** — when an agent's email is blocked:
  197. - The agent is informed the email was blocked and told to notify their owner
  198. - The owner receives a notification email with full blocked email content, warnings, and pending ID
  199. - Only the master key holder can approve or reject (`POST /mail/pending/:id/approve`)
  200. - Agents can list and view their own pending emails but **cannot** approve or reject them
  201. - System prompt guidelines instruct agents to inform their owner and wait, never attempt to bypass
  202. - **DKIM/SPF/DMARC** — automatic DNS setup in domain mode for email authentication
  203. - **Rate limiting** — configurable per-endpoint rate limits
  204. ### SMS / Phone Number Access
  205. - **Provider selection** — choose Google Voice legacy forwarding or 46elks direct SMS API/webhooks
  206. - **46elks integration** — send SMS through the provider API and receive inbound SMS through a secret-protected webhook
  207. - **Google Voice integration** — give agents a real phone number via Google Voice
  208. - **Direct Voice web reading** (primary, instant) — reads SMS directly from voice.google.com via browser
  209. - **Email forwarding** (fallback) — Google Voice forwards SMS to email, agent auto-detects and records them during relay polling
  210. - **Separate Gmail polling** — for users whose GV Gmail differs from relay email, runs a dedicated IMAP poll
  211. - **Verification codes** — automatic extraction of OTP/verification codes from SMS (4-8 digit, alphanumeric, Google G-codes)
  212. - **Send SMS** — direct provider API send when configured, or Google Voice web automation instructions for legacy configs
  213. - **Smart setup wizard** — validates Gmail/GV email matching, warns about mismatches, collects separate credentials when needed
  214. ### Realtime Voice Calls
  215. - **Live two-way conversation** — `RealtimeVoiceBridge` bridges a phone mission to an OpenAI Realtime (`gpt-realtime`) session so an agent can actually talk on the call, not just place it
  216. - **Two carriers — 46elks or Twilio** — pick the provider at phone setup; `RealtimeVoiceBridge` is generalised behind a `RealtimeTransportAdapter` so both run through one bridge. 46elks streams to `/api/agenticmail/calls/realtime` (PCM16 @ 24 kHz); Twilio Media Streams connects a `<Connect><Stream>` to `/api/agenticmail/calls/twilio-stream` (G.711 µ-law @ 8 kHz — OpenAI `audio/pcmu`, no transcoding). Server-side VAD for turn-taking, caller barge-in relayed to the carrier.
  217. - **Memory in the call** — the agent's persistent memory is rendered and folded into the Realtime session instructions, so the model speaks with full continuity, as if it had always known those things
  218. - **Mission-tracked** — the bridge resolves the connection to its phone mission by 46elks `callid`, authenticates the connection token, and persists the conversation transcript to the mission
  219. - **Hardened** — per-frame audio size cap, bounded pre-connect buffer, fail-closed connection auth, terminal-state guard
  220. - **Opt-in** — set `OPENAI_API_KEY` to enable; without it, phone missions still place and track calls (call-control only)
  221. - **Tools on the call** — the Realtime session can call functions mid-call: `ask_operator` (human-in-the-loop — pause, ask the operator, resume, or call back on disconnect), `web_search`, `recall_memory`, `get_datetime`
  222. ### Telegram Channel
  223. - **Chat with your agents over Telegram** — register a Telegram bot token, link a chat, and message your AgenticMail agent (and get replies) from Telegram
  224. - **Inbound webhook** — authenticated with a constant-time `X-Telegram-Bot-Api-Secret-Token` compare; uniform 403 on mismatch
  225. - **Operator channel** — carries `ask_operator` notifications and approvals, so a phone agent can reach you on Telegram mid-call
  226. - **Secrets protected** — bot tokens encrypted at rest, redacted from every log line and error
  227. ### Media Toolset
  228. - **Nine local media tools** — `media_tts`, `media_tts_voices`, `media_image_edit`, `media_video_edit`, `media_audio_edit`, `media_info`, `media_video_understand`, `media_voice_clone`, plus `media_capabilities`
  229. - **Text-to-speech** — synthesise speech with Edge TTS (twelve voice presets); returns OGG/Opus, ready to send as a voice note
  230. - **Image editing** — resize, crop, rotate, convert, compress, text overlay, flip, blur, sharpen, grayscale (ImageMagick)
  231. - **Video editing** — basic (trim, GIF, compress, resize, add/remove audio, speed) and cinematic (color grading, transitions, captions, picture-in-picture, split screen, Ken Burns, slow motion, watermark, concatenate, auto-caption) — all via ffmpeg
  232. - **Audio editing** — trim, convert, merge, volume, speed, extract-from-video, reverse, fade
  233. - **Video understanding** — extract frames + transcribe audio (whisper.cpp) into a structured timeline an agent can read before editing
  234. - **Voice cloning** — reference-voice speech synthesis via F5-TTS (you supply the reference sample + transcript)
  235. - **Opt-in / gracefully degrading** — the underlying binaries (ffmpeg, ffprobe, ImageMagick, whisper.cpp, Python) are **not bundled**; every tool feature-detects the binary it needs and returns a clear, actionable install hint when one is absent — the server never crashes. Call `media_capabilities` (or read the `/health` `media` block) to see what is available
  236. - **Safe by construction** — every binary is invoked via `execFile` with an argument array (never a shell); untrusted input paths are validated (no control characters, no leading-dash flag-injection, must exist) and output files land only inside the configured media directory
  237. ### Persistent Agent Memory
  238. - **Long-term, evolving knowledge** — each agent has a categorised memory (knowledge, preference, correction, skill, reflection, …) that survives across every conversation
  239. - **Confidence + decay** — entries carry a confidence score that decays for unaccessed knowledge; `critical` entries never decay; low-confidence and expired entries are pruned
  240. - **BM25F search** — a zero-dependency full-text index ranks recall by relevance, importance, recency, and access count
  241. - **Prompt + voice injection** — `generateMemoryContext()` renders a ranked markdown block for injection into agent prompts and realtime voice sessions
  242. - **Private per agent** — every memory endpoint is scoped to the authenticated agent; deleting an agent purges its memory
  243. - **Everywhere** — `/memory*` REST endpoints, MCP tools (`memory`, `memory_reflect`, `memory_context`, `memory_stats`), and OpenClaw tools (`agenticmail_memory*`)
  244. ### Smart Orchestration (call_agent)
  245. - **Auto mode detection** — reads task complexity, picks light/standard/full mode automatically
  246. - **Dynamic timeouts** — 60s for quick tasks, 5+ minutes for deep research, 1 hour for async
  247. - **Runtime tool discovery** — probes host config for available tools instead of static deny lists
  248. - **Async execution** — long-running tasks run independently, auto-compact context, email results when done
  249. - **Structured RPC** — sub-agents return JSON, not raw text
  250. ### Integrations
  251. - **MCP server** — 90+ tools for any MCP-compatible AI client
  252. - **OpenClaw plugin** — 80+ tools with skill definition and system prompt guidelines
  253. - **REST API** — 75+ endpoints, OpenAPI-style, Bearer token auth
  254. - **SSE events** — real-time inbox notifications via Server-Sent Events
  255. - **Interactive CLI** — 44 shell commands with arrow key navigation, body previews, retry logic
  256. - **Self-updating** — `agenticmail update` or `/update` in shell, with OpenClaw compatibility check
  257. ---
  258. ## Architecture
  259. ```
  260. ┌──────────────────────────────────────────────────┐
  261. │ AgenticMail │
  262. │ │
  263. AI Client ─MCP─> │ @agenticmail/mcp (100 tools, stdio transport)│
  264. │ │ │
  265. OpenClaw ─────> │ @agenticmail/openclaw (89 tools, plugin) │
  266. │ │ │
  267. HTTP clients──> │ ▼ │
  268. │ @agenticmail/api (Express, 75+ endpoints) │
  269. │ ├── Authentication (master key + agent keys) │
  270. │ ├── Rate limiting (per-endpoint) │
  271. │ ├── SSE streaming (real-time inbox events) │
  272. │ └── Spam filter + Outbound guard │
  273. │ │ │
  274. │ ▼ │
  275. │ @agenticmail/core (SDK layer) │
  276. │ ├── AccountManager (CRUD agents in Stalwart) │
  277. │ ├── MailSender (SMTP, nodemailer) │
  278. │ ├── MailReceiver (IMAP, imapflow) │
  279. │ ├── InboxWatcher (IMAP IDLE → events) │
  280. │ ├── GatewayManager (relay + domain routing) │
  281. │ │ ├── RelayGateway (Gmail/Outlook) │
  282. │ │ ├── CloudflareClient (DNS, tunnels, etc) │
  283. │ │ ├── TunnelManager (cloudflared) │
  284. │ │ ├── DNSConfigurator (MX, SPF, DKIM) │
  285. │ │ └── DomainPurchaser (Registrar API) │
  286. │ ├── StalwartAdmin (mail server management) │
  287. │ ├── EmailSearchIndex (FTS5 full-text search) │
  288. │ └── Storage (SQLite + migrations) │
  289. │ │ │
  290. │ ▼ │
  291. │ Stalwart Mail Server (Docker container) │
  292. │ ├── SMTP (port 587) — submission │
  293. │ ├── SMTP (port 25) — inbound delivery │
  294. │ ├── IMAP (port 143) — mailbox access │
  295. │ └── HTTP (port 8080) — admin API │
  296. └──────────────────────────────────────────────────┘
  297. │ │
  298. ┌─────────────┘ └──────────────┐
  299. ▼ ▼
  300. Relay Mode Domain Mode
  301. ┌──────────────────┐ ┌──────────────────────┐
  302. │ Gmail / Outlook │ │ Cloudflare │
  303. │ IMAP polling │ │ ├── DNS zone │
  304. │ SMTP relay │ │ ├── Tunnel │
  305. │ Sub-addressing │ │ ├── Email Routing │
  306. │ (+agent@gmail) │ │ ├── Email Worker │
  307. └──────────────────┘ │ └── Registrar │
  308. └──────────────────────┘
  309. ```
  310. ### Data Flow
  311. **Sending email (relay mode):**
  312. 1. Agent calls `POST /mail/send` with recipient, subject, body
  313. 2. API runs outbound guard scan — if sensitive data found, email is blocked and owner notified
  314. 3. GatewayManager detects external recipient → routes to RelayGateway
  315. 4. RelayGateway sends via Gmail SMTP as `owner+agentname@gmail.com`
  316. 5. Reply-To set to agent's relay address so replies route back
  317. **Sending email (domain mode):**
  318. 1. Agent calls `POST /mail/send`
  319. 2. Outbound guard scan runs
  320. 3. GatewayManager rewrites `agent@localhost` → `agent@yourdomain.com`
  321. 4. Email submitted to local Stalwart via SMTP (port 587)
  322. 5. Stalwart signs with DKIM, resolves MX, delivers directly (or via Gmail relay)
  323. **Receiving email (relay mode):**
  324. 1. RelayGateway polls Gmail IMAP every 30 seconds for new messages
  325. 2. New email detected → parsed → spam scored
  326. 3. If not spam, delivered to agent's local Stalwart mailbox via SMTP
  327. 4. `X-AgenticMail-Relay: inbound` header added for identification
  328. 5. InboxWatcher (IMAP IDLE) fires SSE event to connected clients
  329. **Receiving email (domain mode):**
  330. 1. External sender sends to `agent@yourdomain.com`
  331. 2. Cloudflare Email Routing catches all → routes to Email Worker
  332. 3. Worker reads raw RFC822 message, base64-encodes, POSTs to `/api/agenticmail/mail/inbound`
  333. 4. Inbound endpoint validates secret, parses email, delivers to agent's mailbox
  334. 5. InboxWatcher fires SSE event
  335. ---
  336. ## Quick Start
  337. ### Prerequisites
  338. - [Node.js](https://nodejs.org) **22 or later** (we use the built-in `node:sqlite` module — zero native compilation, no `node-gyp` headaches)
  339. - `brew` (macOS) or `apt` (Linux) so the wizard can install Colima / Docker if you don't already have it
  340. ### Two install paths
  341. | Path | When to use | Command |
  342. |---|---|---|
  343. | **Autonomous** ✨ | Letting an AI agent (e.g. Claude Code) install AgenticMail on your behalf, or you just want zero questions | `npm install -g @agenticmail/cli && agenticmail bootstrap` |
  344. | **Interactive** | You want to connect a Gmail relay or your own domain right away | `npm install -g @agenticmail/cli && agenticmail setup` |
  345. #### Autonomous install (recommended for most users)
  346. ```bash
  347. # Option A — one-liner (does the npm install + bootstrap for you, plus a Node 22+ preflight)
  348. curl -fsSL https://raw.githubusercontent.com/agenticmail/agenticmail/main/install.sh | bash
  349. # Option B — equivalent, manually
  350. npm install -g @agenticmail/cli
  351. agenticmail bootstrap
  352. ```
  353. Either path: zero prompts. The pipeline:
  354. 1. **`agenticmail setup --yes`** — auto-installs Colima + Docker if missing, starts the Stalwart mail server, generates your master key, creates a default "secretary" agent. **Skips external email/SMS setup** (those need user-owned credentials; add them later if you want).
  355. 2. **`agenticmail service install`** — registers a launchd plist (macOS) / systemd unit (Linux) so the API auto-starts on boot, and starts it now.
  356. 3. Waits for `GET /api/agenticmail/health` to come up on the configured port (default `http://127.0.0.1:3829`).
  357. 4. **`agenticmail claudecode`** — wires the Claude Code integration in if you have Claude Code installed (idempotent / no-op otherwise).
  358. After this, you have a fully working local AgenticMail with internal multi-agent coordination over `*@localhost`. Add an external Gmail relay or your own domain anytime with `agenticmail setup` (interactive).
  359. #### Interactive install
  360. ```bash
  361. npm install -g @agenticmail/cli
  362. agenticmail setup
  363. ```
  364. The wizard walks you through everything: dependency checks, master key generation, mail-server start, optional Gmail relay or custom domain, optional SMS setup, optional realtime voice (OpenAI API key), optional phone calling (pick **46elks or Twilio** and enter that carrier's credentials), optional Telegram channel (bot token + chat link), and optional OpenClaw integration. Every optional step is skippable and re-runnable any time. With `--yes` / `--non-interactive` all the optional steps are skipped with safe defaults.
  365. The new optional steps in detail:
  366. - **Realtime voice** — paste an OpenAI API key to enable live spoken phone calls (the realtime voice bridge). Without it, phone missions still place and track call-control calls; only the spoken-conversation bridge is unavailable. The key is stored as `openaiApiKey` in `~/.agenticmail/config.json` (file mode 0600).
  367. - **Phone calling** — pick your carrier (`46elks` or `twilio`), enter that carrier's credentials (46elks API username/password, or Twilio Account SID/Auth Token), a caller number, and a public HTTPS webhook base URL. The webhook secret is auto-generated if you don't supply one. Persisted to the agent's phone-transport config.
  368. - **Telegram channel** — paste a bot token from `@BotFather` and your chat id. The token is verified with Telegram before it's stored; the channel comes up in poll mode and `agenticmail start` auto-spawns a standalone bridge service that wakes the agent on inbound DMs with the full MCP toolset (memory, send_email, call_phone, …) available.
  369. ### Want non-interactive setup? (env-piped, AI-assistant-friendly)
  370. Same setup, no prompts — secrets ride in via env vars. Useful for Claude / Codex / scripted installs:
  371. ```bash
  372. # Email
  373. GMAIL_PASSWORD=… agenticmail setup-email <gmail-address>
  374. # Twilio outbound calls (auto-opens a free Cloudflare quick-tunnel if you
  375. # don't have a public HTTPS URL — no Cloudflare account required)
  376. TWILIO_ACCOUNT_SID='<sid>' TWILIO_AUTH_TOKEN='<token>' \
  377. AGENTICMAIL_PHONE_NUMBER='<E.164>' \
  378. agenticmail setup-phone --provider twilio
  379. # Telegram (bridge auto-spawns on next `agenticmail start`)
  380. TELEGRAM_BOT_TOKEN='<from @BotFather>' TELEGRAM_CHAT_ID='<your chat id>' \
  381. agenticmail setup-telegram
  382. # Manual tunnel control (not usually needed — setup-phone opens one for you)
  383. agenticmail tunnel start # cloudflared quick-tunnel
  384. agenticmail tunnel url # prints the *.trycloudflare.com URL
  385. agenticmail tunnel stop
  386. ```
  387. ### Skip external email entirely?
  388. Yes. AgenticMail works in **local-only mode** — agents email each other at `*@localhost` through the bundled Stalwart server with full RFC-822 routing, threading, attachments, and search. That's all the Claude Code multi-agent flow needs. The external Gmail/domain relay is optional and only matters when you want agents to send mail to the public internet.
  389. ### What the wizard does for you
  390. - Checks Node, Colima/Docker, brew/apt
  391. - Generates a master API key (saved to `~/.agenticmail/config.json`, file mode 0600)
  392. - Initialises the SQLite database (`node:sqlite` — Node 22+ built-in, **no native compilation, no prebuilt binaries needed**)
  393. - Starts Stalwart in a Docker container
  394. - Creates your first agent with its own email and API key
  395. - Optionally configures a gateway (relay or domain) for internet email
  396. - Optionally enables realtime voice (OpenAI API key), phone calling (46elks or Twilio), and the Telegram channel
  397. ### Send your first email (programmatic)
  398. ```typescript
  399. import { AgenticMailClient } from '@agenticmail/cli';
  400. const client = new AgenticMailClient({
  401. apiUrl: 'http://127.0.0.1:3829',
  402. apiKey: 'ak_your_agent_api_key',
  403. });
  404. // Send an email
  405. await client.send({
  406. to: 'colleague@example.com',
  407. subject: 'Hello from my AI agent',
  408. text: 'This email was sent by an AI agent using AgenticMail.',
  409. });
  410. // Check inbox
  411. const inbox = await client.listInbox(10);
  412. for (const msg of inbox) {
  413. console.log(`${msg.from} — ${msg.subject}`);
  414. }
  415. // Read a specific email
  416. const email = await client.readMessage(inbox[0].uid);
  417. console.log(email.text);
  418. ```
  419. ### Send your first email (CLI)
  420. ```
  421. agenticmail> /send
  422. To: someone@example.com
  423. Subject: Test email
  424. Body: Hello from the AgenticMail shell!
  425. Email sent! Message ID: <abc123@localhost>
  426. ```
  427. ### Send your first email (curl)
  428. ```bash
  429. curl -X POST http://127.0.0.1:3829/api/agenticmail/mail/send \
  430. -H "Authorization: Bearer ak_your_agent_key" \
  431. -H "Content-Type: application/json" \
  432. -d '{
  433. "to": "someone@example.com",
  434. "subject": "Hello",
  435. "text": "Sent via the AgenticMail API."
  436. }'
  437. ```
  438. ---
  439. ## CLI Commands
  440. AgenticMail includes a full CLI for managing your server. All commands are available via `agenticmail <command>` or `npx @agenticmail/cli@latest <command>`.
  441. ### Core Commands
  442. | Command | Description |
  443. |---------|-------------|
  444. | `agenticmail` | **Start the server** (runs setup first if not initialized). Opens the interactive shell after startup. This is the default command — just run `agenticmail` with no arguments. |
  445. | `agenticmail bootstrap` | ✨ **Zero-question install.** One-shot pipeline: setup + service install + claudecode wiring. Designed for AI agents (Claude Code, scripts, CI) to run on a user's behalf — no prompts, no decisions. Skips Gmail relay and SMS setup (which need user-owned credentials); add them later with `agenticmail setup`. |
  446. | `agenticmail setup` | **Run the setup wizard** interactively. Walks you through system checks, account creation, service startup, email connection (Gmail/Outlook/custom domain), phone number (SMS) setup, realtime voice (OpenAI API key), phone calling (46elks or Twilio), the Telegram channel, and OpenClaw integration. Pass `--yes` (or `-y`, `--non-interactive`) to skip every prompt and use safe defaults. Safe to re-run — won't overwrite existing config. |
  447. | `agenticmail start` | **Start the server** and open the interactive shell. Ensures Docker is running, Stalwart is up, and the API server is reachable. Automatically installs the auto-start service if not already set up. |
  448. | `agenticmail shell` | 👀 **Drop into the interactive shell against an already-running server.** Use this to monitor every agent's inbox, send mail on their behalf, watch the dispatcher event feed, or run any of the 44+ shell commands. Exits cleanly with `/exit`; the server keeps running. Best command to point a user at when they ask "what have my agents been doing?" |
  449. | `agenticmail web` | 🌐 **Open the Gmail-style web UI in your browser.** Two-column layout (sidebar with Compose + folders / content pane), 24×24 vector icons, hash router, real-time SSE updates, full markdown rendering, compose + reply with the `wake` parameter surfaced as a field. Same master key as the API. Available at `http://127.0.0.1:3829/` whenever the API server is running. |
  450. | `agenticmail stop` | **Stop the server.** Kills the background API server process. If auto-start is enabled, it will restart on next boot. Use `agenticmail service uninstall` to fully disable. |
  451. | `agenticmail status` | **Show what's running.** Displays the status of Docker, Stalwart, the API server, email connection, and auto-start service. |
  452. ### Integration Commands
  453. | Command | Description |
  454. |---------|-------------|
  455. | `agenticmail openclaw` | **Set up AgenticMail for OpenClaw.** Starts infrastructure, creates an agent, configures the OpenClaw plugin, enables agent auto-spawn via hooks, and restarts the OpenClaw gateway. |
  456. | `agenticmail claudecode` | ✨ **Set up AgenticMail for Claude Code.** Provisions a dedicated "claudecode" bridge agent, writes an MCP server entry to `~/.claude.json`, generates a Claude Code subagent file per AgenticMail agent under `~/.claude/agents/`, and starts the dispatcher daemon (PM2-managed) that auto-wakes agents on inbound mail or `/tasks/rpc`. No separate Anthropic key needed — workers ride on your existing Claude OAuth. Flags: `--status`, `--remove`, `--purge-bridge`. See [@agenticmail/claudecode on npm](https://www.npmjs.com/package/@agenticmail/claudecode) for the full design. |
  457. ### Service Management (Auto-Start)
  458. AgenticMail installs a system service so it automatically starts when your computer boots. On macOS this is a LaunchAgent; on Linux it's a systemd user service.
  459. | Command | Description |
  460. |---------|-------------|
  461. | `agenticmail service` | **Show auto-start status.** Displays whether the service is installed and running. |
  462. | `agenticmail service install` | **Install the auto-start service.** AgenticMail will start automatically on boot. The startup script waits up to 10 minutes for Docker to be ready, then checks that Stalwart is running (starts it if needed), then launches the API server. |
  463. | `agenticmail service uninstall` | **Remove the auto-start service.** AgenticMail will no longer start on boot. |
  464. | `agenticmail service reinstall` | **Reinstall the service.** Use this after config changes or updates to refresh the service file. |
  465. **What happens on reboot:**
  466. 1. Your computer starts → Docker Desktop launches (its own auto-start)
  467. 2. Stalwart mail server starts (`restart: unless-stopped` in Docker)
  468. 3. AgenticMail startup script waits for Docker to be ready (up to 10 min)
  469. 4. Script verifies Stalwart is running (auto-starts it if Docker restarted without it)
  470. 5. API server starts and begins accepting requests
  471. If the API server crashes, the system service automatically restarts it.
  472. ### Maintenance Commands
  473. | Command | Description |
  474. |---------|-------------|
  475. | `agenticmail update` | **Update to the latest version.** Checks npm for a new version, updates the CLI and OpenClaw plugin, and restarts the OpenClaw gateway if applicable. |
  476. | `agenticmail help` | **Show available commands.** |
  477. ### Logs
  478. Server logs are stored in `~/.agenticmail/logs/`:
  479. - `server.log` — API server stdout
  480. - `server.err.log` — API server stderr
  481. - `startup.log` — Boot sequence log (Docker wait times, Stalwart checks)
  482. ---
  483. ## Gateway Modes
  484. AgenticMail supports two modes for sending/receiving real internet email:
  485. ### Relay Mode (Beginner-Friendly)
  486. Use your existing Gmail or Outlook account as a relay. No domain purchase needed. Setup takes under 2 minutes.
  487. **How it works:**
  488. - Outbound: emails sent via your Gmail/Outlook SMTP as `you+agentname@gmail.com`
  489. - Inbound: AgenticMail polls your Gmail/Outlook IMAP for new messages addressed to `you+agentname@gmail.com` and delivers them to the agent's local mailbox
  490. - Gmail's `+` sub-addressing routes replies back to the right agent
  491. **Setup:**
  492. ```bash
  493. # In the interactive shell:
  494. agenticmail> /relay
  495. # Or via API:
  496. curl -X POST http://127.0.0.1:3829/api/agenticmail/gateway/relay \
  497. -H "Authorization: Bearer mk_your_master_key" \
  498. -H "Content-Type: application/json" \
  499. -d '{
  500. "provider": "gmail",
  501. "email": "you@gmail.com",
  502. "password": "xxxx xxxx xxxx xxxx"
  503. }'
  504. ```
  505. **Requirements:**
  506. - Gmail: [App password](https://myaccount.google.com/apppasswords) (not your regular password)
  507. - Outlook: App password from Microsoft account security settings
  508. ### Domain Mode (Advanced)
  509. Full custom domain with Cloudflare. Agents send from `agent@yourdomain.com` with proper email authentication.
  510. **What gets configured automatically:**
  511. - Cloudflare DNS zone creation
  512. - MX records pointing to Cloudflare Email Routing
  513. - SPF record (`v=spf1 include:_spf.mx.cloudflare.net ~all`)
  514. - DKIM key generation and TXT record
  515. - DMARC record (`v=DMARC1; p=quarantine`)
  516. - Cloudflare Tunnel (CNAME record, ingress rules)
  517. - Cloudflare Email Worker deployment (catches all inbound email)
  518. - Catch-all Email Routing rule → Worker → AgenticMail inbound endpoint
  519. - Stalwart hostname, DKIM signing, domain principal
  520. - `@domain` email aliases for all existing agents
  521. - Optional: Gmail SMTP outbound relay, domain purchase
  522. **Setup:**
  523. ```bash
  524. curl -X POST http://127.0.0.1:3829/api/agenticmail/gateway/domain \
  525. -H "Authorization: Bearer mk_your_master_key" \
  526. -H "Content-Type: application/json" \
  527. -d '{
  528. "cloudflareToken": "your_cf_api_token",
  529. "cloudflareAccountId": "your_cf_account_id",
  530. "domain": "yourdomain.com",
  531. "gmailRelay": {
  532. "email": "you@gmail.com",
  533. "appPassword": "xxxx xxxx xxxx xxxx"
  534. }
  535. }'
  536. ```
  537. **Cloudflare API token permissions needed:**
  538. - Zone: DNS (Edit), Email Routing (Edit)
  539. - Account: Cloudflare Tunnel (Edit), Workers Scripts (Edit), Registrar (Edit — only if purchasing domains)
  540. ---
  541. ## Packages
  542. This is a TypeScript monorepo. Seven packages, each shipped to npm independently.
  543. | Package | Description | Install |
  544. |---------|-------------|---------|
  545. | [`@agenticmail/cli`](./agenticmail) | CLI, setup wizard, interactive shell. Install this to get started. | `npm i -g @agenticmail/cli` |
  546. | [`@agenticmail/core`](./packages/core) | Core SDK — accounts, SMTP/IMAP, gateway, spam filter, outbound guard, storage | `npm i @agenticmail/core` |
  547. | [`@agenticmail/api`](./packages/api) | Express REST API server with 75+ endpoints | `npm i @agenticmail/api` |
  548. | [`@agenticmail/mcp`](./packages/mcp) | MCP server with 100 tools for any MCP-compatible AI client | `npm i -g @agenticmail/mcp` |
  549. | [`@agenticmail/claudecode`](./packages/claudecode) | Anthropic Claude Code integration — registers MCP server + native subagents + lifecycle hooks + dispatcher daemon | `npm i -g @agenticmail/claudecode` |
  550. | [`@agenticmail/codex`](./packages/codex) | OpenAI Codex CLI integration — same architecture as `@agenticmail/claudecode`, adapted to Codex's TOML config and `spawn_agent` tool | `npm i -g @agenticmail/codex` |
  551. | [`@agenticmail/openclaw`](./packages/openclaw) | OpenClaw plugin with 89 tools and skill definition | `openclaw plugin install agenticmail` |
  552. **Plugin folders** (host marketplace manifests, separate from npm packages):
  553. | Folder | Host | What's inside |
  554. |---|---|---|
  555. | [`plugin/`](./plugin) | Claude Code | `.claude-plugin/plugin.json` manifest + `.mcp.json` + skills. Ship target for Anthropic's plugin marketplace. |
  556. | [`plugin-codex/`](./plugin-codex) | OpenAI Codex CLI | `.codex-plugin/plugin.json` manifest + `hooks/hooks.json` + `mcp_servers.toml` snippet + agent template. Ship target for Codex's plugin discovery (`~/.codex/plugins/`). |
  557. **Dependency graph:**
  558. ```
  559. @agenticmail/cli ──────> @agenticmail/api ────> @agenticmail/core
  560. @agenticmail/mcp (standalone — HTTP calls to API)
  561. @agenticmail/claudecode (peer-dep on @anthropic-ai/claude-agent-sdk)
  562. @agenticmail/codex (peer-dep on @openai/codex-sdk)
  563. @agenticmail/openclaw (standalone — HTTP calls to API)
  564. ```
  565. ---
  566. ## API Overview
  567. All endpoints are under `/api/agenticmail`. Authentication via `Authorization: Bearer <key>` header.
  568. Two key types:
  569. - **Master key** (`mk_...`) — full admin access (create/delete agents, approve blocked emails, gateway config)
  570. - **Agent key** (`ak_...`) — scoped to one agent (read own inbox, send email, manage own drafts/contacts/etc.)
  571. ### Key Endpoints
  572. | Method | Path | Auth | Description |
  573. |--------|------|------|-------------|
  574. | **Mail** | | | |
  575. | `POST` | `/mail/send` | Agent | Send email (text, HTML, attachments) |
  576. | `GET` | `/mail/inbox` | Agent | List inbox messages (paginated) |
  577. | `GET` | `/mail/digest` | Agent | Inbox with body previews |
  578. | `GET` | `/mail/messages/:uid` | Agent | Read full email with headers and attachments |
  579. | `POST` | `/mail/search` | Agent | Search by from, subject, body, date |
  580. | `POST` | `/mail/messages/:uid/move` | Agent | Move to folder |
  581. | `POST` | `/mail/messages/:uid/spam` | Agent | Report as spam |
  582. | `GET` | `/mail/folders` | Agent | List all folders |
  583. | `GET` | `/mail/pending` | Both | List blocked outbound emails |
  584. | `POST` | `/mail/pending/:id/approve` | Master | Approve blocked email |
  585. | `POST` | `/mail/pending/:id/reject` | Master | Reject blocked email |
  586. | **Accounts** | | | |
  587. | `POST` | `/accounts` | Master | Create new agent |
  588. | `GET` | `/accounts` | Master | List all agents with metadata |
  589. | `GET` | `/accounts/me` | Agent | Get own agent info |
  590. | `DELETE` | `/accounts/:id` | Master | Delete agent (with email archival) |
  591. | `GET` | `/accounts/directory` | Both | Agent discovery directory |
  592. | **Events** | | | |
  593. | `GET` | `/events` | Agent | SSE stream — new email with route metadata, flags, expunge events |
  594. | **Gateway** | | | |
  595. | `GET` | `/gateway/status` | Both | Current gateway mode and health |
  596. | `POST` | `/gateway/relay` | Master | Configure relay mode |
  597. | `POST` | `/gateway/domain` | Master | Configure domain mode |
  598. | `POST` | `/gateway/test` | Both | Send a test email |
  599. | **Tasks** | | | |
  600. | `POST` | `/tasks/assign` | Both | Assign task to another agent |
  601. | `POST` | `/tasks/rpc` | Both | Synchronous agent-to-agent RPC (long-poll) |
  602. | `GET` | `/tasks/pending` | Agent | List tasks assigned to me |
  603. | `POST` | `/tasks/:id/claim` | Agent | Claim a pending task |
  604. | `POST` | `/tasks/:id/result` | Agent | Submit task result |
  605. Plus endpoints for drafts, contacts, tags, rules, signatures, templates, scheduled emails, spam management, batch operations, domains, and agent deletion/cleanup.
  606. See the [API package README](./packages/api) for complete endpoint documentation.
  607. ---
  608. ## MCP Integration
  609. The MCP server exposes 80+ tools to any MCP-compatible AI client via stdio transport.
  610. ### Setup
  611. Add to your MCP client configuration (e.g., `.mcp.json` or project settings):
  612. ```json
  613. {
  614. "mcpServers": {
  615. "agenticmail": {
  616. "command": "npx",
  617. "args": ["-y", "@agenticmail/mcp"],
  618. "env": {
  619. "AGENTICMAIL_API_URL": "http://127.0.0.1:3829",
  620. "AGENTICMAIL_API_KEY": "ak_your_agent_key"
  621. }
  622. }
  623. }
  624. }
  625. ```
  626. ### Desktop Clients
  627. For desktop AI applications, add the same configuration to your app's MCP config file (check your app's documentation for the file location).
  628. ### What your AI can do
  629. Once connected, your AI can:
  630. - "Check my inbox" → `list_inbox`
  631. - "Send an email to john@example.com about the project update" → `send_email`
  632. - "Reply to that last email saying thanks" → `reply_email`
  633. - "Search for emails from Sarah about the budget" → `search_emails`
  634. - "Create a draft response to the client" → `manage_drafts`
  635. - "What tasks are assigned to me?" → `check_tasks`
  636. - "Ask the research agent to look up competitor pricing" → `call_agent`
  637. See the [MCP package README](./packages/mcp) for the full tool list.
  638. ---
  639. ## Host Integrations
  640. AgenticMail is host-agnostic at the protocol level (it's just SMTP/IMAP/HTTP/MCP under the hood), but each agentic CLI host expects its config + hooks + subagent definitions in a slightly different shape. We ship one **host integration package** per supported host. Each one:
  641. 1. Registers the AgenticMail MCP server in the host's config so the model can see all 100 tools.
  642. 2. Surfaces every AgenticMail account as a native sub-agent the model can dispatch to.
  643. 3. Wires up the host's lifecycle hooks (`SessionStart`, `UserPromptSubmit`, `Stop`) so the agent gets a fresh-mail digest and capabilities preamble at the right moments.
  644. 4. Runs a long-lived **dispatcher daemon** that watches every account's inbox via SSE and spawns a one-shot model turn whenever new mail or a task arrives — so agents wake on each other's replies automatically without polling.
  645. ### Currently shipping
  646. | Host | Package | Plugin folder | Status |
  647. |---|---|---|---|
  648. | Anthropic Claude Code | [`@agenticmail/claudecode`](./packages/claudecode) | [`plugin/`](./plugin) | **Shipping (0.2.x)** |
  649. | OpenAI Codex CLI | [`@agenticmail/codex`](./packages/codex) | [`plugin-codex/`](./plugin-codex) | **Shipping (0.1.x)** |
  650. Both integrations share the same dispatcher architecture (per-agent serialization, wake-coalesce, wake-budget, restart recovery, capabilities preamble). The host-specific bits are: config-file format (JSON vs TOML), subagent definition syntax (markdown+frontmatter vs TOML heredoc), and the SDK we drive workers through (`@anthropic-ai/claude-agent-sdk` vs `@openai/codex-sdk`).
  651. ### Picking the right install path
  652. | You want… | Run |
  653. |---|---|
  654. | **One-line setup for Claude Code** | `npm install -g @agenticmail/cli && agenticmail claudecode` |
  655. | **One-line setup for Codex** | `npm install -g @agenticmail/codex && agenticmail-codex install` |
  656. | **Install both side-by-side** | Run both — they don't conflict. Each writes to its own host's config; the AgenticMail accounts are shared. |
  657. | **Marketplace install (Anthropic plugin store)** | Drop [`plugin/`](./plugin) into your Claude Code plugin directory and run `/agenticmail-install`. |
  658. | **Marketplace install (Codex `~/.codex/plugins/`)** | Copy [`plugin-codex/`](./plugin-codex) to `~/.codex/plugins/agenticmail/`. |
  659. | **Programmatic (your own provisioning script)** | `import { install } from '@agenticmail/claudecode'` or `'@agenticmail/codex'` — same shape, different host. |
  660. ### Cross-host coordination
  661. The mail layer is the lingua franca. An agent running under Claude Code can email an agent running under Codex (or vice versa) using the exact same `send_email({ to, cc, wake })` MCP tool — the message lands in the target's inbox, the target's host-specific dispatcher picks it up, spawns the right kind of turn (Claude or Codex), and the agent replies-all to the thread. From the sender's perspective there's no API difference between "my teammate runs under the same host as me" and "my teammate runs under a different host." That's the whole point of routing through email instead of host-native peer messaging.
  662. ### Roadmap
  663. | Host | Status | Notes |
  664. |---|---|---|
  665. | xAI Grok Build CLI | Researched — see [wiki](https://github.com/agenticmail/agenticmail/wiki/Integration-Grok-Build) | Blocked on getting a SuperGrok Heavy seat to validate the closed-beta config-file paths against the community CLI proxy. ~80% architectural overlap. |
  666. | Nous Research Hermes Agent | Researched — see [wiki](https://github.com/agenticmail/agenticmail/wiki/Integration-Hermes) | Python-native plugin (`pip install hermes-agent-agenticmail`). ~75% architectural overlap with claudecode/codex. |
  667. ---
  668. ## OpenClaw Integration
  669. Already have OpenClaw? Two steps:
  670. ```bash
  671. # Step 1 — Install AgenticMail globally and run the setup wizard
  672. npm install -g @agenticmail/cli && agenticmail setup
  673. ```
  674. ```bash
  675. # Step 2 — Connect AgenticMail to your OpenClaw instance
  676. agenticmail openclaw
  677. ```
  678. That's it. The global install gives you the `agenticmail` command. The `openclaw` command will start the mail server, create an agent, and merge the plugin config into your `openclaw.json` automatically. Your OpenClaw agent now has its own email address.
  679. ### Manual Configuration
  680. If you prefer to configure manually, add to `~/.openclaw/openclaw.json`:
  681. ```json
  682. {
  683. "plugins": {
  684. "agenticmail": {
  685. "enabled": true,
  686. "config": {
  687. "apiUrl": "http://127.0.0.1:3829",
  688. "apiKey": "ak_your_agent_key",
  689. "masterKey": "mk_your_master_key"
  690. }
  691. }
  692. }
  693. }
  694. ```
  695. The plugin survives OpenClaw updates — plugin configuration lives in user config (`~/.openclaw/openclaw.json`), not in the OpenClaw source directory.
  696. ### Chat with Your AI Agent
  697. Use `/chat` in the AgenticMail shell to talk directly to your OpenClaw agent in real-time:
  698. ```
  699. ╭───────────────────────────────────────────────╮
  700. │ ❯ what's the weather in NYC? │
  701. ╰───────────────────────────────────────────────╯
  702. You 👤
  703. ╭──────────────╮
  704. │ what's the │
  705. │ weather in │
  706. │ NYC? │
  707. ╰──────────────╯
  708. 🎀 Fola
  709. ╭──────────────────────────────────────╮
  710. │ Currently 42°F and cloudy in NYC. │
  711. ╰──────────────────────────────────────╯
  712. ```
  713. - WebSocket connection to OpenClaw gateway with Ed25519 device auth
  714. - Bubble-style chat UI with markdown rendering
  715. - Animated thinking indicator with elapsed timer
  716. - Multi-line input (Enter sends, `\` + Enter for new lines)
  717. ### Smart Sub-Agent Spawning
  718. The `call_agent` tool intelligently spawns sub-agents:
  719. - **Auto mode detection** — light (simple tasks), standard (web research), full (multi-agent coordination)
  720. - **Dynamic timeouts** — 60s / 180s / 300s based on complexity
  721. - **Dynamic tool discovery** — probes OpenClaw config at runtime instead of static deny lists
  722. - **Async mode** — `call_agent(async=true)` for long-running tasks. The caller polls `/tasks/assigned` for completion; the assigned agent **emails the result back to the caller** when it has email capability enabled. In a localhost-only / no-relay setup the result still lands in the caller's local mailbox, so check `/mail/inbox` if you don't see an SMTP delivery.
  723. - **Web search fallback** — uses DuckDuckGo when Brave API isn't configured
  724. See the [OpenClaw package README](./packages/openclaw) for the full tool list.
  725. ---
  726. ## Interactive Shell
  727. The CLI includes a full-featured interactive shell with 44 commands:
  728. ```
  729. agenticmail> /inbox
  730. ★ 1 john@example.com Project Update 2m ago
  731. 2 sarah@example.com Re: Budget Review 1h ago
  732. 3 notifications@github.com [repo] New issue #42 3h ago
  733. ─────────────────────────────────────────────────
  734. Page 1/3 ─ [←] prev [→] next [v] toggle previews [Esc] back
  735. Use ↑↓ arrow keys to select, Enter to read inline
  736. ```
  737. **Key features:**
  738. - Arrow key navigation with cursor selection
  739. - Body preview toggle (press `v`)
  740. - Inline email reading (press `Enter`)
  741. - Unread markers (`★`)
  742. - 3-retry input validation on all prompts
  743. - Paginated views with `←`/`→` navigation
  744. ### Command Reference
  745. ```
  746. Email: /inbox /send /read /reply /forward /search /delete /save
  747. /thread /unread /archive /trash
  748. Organize: /folders /contacts /drafts /signature /templates /schedule /tag
  749. Agents: /agents /switch /deleteagent /deletions
  750. Security: /spam /rules /pending
  751. Gateway: /relay /digest /setup /status /openclaw
  752. System: /help /clear /exit
  753. ```
  754. ---
  755. ## Security
  756. ### Outbound Guard
  757. Every outgoing email is scanned before sending. The guard detects:
  758. | Category | Examples |
  759. |----------|----------|
  760. | API keys | `sk-...`, `AKIA...`, `ghp_...`, `sk_live_...` |
  761. | Credentials | `password: ...`, `secret: ...`, `token: ...` |
  762. | Private keys | `-----BEGIN RSA PRIVATE KEY-----` |
  763. | PII | Social security numbers, credit card patterns |
  764. | Internal data | Localhost URLs, internal IPs, config file contents |
  765. When sensitive data is detected:
  766. 1. Email is **blocked** and saved to the `pending_outbound` table
  767. 2. Agent receives a response explaining what was blocked and why, with instructions to inform their owner
  768. 3. Owner (master key holder) is notified via email with the full blocked email content, security warnings, recipient, subject, and pending ID
  769. 4. Owner approves or rejects via the master key API (`POST /mail/pending/:id/approve` or `/reject`) or by replying to the notification email
  770. 5. Agents **cannot** approve or reject their own blocked emails — the approve/reject endpoints require the master key
  771. 6. Agents can only list and view their pending emails to check approval status
  772. 7. MCP and OpenClaw tools enforce this by rejecting approve/reject actions with a message directing agents to inform their owner
  773. 8. System prompt guidelines (OpenClaw) instruct agents to never attempt self-approval or rewrite emails to bypass detection
  774. ### Spam Filter
  775. Inbound emails are scored against rule-based patterns:
  776. | Category | Score Range | Examples |
  777. |----------|-------------|----------|
  778. | Phishing | 10-30 | Fake login pages, urgency language, spoofed senders |
  779. | Scam | 15-25 | Nigerian prince, lottery winner, inheritance schemes |
  780. | Malware | 20-30 | Suspicious attachments, executable links |
  781. | Commercial | 5-15 | Unsolicited marketing, unsubscribe-heavy emails |
  782. | Social engineering | 10-20 | Impersonation, authority pressure |
  783. - Emails scoring >= 40 (configurable) are moved to Spam folder
  784. - Emails scoring 20-39 get a warning flag
  785. - Internal agent-to-agent emails skip spam filtering entirely
  786. - Relay-rewritten emails (`@localhost` from, external replyTo) are always treated as external
  787. ### Authentication
  788. - **Master key** — full admin access, required for agent creation/deletion, gateway config, email approval
  789. - **Agent API keys** — scoped per-agent, can only access own inbox and send from own address
  790. - **Inbound webhook secret** — authenticates Cloudflare Email Worker requests to the inbound endpoint
  791. ---
  792. ## Configuration
  793. ### Environment Variables
  794. ```bash
  795. # === Required ===
  796. AGENTICMAIL_MASTER_KEY=mk_your_key # Master API key (generate: openssl rand -hex 32)
  797. # === Stalwart Mail Server ===
  798. STALWART_ADMIN_USER=admin # Stalwart admin username
  799. STALWART_ADMIN_PASSWORD=changeme # Stalwart admin password
  800. STALWART_URL=http://localhost:8080 # Stalwart HTTP admin URL
  801. # === SMTP/IMAP (local Stalwart) ===
  802. SMTP_HOST=localhost # SMTP host
  803. SMTP_PORT=587 # SMTP submission port
  804. IMAP_HOST=localhost # IMAP host
  805. IMAP_PORT=143 # IMAP port
  806. # === Optional ===
  807. AGENTICMAIL_API_PORT=3829 # API server port (default: 3829 — chosen to
  808. # avoid 3000/3100/3200/3300/4000/5000/8000/8080
  809. # which are all common dev-tool defaults)
  810. AGENTICMAIL_API_HOST=127.0.0.1 # API bind host (default: 127.0.0.1; loopback only)
  811. AGENTICMAIL_DATA_DIR=~/.agenticmail # Data directory for SQLite DB and config
  812. # === Realtime Voice (optional) ===
  813. OPENAI_API_KEY=sk-... # Enables the realtime voice bridge — bridges a
  814. # phone mission to an OpenAI Realtime session.
  815. # Without it, calls are call-control only.
  816. # === Gateway: Relay Mode ===
  817. RELAY_PROVIDER=gmail # gmail or outlook
  818. RELAY_EMAIL=you@gmail.com # Your email address
  819. RELAY_PASSWORD=xxxx xxxx xxxx xxxx # App password
  820. # === Gateway: Domain Mode ===
  821. CLOUDFLARE_API_TOKEN=your_token # Cloudflare API token
  822. CLOUDFLARE_ACCOUNT_ID=your_account_id # Cloudflare account ID
  823. AGENTICMAIL_DOMAIN=yourdomain.com # Your domain
  824. AGENTICMAIL_INBOUND_SECRET=your_secret # Shared secret for Email Worker
  825. # === Gmail SMTP Relay (domain mode outbound) ===
  826. GMAIL_RELAY_EMAIL=you@gmail.com # Gmail address for outbound relay
  827. GMAIL_RELAY_APP_PASSWORD=xxxx xxxx xxxx # Gmail app password
  828. # === Debug ===
  829. # AGENTICMAIL_DEBUG=1 # Enable verbose per-message logging
  830. ```
  831. ### Docker Compose
  832. ```yaml
  833. # docker-compose.yml (included in repo)
  834. services:
  835. stalwart:
  836. image: stalwartlabs/stalwart:latest
  837. container_name: agenticmail-stalwart
  838. ports:
  839. - "8080:8080" # HTTP Admin + JMAP
  840. - "587:587" # SMTP Submission
  841. - "143:143" # IMAP
  842. - "25:25" # SMTP Inbound
  843. volumes:
  844. - stalwart-data:/opt/stalwart
  845. - ~/.agenticmail/stalwart.toml:/opt/stalwart/etc/stalwart.toml:ro
  846. restart: unless-stopped
  847. ```
  848. ### SQLite Database
  849. AgenticMail stores all state in a SQLite database at `~/.agenticmail/agenticmail.db`. As of `@agenticmail/core@0.7.x` we use Node's built-in **`node:sqlite`** module (stable since Node 22) instead of `better-sqlite3`. The migration removed all native compilation from the install path — no `node-gyp`, no prebuilt-binary version-mismatch issues, no Python prerequisites. The on-disk database format is unchanged (it's still SQLite 3), so existing `~/.agenticmail/agenticmail.db` files continue to work without migration.
  850. Tables:
  851. - `agents` — agent accounts (name, email, API key, metadata)
  852. - `gateway_config` — relay or domain mode configuration
  853. - `pending_outbound` — blocked emails awaiting approval
  854. - `delivered_messages` — deduplication tracking for inbound relay
  855. - `spam_log` — spam scoring history
  856. - `agent_tasks` — inter-agent task assignments
  857. - `email_rules` — per-agent email filtering rules
  858. - `contacts`, `drafts`, `signatures`, `templates`, `scheduled_emails`, `tags`
  859. ---
  860. ## Development
  861. ### Setup
  862. ```bash
  863. git clone https://github.com/agenticmail/agenticmail.git
  864. cd agenticmail
  865. npm install
  866. docker compose up -d
  867. npm run build
  868. npm test
  869. ```
  870. ### Project Structure
  871. ```
  872. agenticmail/
  873. ├── agenticmail/ # CLI facade package (npm: agenticmail)
  874. │ └── src/
  875. │ ├── cli.ts # CLI entry point (setup, start, status)
  876. │ ├── shell.ts # Interactive REPL (44 commands)
  877. │ └── index.ts # Re-exports from @agenticmail/core
  878. ├── packages/
  879. │ ├── core/ # @agenticmail/core
  880. │ │ └── src/
  881. │ │ ├── accounts/ # Agent CRUD, roles, deletion
  882. │ │ ├── mail/ # Sender, receiver, parser, spam filter, outbound guard
  883. │ │ ├── inbox/ # IMAP IDLE watcher
  884. │ │ ├── gateway/ # Relay, Cloudflare, DNS, tunnel, domain purchase
  885. │ │ ├── stalwart/ # Stalwart admin API client
  886. │ │ ├── storage/ # SQLite database, migrations, search index
  887. │ │ ├── domain/ # Domain management
  888. │ │ └── setup/ # Dependency checker, installer
  889. │ ├── api/ # @agenticmail/api
  890. │ │ └── src/
  891. │ │ ├── app.ts # Express app factory
  892. │ │ ├── routes/ # 8 route modules (mail, accounts, events, etc.)
  893. │ │ └── middleware/ # Auth, rate limiting, error handling
  894. │ ├── mcp/ # @agenticmail/mcp
  895. │ │ └── src/
  896. │ │ ├── index.ts # MCP server entry (stdio transport)
  897. │ │ ├── tools.ts # 80+ tool definitions and handlers
  898. │ │ └── resources.ts
  899. │ └── openclaw/ # @agenticmail/openclaw
  900. │ ├── index.ts # Plugin entry, system prompt
  901. │ ├── src/tools.ts # 89 tool definitions and handlers
  902. │ └── skill/ # SKILL.md, reference docs, scripts
  903. ├── docker-compose.yml # Stalwart mail server
  904. ├── .env.example # Environment variable template
  905. └── package.json # Workspace root
  906. ```
  907. ### Build Commands
  908. ```bash
  909. # Build all packages
  910. npm run build
  911. # Build a single package
  912. cd packages/core && npx tsup src/index.ts --format esm --dts --clean
  913. # Run all tests
  914. npm test
  915. # Run tests for a specific package
  916. cd packages/core && npx vitest run
  917. ```
  918. ### Publish to npm
  919. Publish in dependency order:
  920. ```bash
  921. cd packages/core && npm publish
  922. cd packages/api && npm publish
  923. cd packages/mcp && npm publish
  924. cd packages/openclaw && npm publish
  925. cd agenticmail && npm publish
  926. ```
  927. All scoped packages have `"publishConfig": { "access": "public" }` configured.
  928. See [CONTRIBUTING.md](./CONTRIBUTING.md) for development guidelines.
  929. ---
  930. ## Telemetry
  931. AgenticMail collects **anonymous** usage statistics to help improve the product. We track:
  932. - Tool call counts (which tools are popular)
  933. - Package version and OS platform
  934. - Anonymous install ID (random UUID, no personal data)
  935. **We never collect** API keys, email content, addresses, or any personal information.
  936. **Opt out** by setting the environment variable:
  937. ```bash
  938. export AGENTICMAIL_TELEMETRY=0
  939. # or
  940. export DO_NOT_TRACK=1
  941. ```
  942. Telemetry is also automatically disabled in CI environments.
  943. ## Troubleshooting
  944. ### OpenClaw plugin ID mismatch warning
  945. ```
  946. plugin id mismatch (manifest uses "agenticmail", entry hints "openclaw")
  947. ```
  948. This is harmless. OpenClaw infers the plugin ID from the npm package name (`@agenticmail/openclaw`) but the manifest declares `"id": "agenticmail"`. The plugin loads and works correctly.
  949. ### OpenClaw plugin path not found
  950. If OpenClaw reports the plugin path not found, update `plugins.load.paths` in `~/.openclaw/openclaw.json` to point to the correct location:
  951. ```bash
  952. npm prefix -g
  953. # Plugin is at: <prefix>/lib/node_modules/@agenticmail/openclaw
  954. ```
  955. ### `agenticmail: command not found`
  956. Use `npx agenticmail` for one-off usage, or install globally with `npm install -g @agenticmail/cli`.
  957. ## Contributors
  958. Thank you to everyone who has made AgenticMail better.
  959. ### Code
  960. - [@ope-olatunji](https://github.com/ope-olatunji): creator and maintainer
  961. - [@benediktkraus](https://github.com/benediktkraus)
  962. - [@adityachaudhary99](https://github.com/adityachaudhary99)
  963. - [@marcelomar21](https://github.com/marcelomar21)
  964. - Armand ([orbitalreach.space](https://orbitalreach.space))
  965. ### Security researchers
  966. These people reported vulnerabilities privately so they could be fixed before disclosure. See the [security advisories](https://github.com/agenticmail/agenticmail/security/advisories).
  967. - [@benediktkraus](https://github.com/benediktkraus): GHSA-wjjv-3mj2-39hf
  968. - [@SecurePatchOps](https://github.com/SecurePatchOps): GHSA-63gr-g7jc-v8rg
  969. - [@YHalo-wyh](https://github.com/YHalo-wyh): GHSA-hjwc-26pj-v3pm
  970. - [@matte1782](https://github.com/matte1782): GHSA-fq4x-789w-jg5h
  971. - [@manus-pi](https://github.com/manus-pi) and [@manus-use](https://github.com/manus-use): GHSA-h3h3-4g48-gxq9, GHSA-cpgx-gj4r-pf3w, GHSA-4x3j-9wxx-863h
  972. - [@avishaigonen-pluto](https://github.com/avishaigonen-pluto) and [@yotampe-pluto](https://github.com/yotampe-pluto): GHSA-fgq6-mm4x-93qq, GHSA-vm2m-87j8-8w9m
  973. - [@adelzaitri](https://github.com/adelzaitri): GHSA-vj36-c6cj-8qmh
  974. - [@EQSTLab](https://github.com/EQSTLab): GHSA-m52q-h5cf-mj6c
  975. - [@arpitjain099](https://github.com/arpitjain099): GHSA-3jw6-982f-pp9w
  976. - [@mappygrid](https://github.com/mappygrid): GHSA-p76v-w436-9wjh
  977. - [@presendapp](https://github.com/presendapp): GHSA-3gff-66q4-7m3q
  978. - [@wlassalle724](https://github.com/wlassalle724): GHSA-7mcc-72p6-m7p4
  979. ## License
  980. [MIT](./LICENSE) - Ope Olatunji ([@ope-olatunji](https://github.com/agenticmail/agenticmail))

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.