Mail plugin
Named-account mail_* tools backed by Gmail or generic IMAP+SMTP. Both backends
support the core lifecycle: search/read, folders, drafts, send/reply, staged
attachments and organisation. There is no Microsoft Graph backend or provider.
- module: codumentor.plugins.mail
class: MailPlugin
priority: 5
args:
target_agents: main
write_target_agents: main
implicit_gmail: true
default_read_only: true
accounts:
- id: work
backend: gmail
oauth_account_id: person@example.test
read_only: false
Gmail uses the existing oauth and google_workspace plugins. Connect in
Settings → Extensions → Google Workspace, granting Gmail read or read-write
access. Mail does not register a second Google provider or consent screen.
Community personal defaults include mail; an existing deployment must opt in by
adding the plugin. Existing live configuration files are not modified.
Accounts and tools
mail_list_accounts returns reachable accounts, authoritative connected addresses,
read-only status and features. With no accounts it returns setup instructions.
One connected identity defaults implicitly to gmail:<Google account_id>; with
multiple reachable accounts always specify account. Named config bindings
replace that identity's implicit entry. Accounts without a Gmail read grant are
not reachable. A configured Gmail address cannot override the OAuth identity.
Explicit accounts inherit default_read_only (true). Implicit Gmail accounts
preserve legacy behavior: Gmail modify grants allow writes. Effective write
access requires BOTH an account policy allowing it and that selected identity's
gmail.modify grant; scopes are never pooled across identities. The current
user owns both metadata and token lookups. Scope and read-only checks repeat at
execution, including after approval.
| Tool | Approval type | Input notes |
|---|---|---|
mail_list_accounts | none | Current user's reachable metadata |
mail_search | none | from, to, subject, text, since, before, unread, flagged, has_attachment, folder, raw_query, limit (1–50) |
mail_get_message | none | message_id, optional include_body |
mail_get_thread | none | thread_id, optional include_body |
mail_list_folders | none | Gmail labels returned as folders |
mail_list_drafts | none | limit (1–50) |
mail_get_attachment | none | Parent-bound message_id/attachment_id, filename, optional mime_type; staging only |
mail_send | mail.send | to, subject, body, cc, bcc, is_html, reply_to_message_id, or only draft_id |
mail_draft | mail.draft | Compose fields, optional draft_id to replace |
mail_delete_draft | mail.draft | draft_id |
mail_move | mail.move | message_id, target: {action: archive/trash/restore/folder, folder: <handle for folder action>} |
mail_mark | mail.mark | message_id, read and/or flagged |
mail_manage_label | mail.label | Gmail only; action: create/rename/delete, name, label_id folder handle |
mail_set_labels | mail.label | Gmail only; message_id, add_labels, remove_labels (names or folder handles), optional apply_to_thread |
All tools accept optional account. Structured search constraints are ANDed
with parenthesized Gmail raw_query. Dates use YYYY-MM-DD. Structured values
containing quotes/backslashes/newlines are rejected with guidance to use
raw_query. Unsupported arguments are errors, not ignored. There are no
outgoing attachments. Reply defaults and Gmail MIME encoding reuse the legacy
implementation.
IDs returned by generic tools are opaque versioned, typed, account-scoped
mail1_… handles. Do not parse them or pass raw Gmail IDs to generic tools.
Attachment handles are also bound to their parent message. A different account
or handle type is rejected before network access. Folder search accepts a name
or folder handle. Gmail's labels are not exclusive folders: moving to a folder
adds that label and removes INBOX (unless targeting INBOX), preserving other
labels. apply_to_thread still takes a message handle and resolves its
conversation, exactly as legacy Gmail does.
Features use threads: native | emulated | unsupported consistently;
search_dialect is gmail or imap. Gmail supports labels and native threads.
Gmail search returns estimated_total plus count; it is bounded by limit,
not a complete mailbox export. sent: true means Gmail accepted the request;
a transport error during send warns that delivery may be unknown and asks to
check Sent before retrying.
Approvals, containment and compatibility
Writes set is_write, obtain real permission requests, and include authoritative
account/backend/address plus the operation's fields. Invalid IDs, read-only
accounts and unsupported operations are refused before prompting. Active
permission-provider semantics apply: interactive providers may ask, CLI/headless
AutoAllow does not always prompt; deny-by-default headless providers still deny.
The family and write gates both default to main; invalid target settings clamp
to main. Existing subagent containment remains the final ceiling.
Legacy gmail_* names, parameter schemas, raw IDs, result shapes, imports and
gmail.* approval labels remain callable. When mail is enabled, host context
also guards legacy writes against the selected Gmail identity's mail read-only
policy and adds authoritative account metadata to runtime approval details. Their implementation bodies are reused
by the Gmail adapter, not copied. Only new offers hide an old name when its
generic counterpart is available to that agent after its gates. Deferred search
suggestions follow that hint; **explicit find_tools select:gmail_send still
works** for saved callers. Calendar/Drive/Docs/Sheets are unchanged. Old role prose
and saved goals are not rewritten or silently granted new names.
Generic and legacy Gmail access-name denies and approval-label denies restrict
equivalent operations in both directions, conservatively (including future
non-Gmail accounts). Allows remain exact: old Gmail **allows do not grant generic
mail**, and generic allows do not grant legacy names. Existing closed allowlists
need explicit new names. Only direct overlap edges are checked, not transitive
closure: denying mail_mark does not deny mail_move or mail_manage_label.
Broad legacy gmail_modify_message overlaps move, mark and set-label operations;
a deny of any of those blocks that broad legacy tool. Approval labels are coarser:
mail.label covers both label management and applying labels, so a gmail.modify
approval deny also conservatively blocks generic label management. Old denies must be removed deliberately if
an administrator wants to relax them. Account-qualified approval rules such as
mail.send(work) are not supported in this phase; bare mail.send rules
cover every reachable mail account. Use account read-only policy and ordinary
interactive approvals instead of claiming per-account auto-approval.
IMAP+SMTP and host-only credential provisioning
Do not paste passwords into chat, tool inputs, YAML values or ${secret:…}.
Only password_secret names belong in account config. The generic User Secrets
form defaults to turn-visible values and is not the mail provisioning path.
A dedicated authenticated host endpoint provisions the configured secret:
PUT /ui/plugins/mail/accounts/<configured-account-id>/credential
Content-Type: application/json
{"password": "<password>"}
Use the normal authenticated application API session; the endpoint requires
user_secrets:manage. No request user ID is accepted: storage uses the signed-in
principal. The account must be an admin-configured imap_smtp account. A response
only confirms saved, host_only and account; it never returns the password.
There is no mail settings form yet. TUI/host integrations can call
save_account_password(plugin, authenticated_user_id, account_id, password).
Storage requires auth.jwt_secret for encryption. Resolution refuses an existing
non-host-only record and tells the user to replace/rotate it. Host-only values
never enter the turn secret registry. The backend calls
resolve_account_password(app_config, AccountConfig, host_ctx) using the host
context user, never a tool-selected user ID. There is no password-reading agent
tool. Configured IMAP account slots are visible to signed-in users independently
of Google/OAuth, but every operation requires that user's own enrolled credential;
there is no shared or anonymous password fallback.
The account contract is:
accounts:
- id: onprem
backend: imap_smtp
address: person@example.test
username: person
password_secret: onprem_password
read_only: true
imap: {host: mail.example.test, port: 993, tls: implicit, timeout: 15}
smtp: {host: mail.example.test, port: 587, tls: starttls, timeout: 15}
sent_folder: Sent
drafts_folder: Drafts
trash_folder: Trash
archive_folder: Archive
TLS modes are implicit, starttls, none; ports 1–65535, timeout >0 and <=120
seconds. No user-selected endpoints or IMAP OAuth authentication. Plaintext is
rejected unless insecure_loopback_mock: true AND both endpoints are loopback;
this explicit setting is for local mock development only. TLS always verifies
certificates/hostnames and STARTTLS failure never falls back to plaintext. The
entire short-lived stdlib connection lifecycle runs off the event loop, with
socket timeouts and cleanup on cancellation. See the backend contract in
plugins/mail/backends/base.py.
IMAP search defaults to INBOX. Structured criteria AND with a validated standard
IMAP SEARCH raw_query; arbitrary commands, literals and unknown extensions are
rejected. has_attachment is explicitly unsupported; inspect attachments on the
bounded returned messages instead. SEARCH text currently requires printable
ASCII (Unicode message bodies/folder names are supported). Results report
total_matches and truncated, with at most 50 message summaries.
IMAP identities retain folder, UIDVALIDITY and UID inside the opaque handle;
every operation checks UIDVALIDITY and asks to search again if it changed. Reads
use read-only selection and BODY.PEEK, never setting Seen. Sent/Drafts/Trash/
Archive folders must be explicitly configured or discoverable via SPECIAL-USE;
missing folders fail with setup guidance, never guessed/created. Restore moves
from Trash to INBOX; it cannot infer the original folder. Safe delete requires
UIDPLUS and safe move requires MOVE or UIDPLUS; no global EXPUNGE is ever used.
Threads report threads: emulated, even on servers advertising native THREAD:
References/In-Reply-To reconstruction scans the latest 100 messages plus the
selected anchor in one folder. complete: false, scan count and truncation are
explicit; this is not a complete cross-folder conversation. Native THREAD and
unbounded mailbox exports are not implemented.
SMTP envelopes include To/Cc/Bcc but wire/Sent copies omit Bcc. New outgoing
attachments are unsupported; sending an existing MIME draft preserves its parts.
SMTPUTF8 addresses and Resent-* drafts are explicitly unsupported. SMTP accepted
mail returns sent: true even if later Sent APPEND/draft cleanup fails, with
sent_copy_saved, draft_deleted and warnings. Partial recipient refusal reports
refused_recipients and retains a sent draft rather than encouraging a duplicate
send. Connection loss during submission reports unknown delivery state and asks
to check delivery before retrying; no automatic resend occurs. The Sent folder is
preflighted before submission, but a server can still reject its later APPEND.
Attachments use the standard conversation staging service, producer mail, never
invented repository paths. Downloading a part currently fetches its complete MIME
message, rejecting messages above the configured staging ceiling before transfer;
normal reads have a 50 MiB message ceiling. See local mock setup
for the separate opt-in GreenMail workflow and password-free overlay.
Real backend integration (external pinned GreenMail JAR and Java required, no
download/start during ordinary tests):
tmp=$(mktemp -d /tmp/cdm-imap-integration.XXXXXX)
trap 'rm -rf "$tmp"' EXIT
TMPDIR="$tmp" RUN_SLOW_TESTS=1 \
GREENMAIL_JAR=/absolute/path/greenmail-standalone-2.1.15.jar \
./.venv/bin/python -m pytest tests/test_mail_imap_integration.py -q -s
The test owns its loopback JVM, random ports, deterministic fixtures, encrypted
per-user credential store and staging directory, then terminates the JVM even on
failure. JVM and clients run in the same network namespace. TLS certificate and
STARTTLS policy have fake-transport coverage; a real TLS handshake/provider
conformance test is not included.