@chamvi/tool-mail
Mail tools for chamvi agents: mailTools() searches, reads and threads mails and extracts attachment text over IMAP (Gmail, dovecot, Cyrus, ...) without ever changing a mailbox; mailWriteTools() sends mail over SMTP and moves mails to Trash, behind approvals. The public API of packages/tool-mail/src/index.ts and its /module entry. See Mail and calendar tools for an example.
npm install @chamvi/tool-mail @chamvi/core ai --save@chamvi/core and ai are peer dependencies; @chamvi/app is an optional peer of @chamvi/tool-mail/module.
mailTools
function mailTools(options?: MailToolsOptions): ToolSet; // { mail_accounts, mail_search, mail_get, mail_attachment, mail_thread }
function createMailClient(accounts: MailAccount[], options?: MailClientOptions): IMailClient;
const MAIL_REQUEST_ERROR_CODE: 'mail_request';
const MAIL_TIMEOUT_MS: 30_000;
const MAIL_SEARCH_DEFAULT_LIMIT: 20;
const MAIL_SEARCH_MAX_LIMIT: 50;
const MAIL_THREAD_MAX_REFERENCES: 10;
const MAIL_BODY_MAX_CHARS: 50_000;
const MAIL_ATTACHMENT_MAX_CHARS: 20_000;
const MAIL_HTML_MAX_CHARS: 1_000_000;
const MAIL_PDF_MAX_PAGES: 50;
const MAIL_ZIP_PART_MAX_BYTES: 10_485_760;
const MAIL_ZIP_TOTAL_MAX_BYTES: 20_971_520;
const MAIL_OOXML_MAX_SLIDES: 200;
const MAIL_SUBJECT_MAX_CHARS: 1000;
const MAIL_ADDRESSES_MAX_CHARS: 2000;
const MAIL_INVITE_FIELD_MAX_CHARS: 500;
const MAIL_INVITES_MAX: 10;
const MAIL_FETCH_MAX_BYTES: 26_214_400;The tools use client, else a client of accounts, else the client the module provided on the engine (without one, each call fails with context_not_provided). Throws InvalidAgentDefinitionError for options that are no object, a client that is no mail client, an account without id (^[a-z0-9]+(-[a-z0-9]+)*$), host, user or password, a bad security, port, address, folders or gmail, a duplicate id, a timeoutMs that is no integer from 1 to 2^31 - 1 and a clock without now() and setTimeout(). No message echoes a value.
| Tool | Input | Result |
|---|---|---|
mail_accounts | none | MailAccountView[]: each account with its folders (path, special use) |
mail_search | account, query?, folder?, from?, to?, subject?, since?, before? (ISO dates), unread?, limit? (default 20, at most 50) | MailSearchResult: summaries newest first, truncated when more matched |
mail_get | id, offset? | MailMessage: headers (subject cut at 1 000 characters, address lists at 2 000), the text body (HTML stripped) in pages of 50 000 characters, up to 10 invite summaries, the attachment list |
mail_attachment | id, index, offset? | MailAttachmentText: the text of a PDF (the first 50 pages), docx, xlsx, pptx or text file in pages of 20 000 characters; (text extraction failed) for a broken file |
mail_thread | id, limit? | MailSearchResult: the other mails of the thread, across the folders and Sent |
- Read-only. Folders are opened with
EXAMINE, neverSELECT; every body fetch isBODY.PEEK, so\Seenstays as it is; IDLE is off. The client has no method that writes. - Mail ids are
<account>:<folder>:<uidValidity>:<uid>(the folder base64url-encoded), issued by the tools. An unknown account, a folder outside the account's folders (refused before it is opened), a changedUIDVALIDITYor a missing uid is aValidationError(mail id is stale, search again). - Folders. Without
folder, a search coversaccount.folders, else on Gmail All Mail, else every folder but trash and spam. On Gmailqueryis Gmail search syntax and threads followX-GM-THRID; elsewherequeryis IMAP full text and threads followMessage-ID,In-Reply-Toand the last 10References. - Caps. A mail above 25 MiB is not fetched (
truncated: true, headers and attachments only). HTML is cut at 1 000 000 characters before stripping; OOXML parts above 10 MiB are skipped. Attachment bytes are never returned or stored. - Errors. A malformed input is a
ValidationError; a failed request (login, connection, a timeout aftertimeoutMson the clock) aChamviErrorwith codemail_requestand the message<tool>: <account>: <reason>, never the server's text or a credential. Both are tool errors the model reads.
Every tool declares trust: { taint: true }: a result taints the run.
mailWriteTools
function mailWriteTools(options?: MailWriteToolsOptions): ToolSet; // { mail_send, mail_delete }
function createMailWriteClient(accounts: MailWriteAccount[], options?: MailClientOptions): IMailWriteClient;
function provideMailWriteContext(provider: IContextProvider, client: IMailWriteClient): void;
function injectMailWriteContext(ctx: ToolContext): IMailWriteClient;
const MAIL_EFFECT_HEADER: 'X-Chamvi-Effect';
type MailSmtpSettings = { host: string; port?: number; security?: 'tls' | 'starttls' | 'plain' }; // port 465, 587, 25
type MailWriteAccount = MailAccount & { smtp?: MailSmtpSettings };
type MailWriteToolsOptions = {
accounts?: MailWriteAccount[];
client?: IMailWriteClient; // wins over accounts
clock?: IClock;
timeoutMs?: number;
classifier?: { model?: ModelRef }; // the delete classifier, default the agent's model
deleteLimit?: MailDeleteLimitSettings | false; // mail_delete's own limit; false: none
};
type MailDeleteLimitSettings = { max?: number; windowMs?: number; bucket?: string }; // default 20, 1 h, 'deletes'The tools use client, else a client of accounts, else the write client the module provided on the engine. mail_delete carries its own limit (deleteLimit), so the engine needs a limitService unless deleteLimit: false (or the agent sets limits: { mail_delete: false }).
| Tool | Input | Result |
|---|---|---|
mail_send | account, to, cc?, bcc? (at most 50 recipients), subject (at most 500 characters), text (at most 100 000), inReplyTo? (a mail id) | MailSendResult: the Message-ID, filed (a copy is in \Sent), refused recipients |
mail_delete | ids (1 to 20 distinct mail ids) | MailDeleteResult: moved, missing, the trash folder |
- Approvals.
mail_sendalways asks, with the whole mail.mail_deletechecks the limit first; over it the call asks for an approval listing the mails, which also skips the classifier when it listed every mail (not when only folders and uids could be shown, and not for an agentlimits.mail_deleteentry, which replaces the tool's limit whole and shows no listing). A call that passed the limit counts even when the delete approval refuses it. Within the limit a classifier reads from, subject, folder and date only:routinemoves,ask(also any failure) asks. Approvals reach the source chat only when its address is a direct chat, else only the inbox and API. - Wire. The write client sends
LOGIN,LIST,LSUB,EXAMINE,UID SEARCH,UID FETCH,APPENDand, right beforeUID MOVEonly,SELECT, plus SMTP. NeverEXPUNGE,CLOSE,STORE,COPYorDELETE;UID MOVEneeds theMOVEcapability or an active IMAP4rev2 session and goes to the\Trashfolder by special-use flag. - Send. The wire copy has no
Bcc:header, the\Sentcopy keeps it. The mail carriesX-Chamvi-Effectand a Message-ID derived from the call, so a retry finds it in Sent instead of sending again. Addresses are printable ASCII; the subject has no control, zero-width or bidi characters. A timeout after the message was handed over fails withtimed out after the message was handed over; it may have been sent. - Errors. A failed request is a
ChamviErrorwith codemail_request, a refusal by the owner aToolDeniedError.
toolMailModule
// @chamvi/tool-mail/module
function toolMailModule(options?: ToolMailModuleOptions): ToolMailModule; // 'chamvi:tool-mail'
type ToolMailModuleOptions = {
env?: Record<string, string | undefined>; // where MAIL_* is read, default process.env
accounts?: MailWriteAccount[]; // given, MAIL_ACCOUNTS is not read
};
const TOOL_MAIL_MODULE_NAME: 'chamvi:tool-mail';
const MAIL_ACCOUNTS_VARIABLE: 'MAIL_ACCOUNTS';| Variable | |
|---|---|
MAIL_ACCOUNTS | A JSON array of { "id"?, "address", "host", "port"?, "security"?, "folders"?, "gmail"?, "smtp"?: { "host", "port"?, "security"? } }; id defaults to the address with @ and . as - |
MAIL_<ID>_USER | The account's user, default the address; <ID> is the id upper-cased, - as _ |
MAIL_<ID>_PASSWORD | Required |
For an account listed in MAIL_ACCOUNTS each credential can come from a file instead: MAIL_<ID>_PASSWORD_FILE (one trailing newline trimmed; setting both forms is an error). The variables are read and checked when the factory is called; an error names the variable and index, never a value. Accounts stored in the connection store (added on the dashboard through toolMailUiModule()) are added at start (accounts pins the set). For an account listed in MAIL_ACCOUNTS a variable wins per field over its stored value, and a password in neither env nor store fails at startup naming the variable. An account that exists only in the store takes every value from the store: a MAIL_<ID>_* variable named after it is ignored with a warning naming the variable, and a missing password lists it incomplete. Without any account the context stays provided and tools return a connection_not_configured tool error. In start and job mode and a check it builds one client on the app's clock, provides it on the engine (injectMailContext(ctx)) and logs out once the engine drained; migrate mode does nothing.
Types
type MailAccount = {
id: string;
host: string;
port?: number; // default 993 with tls, else 143
security?: 'tls' | 'starttls' | 'plain'; // default tls
user: string;
password: string; // Gmail: an app password
address?: string; // default user
folders?: string[]; // the folders searched and read
gmail?: boolean; // default host === 'imap.gmail.com'
};
// stored connections: smtpHost, smtpPort, smtpSecurity
type MailToolsOptions = {
accounts?: MailAccount[];
client?: IMailClient; // wins over accounts
clock?: IClock;
timeoutMs?: number; // default 30 s per call, connecting included
};
type MailClientOptions = { clock?: IClock; timeoutMs?: number };
interface IMailClient {
accounts(signal?: AbortSignal): Promise<MailAccountView[]>;
search(input: MailSearchInput, signal?: AbortSignal): Promise<MailSearchResult>;
get(id: string, offset?: number, signal?: AbortSignal): Promise<MailMessage>;
attachment(id: string, index: number, offset?: number, signal?: AbortSignal): Promise<MailAttachmentText>;
thread(id: string, limit?: number, signal?: AbortSignal): Promise<MailSearchResult>;
close(): Promise<void>; // logs out of every account
}
function provideMailContext(provider: IContextProvider, client: IMailClient): void;
function injectMailContext(ctx: ToolContext): IMailClient; // ContextNotProvidedError without one
function encodeMailId(parts: MailIdParts): string;
function parseMailId(id: unknown): MailIdParts; // ValidationError for anything elseMailSummary, MailMessage, MailAttachmentInfo, MailAttachmentText, MailAccountView, MailFolderView, MailSearchInput, MailSearchResult and MailIdParts are exported too; the package README lists their fields.