trottamail 0.1.1__py3-none-any.whl

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.
trottamail/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ """Trotta Mail: an email inbox for your AI agent, screened before it reads anything. https://trotta.email/docs"""
2
+
3
+ from .client import DEFAULT_BASE_URL, DomainPage, Page, TrottaMail, __version__, verify_webhook
4
+ from .errors import (
5
+ AuthenticationError,
6
+ BadRequestError,
7
+ ConflictError,
8
+ InternalServerError,
9
+ NotFoundError,
10
+ PermissionDeniedError,
11
+ RateLimitError,
12
+ TrottaMailError,
13
+ UnprocessableEntityError,
14
+ )
15
+
16
+ __all__ = [
17
+ "DEFAULT_BASE_URL",
18
+ "AuthenticationError",
19
+ "BadRequestError",
20
+ "ConflictError",
21
+ "DomainPage",
22
+ "InternalServerError",
23
+ "NotFoundError",
24
+ "Page",
25
+ "PermissionDeniedError",
26
+ "RateLimitError",
27
+ "TrottaMail",
28
+ "TrottaMailError",
29
+ "UnprocessableEntityError",
30
+ "__version__",
31
+ "verify_webhook",
32
+ ]
trottamail/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """python -m trottamail: the same command line as `trottamail`."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
trottamail/cli.py ADDED
@@ -0,0 +1,362 @@
1
+ """trottamail: an inbox for your agent from the command line.
2
+
3
+ trottamail signup --name riley get an inbox and a key (saved for the next commands)
4
+ trottamail wait --code wait for the next verification code and print it
5
+ trottamail inbox list recent mail
6
+ trottamail read MESSAGE_ID read a message in the safe view
7
+ trottamail send --to jordan@trotta.email --subject Hi --text "..."
8
+ trottamail reply MESSAGE_ID --text "..."
9
+ trottamail report MESSAGE_ID --as spam move unwanted mail out of the inbox ("safe" brings it back)
10
+ trottamail scan < message.eml screen any message, store nothing
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import email
17
+ import email.policy
18
+ import json
19
+ import os
20
+ import sys
21
+ from collections.abc import Mapping
22
+ from pathlib import Path
23
+ from typing import Any, Optional
24
+
25
+ import httpx
26
+
27
+ from .client import DEFAULT_BASE_URL, TrottaMail, TrottaMailError, __version__
28
+
29
+ CONFIG = Path(os.environ.get("TROTTA_MAIL_CONFIG", Path.home() / ".config" / "trottamail" / "config.json"))
30
+ LEVEL_MARK = {"safe": " ", "caution": "?", "danger": "!"}
31
+
32
+
33
+ def load_config() -> dict[str, Any]:
34
+ try:
35
+ values = json.loads(CONFIG.read_text())
36
+ return values if isinstance(values, dict) else {}
37
+ except (OSError, ValueError):
38
+ return {}
39
+
40
+
41
+ def save_config(values: dict[str, Any]) -> None:
42
+ CONFIG.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
43
+ # The file holds the API key. It is made readable by its owner only from the first byte, never
44
+ # written open and narrowed afterwards.
45
+ descriptor = os.open(CONFIG, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
46
+ with os.fdopen(descriptor, "w") as handle:
47
+ handle.write(json.dumps(values, indent=2))
48
+ try:
49
+ CONFIG.chmod(0o600) # a file that already existed keeps its old mode otherwise
50
+ except OSError:
51
+ pass
52
+
53
+
54
+ def client(args: argparse.Namespace) -> TrottaMail:
55
+ config = load_config()
56
+ return TrottaMail(
57
+ api_key=os.environ.get("TROTTA_MAIL_API_KEY") or config.get("api_key"),
58
+ base_url=args.api_url or os.environ.get("TROTTA_MAIL_API_URL") or config.get("api_url") or DEFAULT_BASE_URL,
59
+ )
60
+
61
+
62
+ def inbox_id(args: argparse.Namespace, mail: TrottaMail) -> str:
63
+ chosen = getattr(args, "inbox", None) or load_config().get("inbox_id")
64
+ if chosen:
65
+ return str(chosen)
66
+ inboxes = mail.inboxes.list()
67
+ if not inboxes:
68
+ raise SystemExit("No inbox yet. Run: trottamail signup")
69
+ return inboxes[0]["id"]
70
+
71
+
72
+ def body(args: argparse.Namespace) -> str:
73
+ """The message body: --text, or what is piped in. Never a silent wait on a terminal."""
74
+ if args.text is not None:
75
+ return str(args.text)
76
+ if sys.stdin is None or sys.stdin.isatty():
77
+ raise SystemExit("Give the body with --text, or pipe it in.")
78
+ return sys.stdin.read()
79
+
80
+
81
+ def masked(key: str) -> str:
82
+ """Enough of a key to recognize it, not enough to use it."""
83
+ return key[:12] + "..." if len(key) > 16 else "..."
84
+
85
+
86
+ def out(args: argparse.Namespace, data: Any, text: str) -> None:
87
+ print(json.dumps(data, indent=2) if args.json else text)
88
+
89
+
90
+ def verdict_line(message: Mapping[str, Any]) -> str:
91
+ verdict = message.get("verdict") or {}
92
+ return f"{verdict.get('action', '?')} ({verdict.get('level', '?')}): {verdict.get('summary', '')}"
93
+
94
+
95
+ def cmd_signup(args: argparse.Namespace) -> None:
96
+ base = args.api_url or os.environ.get("TROTTA_MAIL_API_URL") or load_config().get("api_url") or DEFAULT_BASE_URL
97
+ mail = TrottaMail.signup(name=args.name, display_name=args.display_name, human_email=args.human_email, base_url=base)
98
+ assert mail.inbox is not None
99
+ save_config({"api_key": mail.api_key, "inbox_id": mail.inbox["id"], "address": mail.inbox["address"], "api_url": base})
100
+ # The key is saved, readable by its owner only. The text output shows only its start, so it does not end
101
+ # up in a terminal log or a model's transcript; --json is for programs and carries it whole.
102
+ out(args, {"api_key": mail.api_key, "inbox": mail.inbox, "claim_url": mail.claim_url}, "\n".join([
103
+ f"Address {mail.inbox['address']}",
104
+ f"Inbox id {mail.inbox['id']}",
105
+ f"API key {masked(mail.api_key or '')} (saved, shown once)",
106
+ f"Claim url {mail.claim_url}",
107
+ "",
108
+ f"Saved to {CONFIG}. Give the claim url to the human responsible for this agent.",
109
+ ]))
110
+
111
+
112
+ def cmd_whoami(args: argparse.Namespace) -> None:
113
+ mail = client(args)
114
+ me = mail.me()
115
+ inboxes = mail.inboxes.list()
116
+ lines = [f"Organization {me['organization']['name']} ({me['organization']['plan']}, {'claimed' if me['organization']['verified'] else 'not claimed yet'})"]
117
+ lines += [f"Inbox {i['address']} {i['id']} guard={i['guard_mode']} unread={i['counts']['unread']} held={i['counts']['held']}" for i in inboxes]
118
+ out(args, {"me": me, "inboxes": inboxes}, "\n".join(lines))
119
+
120
+
121
+ def cmd_inbox(args: argparse.Namespace) -> None:
122
+ mail = client(args)
123
+ messages = mail.messages.list(inbox_id(args, mail), folder=args.folder, q=args.query, limit=args.limit)
124
+ lines = []
125
+ for message in messages:
126
+ mark = LEVEL_MARK.get((message.get("verdict") or {}).get("level", "safe"), " ")
127
+ who = message["from"]["address"] if message["direction"] == "inbound" else "to " + ", ".join(t["address"] for t in message["to"])
128
+ subject = "(held by Trotta)" if message.get("withheld") else message["subject"]
129
+ lines.append(f"{mark} {message['id']} {message['created_at'][:16].replace('T', ' ')} {who[:32]:32} {subject[:60]}")
130
+ out(args, messages, "\n".join(lines) if lines else "No mail in this folder.")
131
+
132
+
133
+ def cmd_read(args: argparse.Namespace) -> None:
134
+ mail = client(args)
135
+ message = mail.messages.get(args.message_id)
136
+ if message.get("withheld"):
137
+ text = f"Held by Trotta. A human has to release it.\n{verdict_line(message)}"
138
+ else:
139
+ codes = ", ".join(c["value"] for c in message["extracted"]["codes"])
140
+ text = "\n".join(filter(None, [
141
+ f"From {message['from'].get('name') or ''} <{message['from']['address']}>",
142
+ f"Subject {message['subject']}",
143
+ f"Verdict {verdict_line(message)}",
144
+ f"Codes {codes}" if codes else "",
145
+ "",
146
+ message.get("text") or "",
147
+ ]))
148
+ out(args, message, text)
149
+
150
+
151
+ def cmd_wait(args: argparse.Namespace) -> None:
152
+ mail = client(args)
153
+ message = mail.inboxes.wait(inbox_id(args, mail), timeout=args.timeout, has_code=args.code, sender=args.sender, subject=args.subject)
154
+ if message is None:
155
+ out(args, {"message": None, "timed_out": True}, "Nothing arrived.")
156
+ raise SystemExit(2)
157
+ if args.code and not args.json:
158
+ print(message["extracted"]["codes"][0]["value"])
159
+ return
160
+ out(args, message, f"{message['from']['address']} {message['subject']}\n{verdict_line(message)}\n\n{message.get('text') or ''}")
161
+
162
+
163
+ def cmd_send(args: argparse.Namespace) -> None:
164
+ mail = client(args)
165
+ text = body(args)
166
+ message = mail.messages.send(
167
+ inbox_id(args, mail), to=args.to, subject=args.subject, text=text, cc=args.cc or None, wait_for_reply=args.wait,
168
+ send_at=args.send_at,
169
+ )
170
+ lines = [f"{message['status']} {message['id']}"]
171
+ if message["status"] == "scheduled":
172
+ lines.append(f"Goes at {message['send_at']}. Stop it with the API: messages.cancel_schedule.")
173
+ if message["status"] == "pending_approval":
174
+ lines.append("Waiting for a human to approve: " + message["verdict"]["summary"])
175
+ if args.wait:
176
+ reply = message.get("reply")
177
+ lines.append(f"\nReply from {reply['from']['address']}:\n{reply['text']}" if reply else "\nNo reply yet.")
178
+ out(args, message, "\n".join(lines))
179
+
180
+
181
+ def cmd_draft(args: argparse.Namespace) -> None:
182
+ mail = client(args)
183
+ text = body(args)
184
+ message = mail.drafts.create(
185
+ inbox_id(args, mail), subject=args.subject, text=text, to=args.to or None, cc=args.cc or None,
186
+ in_reply_to=args.in_reply_to,
187
+ )
188
+ out(args, message, f"draft {message['id']}\nA human reads it and sends it.")
189
+
190
+
191
+ def cmd_updates(args: argparse.Namespace) -> None:
192
+ mail = client(args)
193
+ report = mail.updates(since=args.since, inbox_id=args.inbox, limit=args.limit)
194
+ lines = []
195
+ for item in report["data"]:
196
+ mark = LEVEL_MARK.get(item.get("level", "safe"), " ")
197
+ lines.append(f"{mark} {item['needs']:7} {item['message_id']} {item['from']['address'][:30]:30} {item['subject'][:44]}")
198
+ lines.append(f" {item['why']}")
199
+ if report["held_for_human"]:
200
+ lines.append(f"\n{report['held_for_human']} held for a human.")
201
+ out(args, report, "\n".join(lines) if lines else "Nothing new.")
202
+
203
+
204
+ def cmd_sitrep(args: argparse.Namespace) -> None:
205
+ mail = client(args)
206
+ report = mail.sitrep(inbox_id=args.inbox)
207
+ lines = [report["sentence"]]
208
+ for item in report["needs_you"]:
209
+ lines.append(f" {item['kind']:11} {item['id']} {item['why']}")
210
+ today = report["stopped"]["today"]
211
+ lines.append(
212
+ f"Today: {today['refused']} refused, {today['held']} held, {today['flagged']} flagged, "
213
+ f"{today['outbound_blocked']} outgoing blocked."
214
+ )
215
+ out(args, report, "\n".join(lines))
216
+
217
+
218
+ def cmd_reply(args: argparse.Namespace) -> None:
219
+ mail = client(args)
220
+ text = body(args)
221
+ message = mail.messages.reply(args.message_id, text=text, reply_all=args.all, wait_for_reply=args.wait)
222
+ lines = [f"{message['status']} {message['id']}"]
223
+ if message["status"] == "pending_approval":
224
+ lines.append("Waiting for a human to approve: " + message["verdict"]["summary"])
225
+ if args.wait:
226
+ answer = message.get("reply")
227
+ lines.append(f"\nReply from {answer['from']['address']}:\n{answer['text']}" if answer else "\nNo reply yet.")
228
+ out(args, message, "\n".join(lines))
229
+
230
+
231
+ def cmd_report(args: argparse.Namespace) -> None:
232
+ mail = client(args)
233
+ message = mail.guard.report(args.message_id, args.kind, note=args.note, block_sender=args.block_sender)
234
+ out(args, message, f"{message['id']} {', '.join(message['labels'])}")
235
+
236
+
237
+ def cmd_scan(args: argparse.Namespace) -> None:
238
+ raw = sys.stdin.buffer.read()
239
+ parsed = email.message_from_bytes(raw, policy=email.policy.default)
240
+ content: dict[str, Any | None] = {"direction": "outbound" if args.outbound else "inbound"}
241
+ if parsed.get("From") or parsed.get("Subject"):
242
+ text_part = parsed.get_body(preferencelist=("plain",))
243
+ html_part = parsed.get_body(preferencelist=("html",))
244
+ content.update({
245
+ "sender": str(parsed.get("From", "")) or None, "subject": str(parsed.get("Subject", "")) or None,
246
+ "text": text_part.get_content() if text_part else None, "html": html_part.get_content() if html_part else None,
247
+ "attachments": [{"filename": p.get_filename()} for p in parsed.iter_attachments() if p.get_filename()] or None,
248
+ })
249
+ else:
250
+ content["text"] = raw.decode("utf-8", "replace")
251
+ mail = TrottaMail(api_key=os.environ.get("TROTTA_MAIL_API_KEY") or load_config().get("api_key") or "",
252
+ base_url=args.api_url or os.environ.get("TROTTA_MAIL_API_URL") or load_config().get("api_url") or DEFAULT_BASE_URL)
253
+ result = mail.guard.scan(**{key: value for key, value in content.items() if value is not None})
254
+ verdict = result["verdict"]
255
+ took = f", {verdict['latency_ms']:.0f} ms" if isinstance(verdict.get("latency_ms"), (int, float)) else ""
256
+ lines = [f"{verdict['action'].upper()} ({verdict['level']}, risk {verdict['risk']:.2f}{took})", verdict["summary"]]
257
+ lines += [f" [{s['severity']}] {s['title']}" + (f": {s['evidence']}" if s.get("evidence") else "") for s in verdict["signals"]]
258
+ out(args, result, "\n".join(lines))
259
+ if verdict["action"] in ("hold", "reject"):
260
+ raise SystemExit(3)
261
+
262
+
263
+ def main(argv: Optional[list[str]] = None) -> None:
264
+ parser = argparse.ArgumentParser(prog="trottamail", description="An inbox for your agent, screened before it reads anything.")
265
+ parser.add_argument("--api-url", help="API base URL (default: saved config, TROTTA_MAIL_API_URL, then production)")
266
+ parser.add_argument("--json", action="store_true", help="print the raw API response")
267
+ parser.add_argument("--version", action="version", version=f"trottamail {__version__}")
268
+ commands = parser.add_subparsers(dest="command", required=True)
269
+
270
+ signup = commands.add_parser("signup", help="get an inbox and a key in one step")
271
+ signup.add_argument("--name", help="the part before the @")
272
+ signup.add_argument("--display-name")
273
+ signup.add_argument("--human-email", help="the human responsible for this agent")
274
+ signup.set_defaults(run=cmd_signup)
275
+
276
+ commands.add_parser("whoami", help="show the account and its inboxes").set_defaults(run=cmd_whoami)
277
+
278
+ inbox = commands.add_parser("inbox", help="list recent mail")
279
+ inbox.add_argument("--inbox", help="inbox id (default: the saved one)")
280
+ inbox.add_argument("--folder", default="inbox", choices=["inbox", "held", "sent", "drafts", "scheduled", "spam", "trash", "all"])
281
+ inbox.add_argument("-q", "--query")
282
+ inbox.add_argument("-n", "--limit", type=int, default=20)
283
+ inbox.set_defaults(run=cmd_inbox)
284
+
285
+ read = commands.add_parser("read", help="read a message in the safe view")
286
+ read.add_argument("message_id")
287
+ read.set_defaults(run=cmd_read)
288
+
289
+ wait = commands.add_parser("wait", help="wait for the next message")
290
+ wait.add_argument("--inbox")
291
+ wait.add_argument("--code", action="store_true", help="wait for a verification code and print only the code")
292
+ wait.add_argument("--from", dest="sender")
293
+ wait.add_argument("--subject")
294
+ wait.add_argument("--timeout", type=float, default=120)
295
+ wait.set_defaults(run=cmd_wait)
296
+
297
+ send = commands.add_parser("send", help="send a message (body from --text or stdin)")
298
+ send.add_argument("--inbox")
299
+ send.add_argument("--to", action="append", required=True)
300
+ send.add_argument("--cc", action="append")
301
+ send.add_argument("--subject", required=True)
302
+ send.add_argument("--text")
303
+ send.add_argument("--wait", type=float, help="wait this many seconds (max 60) for the reply")
304
+ send.add_argument("--at", dest="send_at", help="send later: an ISO 8601 time with its offset, up to 30 days ahead")
305
+ send.set_defaults(run=cmd_send)
306
+
307
+ draft = commands.add_parser("draft", help="leave a draft for a human to send (body from --text or stdin)")
308
+ draft.add_argument("--inbox")
309
+ draft.add_argument("--to", action="append")
310
+ draft.add_argument("--cc", action="append")
311
+ draft.add_argument("--subject", required=True)
312
+ draft.add_argument("--text")
313
+ draft.add_argument("--in-reply-to", dest="in_reply_to", help="the id of the message this draft answers")
314
+ draft.set_defaults(run=cmd_draft)
315
+
316
+ updates = commands.add_parser("updates", help="what is new, ranked, with a reason for each")
317
+ updates.add_argument("--inbox")
318
+ updates.add_argument("--since", help="an ISO 8601 time; default 24 hours ago")
319
+ updates.add_argument("--limit", type=int, default=20)
320
+ updates.set_defaults(run=cmd_updates)
321
+
322
+ sitrep = commands.add_parser("sitrep", help="what the guard did today and what needs a human")
323
+ sitrep.add_argument("--inbox")
324
+ sitrep.set_defaults(run=cmd_sitrep)
325
+
326
+ reply = commands.add_parser("reply", help="reply to a message (body from --text or stdin)")
327
+ reply.add_argument("message_id")
328
+ reply.add_argument("--text")
329
+ reply.add_argument("--all", action="store_true", help="reply to everyone")
330
+ reply.add_argument("--wait", type=float, help="wait this many seconds (max 60) for the answer")
331
+ reply.set_defaults(run=cmd_reply)
332
+
333
+ report = commands.add_parser("report", help="say where a message belongs: spam, threat, or safe")
334
+ report.add_argument("message_id")
335
+ report.add_argument("--as", dest="kind", required=True, choices=["spam", "threat", "safe"])
336
+ report.add_argument("--note")
337
+ report.add_argument("--block-sender", action="store_true", help="also put the sender on the block list")
338
+ report.set_defaults(run=cmd_report)
339
+
340
+ scan = commands.add_parser("scan", help="screen a message from stdin (.eml or plain text); nothing is stored")
341
+ scan.add_argument("--outbound", action="store_true", help="screen it as mail you are about to send")
342
+ scan.set_defaults(run=cmd_scan)
343
+
344
+ args = parser.parse_args(argv)
345
+ try:
346
+ args.run(args)
347
+ except TrottaMailError as error:
348
+ print(f"{error.message}" + (f"\n{error.fix}" if error.fix else ""), file=sys.stderr)
349
+ raise SystemExit(1) from None
350
+ except ValueError as error: # an API address that is not https, an id that is not one
351
+ print(str(error), file=sys.stderr)
352
+ raise SystemExit(1) from None
353
+ except httpx.TimeoutException:
354
+ print("The API did not answer in time. Try again.", file=sys.stderr)
355
+ raise SystemExit(1) from None
356
+ except httpx.HTTPError as error:
357
+ print(f"Could not reach the API: {error}", file=sys.stderr)
358
+ raise SystemExit(1) from None
359
+
360
+
361
+ if __name__ == "__main__":
362
+ main()