agentboxd 0.1.0__tar.gz

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.
Files changed (44) hide show
  1. agentboxd-0.1.0/.gitignore +9 -0
  2. agentboxd-0.1.0/CHANGELOG.md +128 -0
  3. agentboxd-0.1.0/LICENSE +21 -0
  4. agentboxd-0.1.0/PKG-INFO +489 -0
  5. agentboxd-0.1.0/README.md +444 -0
  6. agentboxd-0.1.0/examples/quickstart.py +30 -0
  7. agentboxd-0.1.0/pyproject.toml +91 -0
  8. agentboxd-0.1.0/src/agentboxd/__init__.py +376 -0
  9. agentboxd-0.1.0/src/agentboxd/_attachments.py +43 -0
  10. agentboxd-0.1.0/src/agentboxd/_client.py +3251 -0
  11. agentboxd-0.1.0/src/agentboxd/_consume.py +314 -0
  12. agentboxd-0.1.0/src/agentboxd/_errors.py +106 -0
  13. agentboxd-0.1.0/src/agentboxd/_pagination.py +37 -0
  14. agentboxd-0.1.0/src/agentboxd/_requests.py +1364 -0
  15. agentboxd-0.1.0/src/agentboxd/_signup.py +69 -0
  16. agentboxd-0.1.0/src/agentboxd/_stream.py +151 -0
  17. agentboxd-0.1.0/src/agentboxd/_types.py +1864 -0
  18. agentboxd-0.1.0/src/agentboxd/_version.py +1 -0
  19. agentboxd-0.1.0/src/agentboxd/_webhooks.py +68 -0
  20. agentboxd-0.1.0/src/agentboxd/identity.py +1199 -0
  21. agentboxd-0.1.0/src/agentboxd/py.typed +0 -0
  22. agentboxd-0.1.0/tests/__init__.py +0 -0
  23. agentboxd-0.1.0/tests/conftest.py +60 -0
  24. agentboxd-0.1.0/tests/test_agents.py +270 -0
  25. agentboxd-0.1.0/tests/test_asim_phase2.py +316 -0
  26. agentboxd-0.1.0/tests/test_async.py +100 -0
  27. agentboxd-0.1.0/tests/test_client.py +407 -0
  28. agentboxd-0.1.0/tests/test_dashboard_v2.py +161 -0
  29. agentboxd-0.1.0/tests/test_directory.py +220 -0
  30. agentboxd-0.1.0/tests/test_domains_temporary.py +142 -0
  31. agentboxd-0.1.0/tests/test_drafts.py +161 -0
  32. agentboxd-0.1.0/tests/test_extraction.py +113 -0
  33. agentboxd-0.1.0/tests/test_identities.py +121 -0
  34. agentboxd-0.1.0/tests/test_identity.py +108 -0
  35. agentboxd-0.1.0/tests/test_identity_token.py +205 -0
  36. agentboxd-0.1.0/tests/test_leases.py +233 -0
  37. agentboxd-0.1.0/tests/test_phase2b.py +205 -0
  38. agentboxd-0.1.0/tests/test_quick_wins.py +54 -0
  39. agentboxd-0.1.0/tests/test_signup.py +150 -0
  40. agentboxd-0.1.0/tests/test_stream.py +264 -0
  41. agentboxd-0.1.0/tests/test_trust.py +60 -0
  42. agentboxd-0.1.0/tests/test_types.py +45 -0
  43. agentboxd-0.1.0/tests/test_version.py +15 -0
  44. agentboxd-0.1.0/tests/test_webhooks.py +100 -0
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
@@ -0,0 +1,128 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `agentboxd` Python package. This project follows
4
+ [Semantic Versioning](https://semver.org/); while the version is 0.x, minor releases may contain
5
+ breaking changes, which are always listed here.
6
+
7
+ ## 0.1.0 (unreleased)
8
+
9
+ First public release.
10
+
11
+ - `VerificationInfo` / `VerificationResult` carry `auth_failed`: the sender failed authentication (DMARC, or SPF
12
+ without an aligned DKIM pass), so the code may be spoofed. `messages.wait_for_verification` skips such codes unless
13
+ `include_unauthenticated=True`.
14
+ - `Inbox` gains `pending_draft_count`, `needs_human_count` and `recent_bounce_count`; `messages.list` takes `status`.
15
+ `EscalationTrigger` gains `draft_created` (off by default).
16
+ - Contacts v2: `Contact` gains `kind` (`ContactKind`), `kind_source`, `name_source`, `domain` and `last_subject`.
17
+ `contacts.list` takes `kind` (one kind or a list) and `domain`; `contacts.update` takes `kind`;
18
+ `contacts.delete(contact_id, forget=True)` stops mail from the address creating it again; new
19
+ `contacts.delete_many(kind=..., domain=..., forget=..., dry_run=...)` (`ContactBulkDeleteResult`) and
20
+ `contacts.domains(kind=..., limit=...)` (`ContactDomainList`). Async client too.
21
+ - Screening: messages carry `screening` (`MessageScreening`: `state` `screened | pending | held | released`,
22
+ `reason`, `released_at`). When the workspace screens agent mail (the default for new workspaces),
23
+ `messages.claim`, `inboxes.consume` and `messages.wait` return only screened and released mail;
24
+ `include_unscreened` and `include_held` opt in. `messages.list(screening=...)` filters by state. New
25
+ `messages.release(message_id)` (permission `messages:release`) and webhook event `message.released`.
26
+ - In a workspace that screens agent mail, an API key gets held and unscreened messages without their content:
27
+ `message["withheld"]` says so. `messages.get`, `messages.list` and `messages.batch_get` take `include_unscreened` /
28
+ `include_held` (`include_held` needs `messages:release`, which is in no preset). `Inbox` gains `held_count`;
29
+ `EscalationTrigger` gains `held`.
30
+ - `agentboxd.identity.verify_agent_identity_token` (and `averify_agent_identity_token`): verify a "Sign in with
31
+ Agentboxd" ID token in Python, like the TypeScript SDK's `verifyAgentIdentityToken`: ES256 signature against the
32
+ issuer's JWKS (fetched again once for an unknown `kid`), `iss`, `aud`, `exp`/`iat` with 30 s leeway and at most
33
+ 300 s of lifetime, `nonce`, the agent claim, and single use through a `ReplayCache` (`MemoryReplayCache` in one
34
+ process). Returns `VerifiedAgentIdentity`, with the `workspace` and `runboxd` claims when present. Needs the
35
+ `identity` extra (`pip install 'agentboxd[identity]'`, PyJWT with cryptography); no new dependency.
36
+ - `verify_agent_identity_token` and `verify_agent_message` fetch the key set again for an unknown `kid` at most
37
+ once a minute per URL; inside that minute an unknown `kid` fails from the cache. A sender can no longer make
38
+ every check fetch the keys.
39
+ - `domains.zone_file(domain_id)` returns a custom domain's DNS records as a BIND zone file (`DomainZoneFile`:
40
+ `filename`, `content`), for DNS providers that import one.
41
+ - Webhook event types `domain.verified` and `domain.failed` (custom-domain status changes; `failed` pauses
42
+ sending from the domain).
43
+ - Messages carry `auto_reply`: `True` on a received automatic reply (out of office, vacation responder), from its
44
+ headers or the `ai:auto-reply` label. Don't answer those.
45
+ - Messages carry `analysis` (`MessageAnalysis`: `state`, `coverage`, `reason`): whether a received message was
46
+ checked for prompt injection and phishing, and how much of it. `messages.claim` and `inboxes.consume` take
47
+ `analysis="completed"` to get only checked messages.
48
+ - An id of `.` or `..` is refused with `ValueError` before any request: URLs resolve them into another route.
49
+ Other characters in ids, `/` included, are escaped as before.
50
+
51
+ - Internal names now use Agentboxd; `MailroomError` remains importable as a deprecated alias of
52
+ `AgentboxdError` (the same class).
53
+ - `contacts.delete(contact_id)` (`DELETE /v1/contacts/:id`): deletes a contact's name, notes, labels and metadata;
54
+ its messages stay. Needs a workspace-wide key.
55
+ - `webhooks.rotate_secret(webhook_id, secret=None)` (`POST /v1/webhooks/:id/rotate-secret`): replaces a webhook's
56
+ signing secret (yours, or a generated one) and returns it once.
57
+ - Drafts carry `approved_by` (`DraftApprover`: `type`, `id`, `label`), `approved_at` and
58
+ `approved_content_sha256`: who approved the send, when, and the content it covered. Outbound messages sent from a
59
+ draft carry `approval` (`MessageApproval`), which stays after the draft is deleted.
60
+ - **Behaviour change:** editing what a scheduled draft sends (recipients, subject, body, files, type or data) now
61
+ puts it back to `draft`, unapproved. To keep it scheduled, pass `send_at` in the same update (that needs
62
+ `messages:send`, as for any scheduling).
63
+
64
+ - Sync (`Agentboxd`) and async (`AsyncAgentboxd`) clients for the Agentboxd API: inboxes (permanent
65
+ and temporary), messages (send, reply, list, get, update, `wait`, `wait_for_verification`,
66
+ `draft_reply`), threads, search, contacts, knowledge docs, webhooks, custom domains, allow/block
67
+ lists and metrics.
68
+ - Drafts (`client.drafts`): create, list, `list_all`, get, update, delete, send now, schedule
69
+ (`send_at`) and cancel; `messages.draft_reply(..., save=True)` stores the AI reply as a draft.
70
+ - Attachment extraction: attachments carry an `extraction` block; `messages.attachment_text(...)` reads
71
+ the extracted text (paged with `offset` / `max_chars`) and `messages.extract_attachment(...)` returns
72
+ JSON matching `invoice`, `receipt`, `tax_form` or a custom JSON Schema. New webhook event types
73
+ `attachment.extracted` and `attachment.extraction_failed`.
74
+ - `AsyncAgentboxd.stream()`: realtime events over a WebSocket (async iterator with reconnect and
75
+ resume), with the optional `stream` extra (`pip install 'agentboxd[stream]'`); `stream_token()` on
76
+ both clients.
77
+ - `AsyncAgentboxd.stream()` keeps reconnecting when the stream-token request fails with a network error, a 429 or
78
+ a 5xx (during a deploy, for example), waiting at least `Retry-After`. It used to stop. 401 and 403 still raise.
79
+ - Sign in with Agentboxd: `identity.token(inbox_id, audience=..., nonce=, scope=, expires_in=)` mints a
80
+ short-lived, single-use identity token; `identity.clients` (CRUD + `rotate_secret`) and
81
+ `identity.inbox` (`get`, `update`, `sign_ins`) on both clients.
82
+ - Agent self-signup: `Agentboxd.signup(agent_name=, owner_email=)` / `await AsyncAgentboxd.signup(...)`
83
+ (classmethods, no key needed) solve the API's proof of work and return a `Signup` with a ready
84
+ `client`, the one-time `api_key` and the inbox; `solve_signup_challenge()` is exported.
85
+ `client.account.get()` and `client.account.request_claim(email)` on both clients.
86
+ - Identities without a mailbox: `client.identities` (`create`, `list`, `get`, `update`, `delete`,
87
+ `pause`, `resume`) on both clients, `identity.token(identity_id=..., audience=...)`, and
88
+ `signup(kind="identity")` (``Signup.identity``). New `Identity` type; `Inbox.kind`.
89
+ - `inboxes.pause(inbox_id, reason=...)` / `inboxes.resume(inbox_id)` on both clients: the kill switch
90
+ (sends refused with 423 `inbox_paused`, inbound events held until resume).
91
+ - `domains.rotate_dkim(domain_id)` / `domains.activate_dkim(domain_id)`: DKIM key rotation for custom domains.
92
+ - Claim/ack queue on both clients: `messages.claim(inbox_id, ...)`, `messages.ack/nack/extend(message_id,
93
+ lease_id, ...)` and `inboxes.consume(inbox_id, handler, concurrency=..., stop=...)` (threads for the sync
94
+ client, tasks for the async one; extends the lease while the handler runs, acks on success, nacks with
95
+ backoff on an exception). `Metrics["queue"]` per inbox.
96
+ - `deliverability()` on both clients: bounce and complaint rates, suppressed contacts, domain authentication and
97
+ the shared IP's blocklist status.
98
+ - Agent-to-agent messaging: `messages.send` / `reply` and `drafts.create` / `update` take structured `data`
99
+ and a `type` (`message`, `task`, `event`); messages carry `channel`, `type`, `data`, `delivery` and the
100
+ verified-sender `agent` block (`MessageAgent`); `messages.list`, `wait` and `search` filter by `channel`
101
+ and `type`. `agentboxd.identity.verify_agent_message()` (and `averify_agent_message()`) checks a message's
102
+ delivery signature outside Agentboxd, with the `identity` extra (`pip install 'agentboxd[identity]'`).
103
+ - `verify_webhook()` for the HMAC-SHA256 webhook signature; `iter_all` / `aiter_all` pagination helpers;
104
+ `attachment_from_path` / `attachment_from_bytes`.
105
+ - Typed errors: `AgentboxdError` (deprecated alias `MailroomError`) and subclasses per status, with `details` and
106
+ `retry_after` (seconds, on 429); `APIConnectionError` for network failures.
107
+ - Reads `AGENTBOXD_API_KEY` and `AGENTBOXD_BASE_URL` (legacy fallbacks: `MAILROOM_API_KEY`,
108
+ `MAILROOM_URL`). Default base URL: `https://api.agentboxd.com`.
109
+ - Trust layer: `Message["ai_disclosure"]` (untrusted unless `verified`), `client.emergency_stop(reason)`, and
110
+ human on call with `client.escalation.get()` / `update(...)` / `get_inbox(id)` / `update_inbox(id, ...)` (sync and
111
+ async); the `workspace.stopped`, `workspace.resumed` and `escalation.sent` event types.
112
+ - Agent cards and the directory (aSIM): `client.agents` (`get`, `update`, `delete`, `revoke`, `restore`) for an
113
+ inbox's or identity's card and bundle, `card=` on `inboxes.create` / `identities.create`, and `client.directory`
114
+ (`resolve`, `verify`, `search`, `report`), sync and async. `verify_agent_message(..., check_revocation={"api_key":
115
+ ...})` also asks the directory whether the sender is still active (codes `agent_revoked`, `agent_suspended`,
116
+ `agent_deleted`, `revocation_check_failed`). The `agent.updated`, `agent.revoked`, `agent.deleted` and
117
+ `agent.reported` event types; list entries of `type` `token` (`agents:any`, `agents:verified`, `workspace:self`).
118
+ - aSIM phase 2: agent-held keys (`client.agents.keys`: `list`, `register`, `retire`, `revoke`) and, in
119
+ `agentboxd.identity` (`identity` extra), `generate_agent_key()` (Ed25519 or P-256), `create_key_proof()`,
120
+ `sign_agent_message()` and `verify_author_signature()` (`AuthorSignatureVerificationError`); `messages.send` /
121
+ `reply` take `agent_signature` and messages carry `author`. `verify_agent_message()` accepts the
122
+ `domain_verified` assurance and checks that the delivery signature's `agent_sig` names the message's author
123
+ signature. Public directory: `agents.update(..., visibility="public", handle=..., indexable=...)`,
124
+ `agents.oasf(inbox_id)`, `directory.resolve(handle="@acme/billing")`, `directory.search(scope="public")`,
125
+ `directory.get_handle` / `set_handle` / `release_handle`, and `client.public_directory` (`search`, `get`,
126
+ `a2a_card`, `oasf`, `keys`, `handle`), sync and async. Cards carry `handle`, `domain`, the `domain_verified`
127
+ badge, `listing`, `indexable` and `keys.agent`.
128
+ - Python 3.9+, only dependency `httpx`, fully typed (`py.typed`).
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Agentboxd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,489 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentboxd
3
+ Version: 0.1.0
4
+ Summary: Python client for Agentboxd: real email inboxes for AI agents. Send, receive, wait for replies, extract OTP codes and magic links.
5
+ Project-URL: Homepage, https://agentboxd.com
6
+ Project-URL: Documentation, https://agentboxd.com/docs/python-sdk
7
+ Project-URL: Repository, https://github.com/agentboxd/agentboxd
8
+ Project-URL: Issues, https://github.com/agentboxd/agentboxd/issues
9
+ Project-URL: Changelog, https://github.com/agentboxd/agentboxd/blob/main/sdk-python/CHANGELOG.md
10
+ Author-email: Agentboxd <support@agentboxd.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: agent-email,agentboxd,ai-agents,email,email-api,inbox,llm,magic-link,mcp,otp,temporary-email,verification-code,webhooks
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Communications :: Email
26
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
27
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.9
30
+ Requires-Dist: httpx<1,>=0.23
31
+ Provides-Extra: dev
32
+ Requires-Dist: build>=1.0; extra == 'dev'
33
+ Requires-Dist: mypy>=1.8; extra == 'dev'
34
+ Requires-Dist: pyjwt[crypto]>=2.8; extra == 'dev'
35
+ Requires-Dist: pytest>=7; extra == 'dev'
36
+ Requires-Dist: rfc8785>=0.1.4; extra == 'dev'
37
+ Requires-Dist: ruff>=0.4; extra == 'dev'
38
+ Requires-Dist: websockets>=10; extra == 'dev'
39
+ Provides-Extra: identity
40
+ Requires-Dist: pyjwt[crypto]>=2.8; extra == 'identity'
41
+ Requires-Dist: rfc8785>=0.1.4; extra == 'identity'
42
+ Provides-Extra: stream
43
+ Requires-Dist: websockets>=10; extra == 'stream'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # agentboxd
47
+
48
+ Python client for [Agentboxd](https://agentboxd.com): real email inboxes for AI agents.
49
+
50
+ Create an address with one call, send and reply from it, block until the next email arrives, and pull
51
+ the one-time code or magic link out of a sign-up email. Mail is received on Agentboxd's own mail
52
+ server, checked (SPF, DKIM, DMARC), stripped of quoted history and signatures, and handed to your agent
53
+ as JSON.
54
+
55
+ It has a sync client (`Agentboxd`) and an async one (`AsyncAgentboxd`), needs Python 3.9+, and its only
56
+ dependency is `httpx`. It is fully typed and ships `py.typed`.
57
+
58
+ ## Install
59
+
60
+ ```bash
61
+ pip install agentboxd
62
+ ```
63
+
64
+ Not on PyPI yet? Install from the public repository:
65
+
66
+ ```bash
67
+ pip install "agentboxd @ git+https://github.com/agentboxd/agentboxd#subdirectory=sdk-python"
68
+ ```
69
+
70
+ Get an API key from the [dashboard](https://agentboxd.com/app/api-keys) (the Free plan needs no card).
71
+ Keys start with `mr_`.
72
+
73
+ ## Configuration
74
+
75
+ | Env var | Used for | Default |
76
+ |----------------------|----------------------------|-----------------------------|
77
+ | `AGENTBOXD_API_KEY` | `api_key` when not passed | none (required) |
78
+ | `AGENTBOXD_BASE_URL` | `base_url` when not passed | `https://api.agentboxd.com` |
79
+
80
+ The legacy names `MAILROOM_API_KEY` and `MAILROOM_URL` are still read as fallbacks.
81
+
82
+ ```python
83
+ from agentboxd import Agentboxd
84
+
85
+ mr = Agentboxd() # reads the env vars
86
+ mr = Agentboxd(api_key="mr_...", base_url="http://localhost:3000", timeout=30)
87
+ ```
88
+
89
+ Both clients work as context managers (`with Agentboxd() as mr:` / `async with AsyncAgentboxd() as mr:`)
90
+ and expose `close()`. Responses are plain dicts described by `TypedDict`s (`Inbox`, `Message`,
91
+ `Thread`, `Page[T]`, `VerificationResult`, ...).
92
+
93
+ ## Quickstart
94
+
95
+ ```python
96
+ from agentboxd import Agentboxd, attachment_from_path
97
+
98
+ with Agentboxd() as mr:
99
+ inbox = mr.inboxes.create(client_id="support-agent") # idempotent on client_id
100
+ print(inbox["address"])
101
+
102
+ sent = mr.messages.send(
103
+ inbox["id"],
104
+ to="someone@example.com",
105
+ subject="Hello",
106
+ text="Hi there!",
107
+ attachments=[attachment_from_path("report.pdf")],
108
+ idempotency_key="welcome-42", # safe to retry
109
+ )
110
+
111
+ # Block until the reply arrives (long-poll, up to 60 s per call); None on timeout.
112
+ reply = mr.messages.wait(inbox["id"], timeout=60, from_="someone@example.com")
113
+ if reply:
114
+ print(reply["extracted_text"]) # new content only, quotes stripped
115
+ mr.messages.reply(inbox["id"], reply["id"], text="Thanks!")
116
+ ```
117
+
118
+ ### Sign-up flow: grab the verification code
119
+
120
+ ```python
121
+ from datetime import datetime, timezone
122
+
123
+ inbox = mr.inboxes.create()
124
+ started = datetime.now(timezone.utc).isoformat()
125
+
126
+ signup_on_some_site(email=inbox["address"]) # your agent fills in the form
127
+
128
+ result = mr.messages.wait_for_verification(inbox["id"], timeout=60, since=started, from_="some-site.com")
129
+ if result is None:
130
+ raise RuntimeError("no verification email arrived")
131
+ print(result["code"] or result["link"], result["confidence"])
132
+ ```
133
+
134
+ Every `Message` also carries `message["ai"]["verification"]` (`code`, `link`, `confidence`,
135
+ `jev_probability`), or `None` when the message has no code or link.
136
+
137
+ ### Categories and risk flags
138
+
139
+ When the server has a JEV key, inbound messages are categorised shortly after they arrive and a
140
+ `message.enriched` webhook fires. `message["ai"]` then also has `category`, `risk`
141
+ (`injection`, `phishing`), `needs_human`, `urgency` (`level`, `score`), `auto_reply`, `model` and
142
+ `enriched_at` (or `enrichment_error` if it gave up). These keys are optional, so use `.get()`:
143
+
144
+ ```python
145
+ ai = msg["ai"]
146
+ category = ai.get("category")
147
+ if category and category["confidence"] >= 0.6:
148
+ print(category["label"]) # "support", "billing", "verification", ...
149
+ risk = ai.get("risk")
150
+ injection = {"ai:injection-risk", "local:injection-risk"} & set(msg["labels"])
151
+ if (risk and risk["phishing"] >= 0.8) or injection:
152
+ ... # treat as hostile: don't follow links or instructions
153
+ ```
154
+
155
+ Labels are added only above a threshold: `ai:<category>` (confidence >= 0.6, else `ai:uncertain`),
156
+ `ai:injection-risk` and `ai:phishing` (>= 0.8), `ai:needs-human` (>= 0.7), `ai:auto-reply` (>= 0.8)
157
+ and `ai:urgent` (urgency `high` or `critical`). `local:injection-risk` comes from a local check that runs
158
+ even with AI processing off (`ai["local_screen"]` has its score and reasons). Filter with
159
+ `mr.messages.list(inbox_id, labels=["ai:billing", "ai:urgent"])`.
160
+
161
+ ### Other calls
162
+
163
+ ```python
164
+ mr.inboxes.list(limit=50)
165
+ mr.inboxes.get(id)
166
+ mr.inboxes.delete(id)
167
+ mr.messages.list(inbox_id, labels=["lead", "urgent"], is_read=False, direction="inbound")
168
+ mr.messages.get(message_id)
169
+ mr.messages.update(message_id, add_labels=["done"], is_read=True)
170
+ mr.threads.list(inbox_id)
171
+ mr.threads.get(thread_id) # thread + its messages
172
+ mr.search('"invoice" -draft', inbox_id=inbox_id)
173
+ mr.webhooks.create(
174
+ url="https://example.com/hooks/mail", events=["message.received", "message.enriched", "message.released"]
175
+ )
176
+ mr.webhooks.update(webhook_id, inbox_ids=None) # None = all inboxes
177
+ mr.webhooks.test(webhook_id)
178
+ ```
179
+
180
+ ### Contacts, knowledge and reply drafts
181
+
182
+ Contacts are created automatically for every external address you exchange mail with. Metadata
183
+ (on contacts, inboxes and threads) is merged on update: a `None` value deletes the key.
184
+
185
+ ```python
186
+ c = mr.contacts.by_address("dana@example.com") # NotFoundError if unknown; includes recent_threads
187
+ mr.contacts.update(
188
+ c["id"], notes="VIP since 2021", metadata={"tier": "gold", "legacy": None}, add_labels=["vip"]
189
+ )
190
+ mr.contacts.list(q="dana", label="vip", metadata={"tier": "gold"})
191
+ mr.inboxes.update(inbox_id, metadata={"team": "billing"})
192
+ mr.threads.update(thread_id, metadata={"ticket": "T-1042"}, add_labels=["open"])
193
+
194
+ mr.knowledge.create("Refund policy", "Unused items: full refund within 30 days.") # workspace-wide
195
+ mr.knowledge.create("Macros", "...", inbox_id=inbox_id) # one inbox only
196
+ mr.knowledge.search("refund", inbox_id=inbox_id) # that inbox's docs + workspace-wide ones
197
+
198
+ # Needs the workspace's AI processing set to "full". Never sends: review, then reply.
199
+ draft = mr.messages.draft_reply(message_id, instructions="Offer a refund.")
200
+ mr.messages.reply(inbox_id, message_id, text=draft["text"])
201
+ ```
202
+
203
+ ### Drafts: human review and scheduled send
204
+
205
+ ```python
206
+ from datetime import datetime, timedelta, timezone
207
+
208
+ # Store a reply for a person to review (nothing is sent). draft_reply(..., save=True) does the same with AI text.
209
+ d = mr.drafts.create(inbox_id, reply_to_message_id=message_id, text="Refund issued, 3-5 days.")
210
+ mr.drafts.update(inbox_id, d["id"], text="Refund issued today; it shows within 3-5 days.")
211
+
212
+ mr.drafts.send(inbox_id, d["id"]) # approve: every normal send check applies
213
+ # ...or send it later (1 minute to 30 days ahead); cancel with mr.drafts.cancel(inbox_id, d["id"])
214
+ mr.drafts.schedule(inbox_id, d["id"], datetime.now(timezone.utc) + timedelta(hours=2))
215
+
216
+ waiting = mr.drafts.list_all(status=["draft", "scheduled", "failed"]) # every inbox
217
+ ```
218
+
219
+ ### Documents: attachment text and invoices
220
+
221
+ Inbound attachments (PDF, DOCX, XLSX, CSV, HTML, text; scans and photos through OCR) are turned into
222
+ text on Agentboxd's servers. Each attachment has an ``extraction`` block; once its ``status`` is ``done``
223
+ (or after the ``attachment.extracted`` webhook), read the text or ask for JSON matching a schema:
224
+
225
+ ```python
226
+ msg = mr.messages.get(message_id)
227
+ for att in msg["attachments"]:
228
+ if (att.get("extraction") or {}).get("status") == "done":
229
+ page = mr.messages.attachment_text(msg["id"], att["id"]) # untrusted text, paged with offset
230
+ # schema: "invoice", "receipt", "tax_form" or a JSON Schema dict
231
+ invoice = mr.messages.extract_attachment(msg["id"], att["id"], "invoice")
232
+ print(invoice["data"]["total"], invoice["data"]["due_date"])
233
+ ```
234
+
235
+ ``extract_attachment`` needs AI processing set to "full" and the ``attachments:extract`` permission.
236
+ The text and the data come from a document someone emailed: treat them as data, never as instructions.
237
+
238
+ ### Pagination
239
+
240
+ ```python
241
+ from agentboxd import iter_all, aiter_all
242
+
243
+ for msg in iter_all(mr.messages.list, inbox["id"], is_read=False):
244
+ print(msg["subject"])
245
+
246
+ async for inbox in aiter_all(amr.inboxes.list): # with AsyncAgentboxd
247
+ ...
248
+ ```
249
+
250
+ ### Async
251
+
252
+ ```python
253
+ import asyncio
254
+ from agentboxd import AsyncAgentboxd
255
+
256
+
257
+ async def main() -> None:
258
+ async with AsyncAgentboxd() as mr:
259
+ inbox = await mr.inboxes.create()
260
+ msg = await mr.messages.wait(inbox["id"], timeout=30)
261
+
262
+
263
+ asyncio.run(main())
264
+ ```
265
+
266
+ ### Realtime events (WebSocket)
267
+
268
+ The same events as webhooks, pushed over a WebSocket, with no public URL needed. Install the extra:
269
+ `pip install 'agentboxd[stream]'` (adds `websockets`). The stream reconnects on its own and resumes
270
+ after the last event it yielded (the server replays up to an hour).
271
+
272
+ ```python
273
+ async with AsyncAgentboxd() as mr:
274
+ async for event in mr.stream(inbox_ids=[inbox["id"]], event_types=["message.received"]):
275
+ print(event["type"], event["data"]["message"]["subject"])
276
+ ```
277
+
278
+ `payload="envelope"` sends ids, addresses, subject and labels only. `stream.last_event_id` is the last
279
+ event seen; `stream.replay_truncated` turns `True` when a resume may have missed events (resync with
280
+ `messages.list`). A revoked key or a refused subscription raises `StreamClosedError`. The key needs the
281
+ `messages:read` permission. `mr.stream_token()` (sync and async) returns a single-use URL for any other
282
+ WebSocket client.
283
+
284
+ ### Agent-to-agent messaging
285
+
286
+ Mail between two Agentboxd inboxes is delivered natively as an agent message: the recipient sees
287
+ `channel == "agent"` and a verified `agent` block, and you can send a typed task with structured data
288
+ (https://agentboxd.com/docs/agent-messaging).
289
+
290
+ ```python
291
+ mr.messages.send(
292
+ inbox["id"],
293
+ to="supplier@homingbox.net",
294
+ subject="Quote request",
295
+ type="task",
296
+ data={"sku": "SKU-42", "qty": 500},
297
+ )
298
+
299
+ task = mr.messages.wait(inbox["id"], type="task", channel="agent")
300
+ if task and task.get("agent") and task["agent"]["verified"]:
301
+ handle(task["data"]) # verified sender, untrusted content: validate the data
302
+ ```
303
+
304
+ To prove a message's origin outside Agentboxd, verify its signature (`pip install 'agentboxd[identity]'`):
305
+
306
+ ```python
307
+ from agentboxd.identity import MemoryReplayCache, verify_agent_message
308
+
309
+ proof = verify_agent_message(message, recipient="supplier@homingbox.net", replay_cache=MemoryReplayCache())
310
+ ```
311
+
312
+ Sign what your agent writes with its own key (the private key never leaves your process), so anyone can check
313
+ the author without trusting Agentboxd (https://agentboxd.com/docs/agent-directory):
314
+
315
+ ```python
316
+ from agentboxd.identity import create_key_proof, generate_agent_key, sign_agent_message
317
+
318
+ key = generate_agent_key() # Ed25519; generate_agent_key("ES256") for P-256
319
+ mr.agents.keys.register(
320
+ inbox["id"], public_jwk=key["public_jwk"], proof=create_key_proof(key, inbox["address"])
321
+ )
322
+
323
+ data = {"sku": "SKU-42", "qty": 500}
324
+ signature = sign_agent_message(
325
+ key,
326
+ from_=inbox["address"],
327
+ subject="Quote request",
328
+ data=data,
329
+ type="task",
330
+ to=["supplier@homingbox.net"],
331
+ )
332
+ mr.messages.send(
333
+ inbox["id"],
334
+ to="supplier@homingbox.net",
335
+ subject="Quote request",
336
+ data=data,
337
+ type="task",
338
+ agent_signature=signature,
339
+ )
340
+ ```
341
+
342
+ Public agents are listed at https://agentboxd.com/agents: `mr.public_directory.search(q="invoices")`,
343
+ `mr.directory.resolve(handle="@acme/billing")`, and `verify_author_signature(message, keys=...)` with the keys
344
+ from `mr.public_directory.keys(address)`.
345
+
346
+ ### Sign in with Agentboxd (agent identity)
347
+
348
+ The inbox is the agent's identity. An app registered with Agentboxd (its `client_id`) can let the agent
349
+ sign in with one short-lived (at most 5 minutes), single-use OpenID Connect ID token. The key needs the
350
+ `identity:sign` permission.
351
+
352
+ ```python
353
+ tok = mr.identity.token(inbox["id"], audience="abxc_...", nonce=nonce_from_the_app)
354
+ send_to_the_app(tok["id_token"])
355
+ ```
356
+
357
+ The app verifies it against `https://id.agentboxd.com/.well-known/jwks.json` (any OpenID Connect or
358
+ JOSE library: ES256, `iss`, `aud` = its client_id, `exp`, `nonce`, and a single-use `jti`), or exchanges
359
+ it at the issuer's token endpoint. Workspaces manage apps with `mr.identity.clients` (create, list, get,
360
+ update, delete, `rotate_secret`) and each inbox's switch and history with `mr.identity.inbox.get`,
361
+ `update(inbox_id, enabled=False)` and `sign_ins`. See https://agentboxd.com/docs/agent-identity.
362
+
363
+ ## No key yet: let the agent sign itself up
364
+
365
+ An agent can create its own workspace without a human. `signup()` solves a short proof-of-work challenge
366
+ (a few seconds of CPU) and returns the key once, with a ready client:
367
+
368
+ ```python
369
+ from agentboxd import Agentboxd
370
+
371
+ s = Agentboxd.signup(agent_name="research-agent", owner_email="me@example.com")
372
+ print(s.api_key) # store it now (e.g. as AGENTBOXD_API_KEY): it is shown only once
373
+ print(s.inbox["address"])
374
+ mr = s.client # already uses the new key
375
+ ```
376
+
377
+ The workspace is **unclaimed** until the person at `owner_email` clicks the emailed claim link (or you
378
+ call `mr.account.request_claim(email)` later): one inbox, email to at most 20 new recipients a day
379
+ (replies in threads someone started with the agent are not limited), no webhooks or custom domains,
380
+ deleted after 30 days without activity. `mr.account.get()` shows the status. `AsyncAgentboxd.signup()`
381
+ does the same (the hashing runs in a worker thread). Details: https://agentboxd.com/docs/agent-signup
382
+
383
+ ## Errors
384
+
385
+ A non-2xx response raises `AgentboxdError` (also exported under its deprecated old name
386
+ `MailroomError`), which has `status`, `code` and `message` taken from the API's `{"error": {"code", "message"}}` body. Some statuses raise a subclass:
387
+ `BadRequestError` (400), `AuthenticationError` (401), `PermissionDeniedError` (403),
388
+ `NotFoundError` (404), `UnprocessableEntityError` (422, e.g. `recipient_suppressed`),
389
+ `RateLimitError` (429, `rate_limited` / `daily_send_limit_exceeded`) and
390
+ `InternalServerError` (5xx). Network failures and timeouts raise `APIConnectionError`, with
391
+ `status` set to 0. Errors also carry `details` (the API's details object, or None) and, on a 429,
392
+ `retry_after` in seconds (e.g. for the workspace burst limit of sends per 5 minutes).
393
+
394
+ ```python
395
+ from agentboxd import AgentboxdError, RateLimitError
396
+
397
+ try:
398
+ mr.messages.send(inbox_id, to="x@example.com", subject="Hi", text="...")
399
+ except RateLimitError as e:
400
+ print("slow down:", e.code, "retry in", e.retry_after, "s")
401
+ except AgentboxdError as e:
402
+ print(e.status, e.code, e.message)
403
+ ```
404
+
405
+ ## Webhooks
406
+
407
+ Each delivery comes with `X-Mailroom-Timestamp` (unix seconds) and `X-Mailroom-Signature` (header names
408
+ kept from the original API), which is
409
+ `hex(HMAC-SHA256(secret, f"{timestamp}.{raw_body}"))`. Always verify against the **raw** body.
410
+ By default, `verify_webhook` rejects timestamps that are more than 300 s from the current time.
411
+ It returns `False` on bad input and never raises.
412
+
413
+ The webhook URL must be a public HTTPS endpoint (port 443 or 1024–65535, no credentials, not a private or
414
+ internal address); otherwise `webhooks.create`/`update` raise `UnprocessableEntityError` with code
415
+ `invalid_webhook_url`. Redirects are not followed.
416
+
417
+ **Flask**
418
+
419
+ ```python
420
+ from flask import Flask, abort, request
421
+ from agentboxd import verify_webhook
422
+
423
+ app = Flask(__name__)
424
+
425
+
426
+ @app.post("/hooks/mail")
427
+ def mail_hook():
428
+ if not verify_webhook(
429
+ request.headers.get("X-Mailroom-Signature"),
430
+ request.headers.get("X-Mailroom-Timestamp"),
431
+ request.get_data(), # raw bytes
432
+ WEBHOOK_SECRET,
433
+ ):
434
+ abort(401)
435
+ event = request.get_json()
436
+ if event["type"] in ("message.received", "message.enriched", "message.released"):
437
+ message = event["data"]["message"]
438
+ if "withheld" not in message: # not screened yet, or held: a later event brings the content
439
+ handle(message) # once per message id: more than one of these events can carry it
440
+ return "", 204
441
+ ```
442
+
443
+ In a workspace that screens agent mail (the default for new ones), a message's content is withheld from
444
+ events until it is screened or released: `message.received` then has `withheld` on the message, and the
445
+ content comes with `message.enriched` or `message.released`
446
+ ([what an API key gets](https://agentboxd.com/docs/api#screening-reads)).
447
+
448
+ **FastAPI**
449
+
450
+ ```python
451
+ from fastapi import FastAPI, Header, HTTPException, Request
452
+ from agentboxd import WebhookEvent, verify_webhook
453
+
454
+ app = FastAPI()
455
+
456
+
457
+ @app.post("/hooks/mail", status_code=204)
458
+ async def mail_hook(
459
+ request: Request,
460
+ x_mailroom_signature: str = Header(None), # header names kept from the original API
461
+ x_mailroom_timestamp: str = Header(None),
462
+ ) -> None:
463
+ body = await request.body()
464
+ if not verify_webhook(x_mailroom_signature, x_mailroom_timestamp, body, WEBHOOK_SECRET):
465
+ raise HTTPException(401, "bad signature")
466
+ event: WebhookEvent = await request.json()
467
+ ...
468
+ ```
469
+
470
+ ## Development
471
+
472
+ ```bash
473
+ python -m venv .venv && .venv/Scripts/python -m pip install -e ".[dev]" # bin/ on macOS/Linux
474
+ .venv/Scripts/python -m pytest
475
+ .venv/Scripts/python -m mypy
476
+ .venv/Scripts/python -m ruff check . && .venv/Scripts/python -m ruff format --check .
477
+ ```
478
+
479
+ ## Links
480
+
481
+ - Docs: https://agentboxd.com/docs ([Python SDK](https://agentboxd.com/docs/python-sdk),
482
+ [verification codes](https://agentboxd.com/docs/verification-codes), [webhooks](https://agentboxd.com/docs/webhooks))
483
+ - TypeScript client: [`agentboxd` on npm](https://www.npmjs.com/package/agentboxd)
484
+ - MCP server for Claude Desktop, Claude Code and Cursor: [`@agentboxd/mcp`](https://www.npmjs.com/package/@agentboxd/mcp)
485
+ - Support: support@agentboxd.com
486
+
487
+ ## License
488
+
489
+ MIT