@ghostpaw/email 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ghostpaw/email",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Standalone IMAP/SMTP email engine for Node.js — SQLite local cache, threading, sync, zero dependencies, with a built-in LLM tool facade",
5
5
  "type": "module",
6
6
  "exports": {
@@ -13,17 +13,30 @@
13
13
  "types": "./dist/index.d.cts",
14
14
  "default": "./dist/index.cjs"
15
15
  }
16
- }
16
+ },
17
+ "./mcp": {
18
+ "import": {
19
+ "types": "./dist/mcp.d.ts",
20
+ "default": "./dist/mcp.js"
21
+ },
22
+ "require": {
23
+ "types": "./dist/mcp.d.cts",
24
+ "default": "./dist/mcp.cjs"
25
+ }
26
+ },
27
+ "./package.json": "./package.json"
17
28
  },
18
29
  "main": "./dist/index.cjs",
19
30
  "module": "./dist/index.js",
20
31
  "types": "./dist/index.d.ts",
21
32
  "bin": {
22
- "email": "./dist/cli.js"
33
+ "email": "./dist/cli.js",
34
+ "ghostpaw-email": "./dist/cli.js"
23
35
  },
24
36
  "files": [
25
37
  "dist",
26
- "SKILL.md"
38
+ "SKILL.md",
39
+ "skills"
27
40
  ],
28
41
  "sideEffects": false,
29
42
  "scripts": {
@@ -34,14 +47,26 @@
34
47
  "lint:fix": "biome check --fix",
35
48
  "format": "biome format --write",
36
49
  "typecheck": "tsc --noEmit",
37
- "check": "biome check && tsc --noEmit",
50
+ "check": "npm run check:types && npm run check:lint && npm test && npm run build && npm run check:deps && npm run check:surfaces && npm run check:size && npm run check:api && npm run check:consumer && npm run check:startup && npm run check:ratchet",
38
51
  "check:deps": "node scripts/check-zero-deps.mjs",
39
52
  "clean": "rm -rf dist",
40
- "version": "biome format --write package.json package-lock.json && git add package.json package-lock.json",
41
- "prepublishOnly": "npm run check && npm run build",
53
+ "version": "node scripts/sync_version.mjs && npm run surfaces && git add src/version.ts SKILL.md skills plugin.json mcp.json server.json .claude-plugin mcpb && biome format --write package.json package-lock.json && git add package.json package-lock.json",
54
+ "prepublishOnly": "npm run check",
42
55
  "release:patch": "npm version patch && git push && git push --tags",
43
56
  "release:minor": "npm version minor && git push && git push --tags",
44
- "release:major": "npm version major && git push && git push --tags"
57
+ "release:major": "npm version major && git push && git push --tags",
58
+ "surfaces": "node --experimental-strip-types scripts/surfaces/generate.mjs",
59
+ "check:surfaces": "node --experimental-strip-types scripts/surfaces/generate.mjs --check",
60
+ "check:types": "tsc --noEmit",
61
+ "check:lint": "biome check",
62
+ "check:ratchet": "node --test scripts/guard/*.test.mjs && node scripts/guard/ratchet.mjs",
63
+ "budgets:update": "npm run build && node scripts/guard/size.mjs --update && node scripts/guard/api.mjs --update && node scripts/guard/startup.mjs --update",
64
+ "bench": "npm run build && node scripts/bench/bench.mjs",
65
+ "check:size": "node scripts/guard/size.mjs",
66
+ "check:api": "node scripts/guard/api.mjs",
67
+ "check:consumer": "node scripts/guard/consumer.mjs",
68
+ "check:startup": "node scripts/guard/startup.mjs",
69
+ "mcpb": "node scripts/mcpb/build.mjs"
45
70
  },
46
71
  "engines": {
47
72
  "node": ">=24"
@@ -69,7 +94,12 @@
69
94
  "agent",
70
95
  "tools",
71
96
  "typescript",
72
- "zero-dependencies"
97
+ "zero-dependencies",
98
+ "mcp",
99
+ "mcp-server",
100
+ "model-context-protocol",
101
+ "agent-skills",
102
+ "cli"
73
103
  ],
74
104
  "license": "MIT",
75
105
  "repository": {
@@ -81,7 +111,7 @@
81
111
  "email": "max@anonyfox.com",
82
112
  "url": "https://anonyfox.com"
83
113
  },
84
- "homepage": "https://github.com/GhostPawJS/email",
114
+ "homepage": "https://email.ghostpaw.dev/",
85
115
  "bugs": {
86
116
  "url": "https://github.com/GhostPawJS/email/issues"
87
117
  },
@@ -97,7 +127,9 @@
97
127
  "@types/node": "^25.3.0",
98
128
  "citty": "^0.1.6",
99
129
  "esbuild": "^0.27.4",
130
+ "fflate": "0.8.3",
100
131
  "tsup": "^8.4.0",
101
132
  "typescript": "^5.9.3"
102
- }
133
+ },
134
+ "mcpName": "io.github.GhostPawJS/email"
103
135
  }
@@ -0,0 +1,131 @@
1
+ ---
2
+ name: email
3
+ description: "Read, search, compose, organize and synchronize email with a local SQLite cache. Use when managing email or searching cached messages."
4
+ license: "MIT"
5
+ compatibility: "Node.js 24 or newer. MCP stdio or email CLI."
6
+ ---
7
+
8
+ # email
9
+
10
+ Read and search cached email offline. Configure live accounts with email account add before network operations. Inspect messages before replying or changing folders. Confirm recipients and content before sending; trash and folder deletion can remove mail. Credentials use the existing email CLI account configuration or EMAIL_* environment variables.
11
+
12
+ ## Calling tools
13
+
14
+ MCP: connect to ghostpaw-email, then call a tool by name with its JSON arguments.
15
+
16
+ CLI: `ghostpaw-email call <tool> '<JSON object>'` or `ghostpaw-email <tool> --parameter value` (without a global install: `npx -y @ghostpaw/email <tool> ...`).
17
+
18
+ Inspect schemas with `ghostpaw-email describe <tool>`. Use `--db <path>` to select a database.
19
+
20
+ ## mail_read
21
+
22
+ Read mailbox state: folder list, message queue, thread view, single message body, attachment metadata, or raw EML export.
23
+
24
+ Use when: Inspect folders, cached messages, threads, attachments or raw message content.
25
+
26
+ Not for: Use mail_search to find messages by query or mail_organize to change them.
27
+
28
+ Writes: writes_state.
29
+
30
+ | Parameter | Type | Required | Values / description |
31
+ | --- | --- | --- | --- |
32
+ | view | string | yes | folders, queue, thread, message, attachment, eml. What to read. |
33
+ | folder | string | no | Folder path (required for queue/message/attachment/eml). |
34
+ | uid | integer | no | Message UID (required for message/attachment/eml). |
35
+ | threadId | string | no | Thread ID (required for thread view). |
36
+ | partPath | string | no | Part path for a specific attachment (optional for attachment view). |
37
+ | limit | integer | no | Maximum messages to return (queue view). |
38
+ | unreadOnly | boolean | no | Filter to unread messages only (queue view). |
39
+ | refresh | boolean | no | Fetch live folder list from server before returning (folders/queue view). |
40
+
41
+ ## mail_search
42
+
43
+ Search for messages locally via FTS or remotely via IMAP SEARCH. Returns matching message references.
44
+
45
+ Use when: Find messages by a local full-text query or a remote IMAP search.
46
+
47
+ Not for: Use mail_read when the folder and message UID are already known.
48
+
49
+ Writes: writes_state.
50
+
51
+ | Parameter | Type | Required | Values / description |
52
+ | --- | --- | --- | --- |
53
+ | query | string | yes | Free-text search query or FTS5 expression. |
54
+ | folder | string | no | Restrict search to a specific folder. |
55
+ | mode | string | no | local, remote. local (default) or remote IMAP SEARCH. |
56
+ | since | string | no | ISO date string — only messages after this date. |
57
+ | before | string | no | ISO date string — only messages before this date. |
58
+ | hasAttachments | boolean | no | Filter to messages with attachments. |
59
+ | unreadOnly | boolean | no | Filter to unread messages. |
60
+ | limit | integer | no | Maximum number of results. |
61
+
62
+ ## mail_compose
63
+
64
+ Compose and send email: send new message, reply, forward, save/update/send a draft.
65
+
66
+ Use when: Send, reply, forward, or save and manage a draft after its content is agreed.
67
+
68
+ Not for: Use mail_read to inspect an existing message without sending or saving content.
69
+
70
+ Writes: writes_state.
71
+
72
+ | Parameter | Type | Required | Values / description |
73
+ | --- | --- | --- | --- |
74
+ | action | string | yes | send, reply, forward, save_draft, update_draft, send_draft. |
75
+ | folder | string | no | Source folder (required for reply/forward). |
76
+ | uid | integer | no | Source message UID (required for reply/forward/update_draft/send_draft). |
77
+ | input | object | no | ComposeInput / ReplyInput / ForwardInput payload. |
78
+
79
+ ## mail_organize
80
+
81
+ Organize messages: mark read/unread/starred/answered, copy, move, archive, trash, junk, label, or manage folders.
82
+
83
+ Use when: Change message flags, labels, destinations or folder organization.
84
+
85
+ Not for: Use mail_read or mail_search when only inspection is requested.
86
+
87
+ Writes: writes_state.
88
+
89
+ | Parameter | Type | Required | Values / description |
90
+ | --- | --- | --- | --- |
91
+ | action | string | yes | mark_read, mark_unread, star, unstar, mark_answered, copy, move, archive, trash, junk, not_junk, set_labels, add_labels, remove_labels, create_folder, rename_folder, delete_folder, subscribe_folder, unsubscribe_folder. |
92
+ | folder | string | no | Source folder (required for message actions). |
93
+ | uids | array | no | Message UIDs to act on. |
94
+ | destination | string | no | Destination folder (required for copy/move). |
95
+ | labels | array | no | Labels to set/add/remove. |
96
+ | path | string | no | Folder path (required for folder actions). |
97
+ | oldPath | string | no | Old folder path (required for rename_folder). |
98
+ | newPath | string | no | New folder path (required for rename_folder). |
99
+
100
+ ## mail_sync
101
+
102
+ Manage the IMAP connection lifecycle and sync local state: connect, disconnect, reconnect, sync folders, or refresh the folder list.
103
+
104
+ Use when: Connect, disconnect, reconnect, refresh folders or synchronize the cache.
105
+
106
+ Not for: Use mail_read for cached content or the network watch stream for continuous monitoring.
107
+
108
+ Writes: writes_state.
109
+
110
+ | Parameter | Type | Required | Values / description |
111
+ | --- | --- | --- | --- |
112
+ | action | string | yes | connect, disconnect, reconnect, sync, refresh_folders, watch. |
113
+ | folders | array | no | Folders to sync or watch (optional — defaults to all subscribed folders). |
114
+ | bodies | string | no | none, missing, all. Body fetch strategy for sync (default: missing). |
115
+
116
+ ## Workflow guides
117
+
118
+ - [triage-inbox](references/triage-inbox.md): Process a full inbox from scratch: sync to get latest state, read message queue, selectively fetch bodies for decisions, then bulk-organize by priority.
119
+ - [read-and-reply](references/read-and-reply.md): Read a message with full thread context, then compose and send a properly-threaded reply with quoted attribution.
120
+ - [connect-and-sync](references/connect-and-sync.md): Establish or restore an IMAP connection, refresh the folder list, and pull new messages — handling first-run vs incremental scenarios.
121
+ - [search-and-act](references/search-and-act.md): Find messages matching criteria (local FTS first, remote IMAP SEARCH as fallback), verify targets, then act — organize, reply, or present.
122
+ - [compose-and-send](references/compose-and-send.md): Full draft lifecycle — save, review, update, then send — plus direct send, reply, and forward with proper threading and forwarded-header blocks.
123
+ - [organize-bulk](references/organize-bulk.md): Bulk organize messages across folders — flagging, moving, archiving, labelling — and manage the folder hierarchy as part of the flow.
124
+ - [attachment-workflow](references/attachment-workflow.md): Discover, inspect, and fetch email attachments on demand; embed attachments in outbound messages; and export or import full .eml files.
125
+ - [recover-from-disruption](references/recover-from-disruption.md): Detect and recover from connection loss or IMAP/SMTP failures — reconnect with back-off, re-sync to reconcile state, and handle auth vs transient errors distinctly.
126
+ - [cli](references/cli.md): Complete existing email CLI guide.
127
+
128
+ ## Principles
129
+
130
+ - Inspect before changing messages.
131
+ - Confirm recipients and content before sending.
@@ -0,0 +1,25 @@
1
+ # Attachment Workflow
2
+
3
+ Primary tools:
4
+ - `mail_read`
5
+ - `mail_compose`
6
+ - `mail_sync`
7
+
8
+ Steps:
9
+ 1. Use `mail_read { view: "attachment", folder, uid }` (without `partPath`) to list all attachment metadata for a message. Returns filename, MIME type, size, and `partPath` for each attachment. This call is local — no network fetch.
10
+ 2. Review attachment metadata before deciding what to fetch. For attachments larger than a few MB, confirm intent before fetching binary content.
11
+ 3. Use `mail_read { view: "attachment", folder, uid, partPath }` to fetch the binary content of a specific attachment. If the body is not yet cached, this triggers an on-demand IMAP FETCH for that MIME part.
12
+ 4. Part paths (`1`, `1.2`, `2.1.1`, etc.) are MIME-tree references. They are stable per-message but server-assigned — always use the `partPath` value from the metadata list, never guess.
13
+ 5. For outbound attachments, include them in the `ComposeInput.attachments` array when calling `mail_compose { action: "send" }` or `mail_compose { action: "save_draft" }`.
14
+ 6. To export a full message with all attachments as a self-contained file, use `mail_read { view: "eml", folder, uid }` to get the raw RFC 2822 bytes as a Buffer.
15
+
16
+ Outcome handling:
17
+ - An empty attachment list (0 entities) means the message has `hasAttachments: false` locally, or the body has not been fetched yet. Run `mail_sync { action: "sync", folders: [folder] }` to pull the body, then retry.
18
+ - If a specific attachment fetch fails, the part may have been stripped by the server or the MIME structure may differ from the stored BODYSTRUCTURE. Try re-fetching the full body first.
19
+ - `attachment.data` is a raw `Buffer` — the application layer is responsible for rendering or saving it; tools return the bytes only.
20
+
21
+ Failure handling:
22
+ - Do not fetch all attachments from a batch of messages speculatively — only fetch binary content when explicitly needed.
23
+ - Do not assume `inline: true` attachments are unimportant — inline images and signed content use the inline flag.
24
+ - If `getAttachment` returns stale or empty data, retry after a fresh `mail_sync` pass. Part caching is per-UID/partPath.
25
+ - For very large attachments (>25MB), the on-demand fetch may time out — inform the user and suggest downloading via webmail instead.
@@ -0,0 +1,283 @@
1
+ # SKILL.md — `email` CLI as an Agent Tool Surface
2
+
3
+ The `email` binary is a local-first email CLI built on top of `@ghostpaw/email`. It exposes five
4
+ intent-shaped commands that map directly to the library's tool layer. Agents invoke it as a
5
+ subprocess via bash; no MCP server or standing process is needed.
6
+
7
+ ---
8
+
9
+ ## Prerequisites
10
+
11
+ - Node.js ≥ 24
12
+ - Install once:
13
+ ```bash
14
+ npm install -g @ghostpaw/email # global install, `email` in PATH
15
+ npx @ghostpaw/email account add ... # or zero-install via npx
16
+ ```
17
+
18
+ ---
19
+
20
+ ## Account Setup
21
+
22
+ ```bash
23
+ email account add \
24
+ --name work \
25
+ --imap-host imap.fastmail.com --imap-port 993 \
26
+ --smtp-host smtp.fastmail.com --smtp-port 587 \
27
+ --user me@fastmail.com --pass "app-password"
28
+
29
+ email account list # see all accounts
30
+ email account set-default --name work
31
+ email account show # shows config (password redacted)
32
+ ```
33
+
34
+ ### Environment variables (no config file needed — useful in CI)
35
+
36
+ | Variable | Purpose |
37
+ |---|---|
38
+ | `EMAIL_ACCOUNT` | Select account by slug |
39
+ | `EMAIL_IMAP_HOST` | IMAP hostname |
40
+ | `EMAIL_IMAP_PORT` | IMAP port (default: 993) |
41
+ | `EMAIL_IMAP_TLS` | `"false"` to disable TLS |
42
+ | `EMAIL_SMTP_HOST` | SMTP hostname |
43
+ | `EMAIL_SMTP_PORT` | SMTP port (default: 587) |
44
+ | `EMAIL_SMTP_TLS` | `"false"` to disable TLS |
45
+ | `EMAIL_USER` | Auth username |
46
+ | `EMAIL_PASS` | Password auth |
47
+ | `EMAIL_ACCESS_TOKEN` | OAuth2 access token |
48
+ | `EMAIL_REFRESH_TOKEN` | OAuth2 refresh token |
49
+ | `EMAIL_CONFIG_DIR` | Override config directory (full path) |
50
+ | `EMAIL_DATA_DIR` | Override SQLite data directory (full path) |
51
+ | `NO_COLOR` | Disable ANSI color output |
52
+
53
+ ---
54
+
55
+ ## `--json` — Machine-Readable Output
56
+
57
+ **Always use `--json` when invoking from an agent.** Every command outputs a JSON object:
58
+
59
+ ```json
60
+ {
61
+ "outcome": "success",
62
+ "summary": "42 message(s) in INBOX.",
63
+ "entities": [
64
+ { "kind": "message", "id": "1921", "title": "Re: Q2 roadmap" }
65
+ ],
66
+ "nextSteps": [
67
+ "Use view: \"message\" with folder and uid to read a specific message."
68
+ ]
69
+ }
70
+ ```
71
+
72
+ `outcome` values:
73
+ - `"success"` — operation completed
74
+ - `"no_op"` — nothing to do (not an error)
75
+ - `"needs_clarification"` — more information required; check `nextSteps`
76
+ - `"error"` — operation failed; check `summary` for details and `nextSteps` for guidance
77
+
78
+ **On error, `--json` output still goes to stdout** (not stderr) so downstream parsers can always
79
+ parse stdout unconditionally.
80
+
81
+ ---
82
+
83
+ ## Exit Codes
84
+
85
+ | Code | When |
86
+ |---|---|
87
+ | `0` | `success` or `no_op` |
88
+ | `1` | Missing required flag, invalid value, body required |
89
+ | `2` | No config, malformed config, unknown account, no default account |
90
+ | `3` | Authentication failure |
91
+ | `4` | Network / connection failure |
92
+ | `5` | Tool returned `outcome: "error"` |
93
+ | `6` | Tool returned `outcome: "needs_clarification"` |
94
+ | `127` | Unexpected / unhandled error |
95
+
96
+ ---
97
+
98
+ ## Commands
99
+
100
+ ### `email read [view]`
101
+
102
+ Read mailbox state. Default view: `queue` (INBOX).
103
+
104
+ ```bash
105
+ email read --json # queue view, INBOX
106
+ email read folders --json # list all folders
107
+ email read queue --folder Sent --limit 20 --json
108
+ email read queue --unread-only --json
109
+ email read thread --thread-id <id> --json
110
+ email read message --folder INBOX --uid 1921 --json
111
+ email read attachment --folder INBOX --uid 1921 --json # list attachments
112
+ email read eml --folder INBOX --uid 1921 # raw EML bytes to stdout
113
+ ```
114
+
115
+ **`eml` view:** writes raw EML bytes to stdout. In `--json` mode the bytes are base64-encoded
116
+ under a `"data"` key.
117
+
118
+ ```bash
119
+ email read eml --folder INBOX --uid 42 > message.eml
120
+ email read eml --folder INBOX --uid 42 --json | jq -r '.data' | base64 -d > message.eml
121
+ ```
122
+
123
+ ### `email search <query>`
124
+
125
+ Search messages via local FTS5 (default) or remote IMAP SEARCH.
126
+
127
+ ```bash
128
+ email search "invoice" --json
129
+ email search "from:boss@work.com subject:quarterly" --json
130
+ email search "budget 2026" --folder Archive --limit 10 --json
131
+ email search "urgent" --mode remote --json
132
+ email search "report" --since 2026-01-01 --before 2026-04-01 --json
133
+ email search "contract" --has-attachments --json
134
+ ```
135
+
136
+ ### `email compose <action>`
137
+
138
+ Compose and send email. Body comes from `--body` or piped stdin.
139
+
140
+ ```bash
141
+ # Send
142
+ email compose send --to alice@example.com --subject "Hello" --body "Hi there" --json
143
+ echo "Meeting at 3pm?" | email compose send --to alice@example.com --subject "Quick question"
144
+
145
+ # Reply (body from stdin)
146
+ echo "Sounds good!" | email compose reply --folder INBOX --uid 1921
147
+
148
+ # Reply-all
149
+ email compose reply --folder INBOX --uid 1921 --body "Thanks all" --reply-all --json
150
+
151
+ # Forward
152
+ email compose forward --folder INBOX --uid 1921 --to bob@example.com --body "FYI" --json
153
+
154
+ # Attach files (comma-separated paths)
155
+ email compose send --to a@b.com --subject "Report" --body "See attached" \
156
+ --attach /path/to/report.pdf,/path/to/data.csv --json
157
+
158
+ # Drafts
159
+ email compose draft --save --to a@b.com --subject "Draft" --body "WIP" --json
160
+ email compose draft --send-draft 42 --json
161
+ ```
162
+
163
+ ### `email organize <action>`
164
+
165
+ Organize messages and folders. `--uids` accepts comma-separated UIDs.
166
+
167
+ ```bash
168
+ email organize mark-read --folder INBOX --uids 1,2,3 --json
169
+ email organize star --folder INBOX --uids 42 --json
170
+ email organize archive --folder INBOX --uids 1921,1922 --json
171
+ email organize trash --folder INBOX --uids 1800 --json
172
+ email organize move --folder INBOX --uids 100 --destination Archive --json
173
+ email organize set-labels --folder INBOX --uids 42 --labels "work,priority" --json
174
+ email organize create-folder --path "Projects/2026" --json
175
+ email organize rename-folder --old-path "Projects" --new-path "Work/Projects" --json
176
+ email organize delete-folder --path "OldFolder" --json
177
+ ```
178
+
179
+ ### `email sync [action]`
180
+
181
+ Manage IMAP connection and sync local SQLite state. Default action: `sync`.
182
+
183
+ ```bash
184
+ email sync --json # sync all folders (default)
185
+ email sync sync --folders INBOX,Sent --json
186
+ email sync sync --bodies all --json # fetch all bodies
187
+ email sync refresh-folders --json
188
+ email sync connect --json
189
+ email sync disconnect --json
190
+ email sync watch --json # syncs then exits; continuous watching needs the library
191
+ ```
192
+
193
+ ---
194
+
195
+ ## Multi-Step Workflow Examples
196
+
197
+ ### Triage inbox
198
+
199
+ ```bash
200
+ # Get unread messages
201
+ UNREAD=$(email read queue --unread-only --json)
202
+ echo "$UNREAD" | jq '.entities[].id'
203
+
204
+ # Archive a batch
205
+ email organize archive --folder INBOX --uids 1,2,3 --json
206
+ ```
207
+
208
+ ### Read and reply
209
+
210
+ ```bash
211
+ # Read a specific message
212
+ MSG=$(email read message --folder INBOX --uid 1921 --json)
213
+ echo "$MSG" | jq '.summary'
214
+
215
+ # Reply
216
+ echo "Thanks, will do." | email compose reply --folder INBOX --uid 1921 --json
217
+ ```
218
+
219
+ ### Search and act
220
+
221
+ ```bash
222
+ # Find all invoices from last month
223
+ RESULTS=$(email search "invoice" --since 2026-02-01 --before 2026-03-01 --json)
224
+ UIDS=$(echo "$RESULTS" | jq -r '.entities[].id' | tr '\n' ',' | sed 's/,$//')
225
+
226
+ # Move them to an Archive folder
227
+ email organize move --folder INBOX --uids "$UIDS" --destination Archive --json
228
+ ```
229
+
230
+ ### Full sync then read
231
+
232
+ ```bash
233
+ email sync --json
234
+ email read queue --limit 20 --json
235
+ ```
236
+
237
+ ### Export an attachment
238
+
239
+ ```bash
240
+ # List attachments
241
+ ATTS=$(email read attachment --folder INBOX --uid 1921 --json)
242
+ PART=$(echo "$ATTS" | jq -r '.entities[0].id')
243
+
244
+ # Download raw bytes
245
+ email read attachment --folder INBOX --uid 1921 --part-path "$PART" > attachment.pdf
246
+ ```
247
+
248
+ ---
249
+
250
+ ## Error Handling for Agents
251
+
252
+ - **Always check `outcome`** before acting on `entities`. Even exit code 0 can return `"no_op"`.
253
+ - **Do not retry auth errors** (exit 3) — they require credential changes.
254
+ - **On `needs_clarification`** (exit 6) — read `nextSteps` and ask the user for more information.
255
+ - **On `error`** (exit 5) — the tool's `summary` and `nextSteps` contain actionable guidance.
256
+ - **Network errors** (exit 4) — retry after a brief pause; check host/port if it persists.
257
+
258
+ ---
259
+
260
+ ## Piping Patterns
261
+
262
+ ```bash
263
+ # Pipe body from stdin
264
+ echo "Hello" | email compose send --to x@y.com --subject "Hi"
265
+
266
+ # Export EML and forward to another tool
267
+ email read eml --folder INBOX --uid 42 | mail -s "fwd" target@example.com
268
+
269
+ # JSON pipeline
270
+ email read queue --json | jq '.entities[] | select(.title | test("invoice"; "i")) | .id'
271
+
272
+ # Quiet mode — only exit code matters
273
+ email organize archive --folder INBOX --uids 42 --quiet && echo "archived"
274
+ ```
275
+
276
+ ---
277
+
278
+ ## What the CLI Does NOT Do
279
+
280
+ - **No persistent daemon.** Every invocation opens a fresh IMAP connection and closes it cleanly.
281
+ - **No continuous IDLE watch.** `email sync watch` syncs once and exits. For push-style updates,
282
+ use `Mailbox.network.watch()` from the library directly.
283
+ - **No interactive prompts.** All input comes from flags or stdin.
@@ -0,0 +1,30 @@
1
+ # Compose and Send
2
+
3
+ Primary tools:
4
+ - `mail_compose`
5
+ - `mail_read`
6
+ - `mail_sync`
7
+
8
+ Steps:
9
+ 1. For a new message that needs review before sending, use `mail_compose { action: "save_draft", input: { to, subject, textPlain, attachments? } }` to create a draft. Store the returned `uid`.
10
+ 2. Use `mail_read { view: "message", folder: "Drafts", uid }` to verify the draft content before sending.
11
+ 3. To update the draft (correcting body or recipients), use `mail_compose { action: "update_draft", uid, input: { ... } }`. The old draft is replaced and a new `uid` is returned.
12
+ 4. When ready to send, use `mail_compose { action: "send_draft", uid }`. This runs the full SMTP send, appends the message to the Sent folder, and expunges the draft.
13
+ 5. For immediate sends without a draft step, use `mail_compose { action: "send", input }` directly.
14
+ 6. For replies, always use `mail_compose { action: "reply", folder, uid, input: { text } }` — never plain `send`. This sets `In-Reply-To`, `References`, and prepends the attribution + quoted body automatically.
15
+ 7. For forwards, use `mail_compose { action: "forward", folder, uid, input }`:
16
+ - Inline mode (default): prepends "---------- Forwarded message ----------" header block with From/Date/Subject/To, then the original plaintext body.
17
+ - Attachment mode: wraps the original message as a `.eml` attachment.
18
+ 8. After any successful send, use `mail_read { view: "queue", folder: "Sent" }` to verify the copy was appended.
19
+
20
+ Outcome handling:
21
+ - `save_draft` returns `{ uid }` — use this uid for `update_draft` and `send_draft`.
22
+ - A `success` from `send`, `reply`, `forward`, or `send_draft` contains a `messageId` — this is the SMTP message ID, confirming the message left the server. Delivery to the recipient is async.
23
+ - If SMTP fails, the draft is NOT automatically deleted — retry `send_draft` after resolving the connection issue.
24
+
25
+ Failure handling:
26
+ - Do not send without at least one `to` recipient — the tool will return an error.
27
+ - Do not manually set `In-Reply-To` or `References` headers for replies — use `action: "reply"`, which handles threading automatically.
28
+ - Do not use `action: "send"` for replies; threading headers will be missing, breaking mail client thread views.
29
+ - If SMTP fails mid-send (after draft exists), use `mail_sync { action: "reconnect" }` to restore the session, then retry `send_draft`.
30
+ - Do not delete a draft until send returns `outcome: "success"` — a failed send must leave the draft intact for retry.
@@ -0,0 +1,29 @@
1
+ # Connect and Sync
2
+
3
+ Primary tools:
4
+ - `mail_sync`
5
+ - `mail_read`
6
+
7
+ Steps:
8
+ 1. Use `mail_sync { action: "connect" }` to open the IMAP connection. The session negotiates capabilities, authenticates (LOGIN / PLAIN / XOAUTH2 / OAUTHBEARER), and enables extensions (IDLE, COMPRESS=DEFLATE, CONDSTORE/QRESYNC) automatically.
9
+ 2. If connect fails, inspect the error message before retrying:
10
+ - Auth error → credentials are wrong; do not retry blindly. Surface the error to the user.
11
+ - Connection refused / timeout → transient network issue; retry once.
12
+ 3. After a successful connect, use `mail_sync { action: "refresh_folders" }` to get the current folder list. This detects new folders, updated role assignments (inbox/sent/drafts/trash/junk/archive), and subscription changes.
13
+ 4. Run `mail_sync { action: "sync", bodies: "missing" }` for normal incremental sync (default). The engine uses QRESYNC when available (flag changes + expunges in one round trip), falling back to UID-based comparison.
14
+ - Use `bodies: "all"` only when a full cache rebuild is explicitly needed.
15
+ - Pass `folders: ["INBOX", "Sent"]` to restrict to specific folders.
16
+ 5. After sync, use `mail_read { view: "folders" }` to verify the local folder state, then `mail_read { view: "queue", folder: "INBOX" }` to surface new messages.
17
+ 6. For continuous monitoring, `mail_sync { action: "watch" }` starts IMAP IDLE over selected folders — this requires a persistent application-layer connection and is not a single-call operation.
18
+
19
+ Outcome handling:
20
+ - `totalNew > 0` in the sync result means new messages arrived — run `mail_read queue` to surface them.
21
+ - `totalExpunged > 0` means messages were removed on the server; local state was reconciled automatically.
22
+ - A UIDVALIDITY reset (logged in sync result) means the entire folder cache was cleared and a full re-sync ran — this is normal after a server migration or mailbox recreation.
23
+ - `refresh_folders` returning fewer folders than expected may mean the subscription list changed on the server — check with the account's webmail interface.
24
+
25
+ Failure handling:
26
+ - Do not run `mail_sync sync` before `connect` succeeds — sync requires an active session.
27
+ - Do not retry `connect` more than 3 times without inspecting the error — auth failures need credential fixes, not retries.
28
+ - If `refresh_folders` returns 0 folders, something is wrong with the account — do not proceed to sync.
29
+ - If sync is interrupted mid-run, the next incremental sync will resume from the last known MODSEQ/UID — do not run a full sync unless explicitly requested.
@@ -0,0 +1,33 @@
1
+ # Organize Bulk
2
+
3
+ Primary tools:
4
+ - `mail_organize`
5
+ - `mail_search`
6
+ - `mail_read`
7
+ - `mail_sync`
8
+
9
+ Steps:
10
+ 1. Always identify the target messages first before acting. Use `mail_read { view: "queue", folder }` for recent messages or `mail_search { query }` for criteria-based selection. Collect the UIDs.
11
+ 2. Apply flag operations before disposition:
12
+ - Mark messages as read first: `mail_organize { action: "mark_read", folder, uids }`.
13
+ - Then apply bulk disposition: `archive`, `trash`, `junk`, or `move`.
14
+ 3. For moving to a specific folder: `mail_organize { action: "move", folder, uids, destination }`. If the destination folder doesn't exist, create it first with `mail_organize { action: "create_folder", path }`.
15
+ 4. For label management (Gmail and compatible IMAP):
16
+ - `set_labels` replaces the full label set.
17
+ - `add_labels` appends to existing labels.
18
+ - `remove_labels` removes specific labels.
19
+ Note: label operations are no-ops on servers without `XLIST` or keyword flag support.
20
+ 5. After any folder creation, rename, or deletion: run `mail_sync { action: "refresh_folders" }` to reconcile the local folder cache.
21
+ 6. For large batches (>50 messages), split UIDs into groups of 50 to stay within IMAP command length limits and avoid timeouts.
22
+
23
+ Outcome handling:
24
+ - `archive` / `trash` / `move` returning `success` means the server confirmed the COPY+STORE(\Deleted)+EXPUNGE sequence completed.
25
+ - `mark_read` returning `success` sets the `\Seen` flag only — it does not move or remove the message.
26
+ - Folder creation does not auto-update the local folder list — always follow with `refresh_folders`.
27
+ - `junk` and `archive` use server-detected special-use folders — if those roles are not assigned to any folder, the operation falls back to a move to a folder named "Junk" or "Archive" respectively.
28
+
29
+ Failure handling:
30
+ - Do not `delete_folder` unless you've confirmed the folder is empty or the intent is to cascade-delete its contents.
31
+ - Do not `move` to a non-existent folder — create it first, then move.
32
+ - Do not bulk-apply `trash` to the entire inbox without reading the queue first — irreversible operations need explicit confirmation.
33
+ - Do not apply label operations on servers that don't support them; check folder capabilities or catch the error gracefully.