@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.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.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,2107 @@
1
+ """Email helper utilities for Gmail tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import base64
7
+ import binascii
8
+ import codecs
9
+ import contextlib
10
+ import hashlib
11
+ import itertools
12
+ import logging
13
+ import re
14
+ import secrets
15
+ import ssl
16
+ import sys
17
+ from collections import Counter, OrderedDict
18
+ from datetime import datetime, timezone
19
+ from email.header import Header
20
+ from email.message import Message
21
+ from email.parser import BytesParser
22
+ from email.policy import default as default_email_policy
23
+ from email.utils import getaddresses, parseaddr, parsedate_to_datetime
24
+ from html.parser import HTMLParser
25
+ from threading import Lock
26
+ from time import monotonic
27
+ from typing import Any, Callable, Dict, Iterable, List, Literal, Mapping, Optional
28
+ from urllib.parse import quote
29
+
30
+ import httplib2
31
+ from fastmcp.exceptions import ToolError as ToolExecutionError
32
+ from googleapiclient.errors import HttpError
33
+
34
+ from core.file_limits import (
35
+ FileTooLargeError,
36
+ ensure_within_file_size_limit,
37
+ get_max_file_bytes,
38
+ )
39
+ from core.utils import UserInputError
40
+ from gmail.gmail_web_mime import (
41
+ TextDirection,
42
+ assemble_alternative,
43
+ base_text_direction,
44
+ build_forwarded_container_html,
45
+ build_forwarded_plain,
46
+ build_quote_container_html,
47
+ build_quote_plain,
48
+ encode_raw,
49
+ format_address_list,
50
+ format_attribution_html,
51
+ format_attribution_plain,
52
+ format_display_address,
53
+ format_gmail_date,
54
+ gmail_boundary,
55
+ new_message_html,
56
+ plain_body_to_html,
57
+ )
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+ RAW_BODY_TRUNCATE_LIMIT = 20000
62
+ MAX_PAGINATED_MESSAGE_BYTES = 64 * 1024 * 1024
63
+ _PAGE_CACHE_BYTES = 64 * 1024 * 1024
64
+ _PAGE_CACHE_ENTRIES = 128
65
+ _PAGE_CACHE_TTL = 300
66
+ _PAGE_CACHE = OrderedDict()
67
+ _PAGE_CACHE_LOCK = Lock()
68
+ GMAIL_QUOTA_ERROR_MARKERS = (
69
+ "dailyLimitExceeded",
70
+ "quotaExceeded",
71
+ "rateLimitExceeded",
72
+ "userRateLimitExceeded",
73
+ "usageLimits",
74
+ "quota",
75
+ "rate limit",
76
+ )
77
+
78
+ GMAIL_METADATA_HEADERS = [
79
+ "Subject",
80
+ "From",
81
+ "To",
82
+ "Cc",
83
+ "Reply-To",
84
+ "Message-ID",
85
+ "In-Reply-To",
86
+ "References",
87
+ "Date",
88
+ "List-Unsubscribe",
89
+ "Precedence",
90
+ "List-Id",
91
+ ]
92
+
93
+ EMAIL_REACTION_MIME_TYPE = "text/vnd.google.email-reaction+json"
94
+ # Reactions require MIME types, which format=metadata omits. Exclude bodies at
95
+ # the root and first two part levels, then retain complete deeper parts (and
96
+ # their bodies) so recursive inspection can reach every MIME type.
97
+ THREAD_REPLY_CONTEXT_FIELDS = (
98
+ "messages(labelIds,payload(headers,mimeType,parts(mimeType,parts(mimeType,parts))))"
99
+ )
100
+
101
+ # Gmail accepts label colors only from a fixed palette, and rejects anything else
102
+ # with an opaque 400. Both backgroundColor and textColor draw from this same set.
103
+ # https://developers.google.com/gmail/api/reference/rest/v1/users.labels#Label
104
+ # Synchronized with Gmail v1 discovery revision 20260824. When Gmail changes the
105
+ # LabelColor schema, update this set and its exact fingerprint test together.
106
+ GMAIL_LABEL_COLORS = frozenset(
107
+ {
108
+ "#000000",
109
+ "#007286",
110
+ "#04502e",
111
+ "#076239",
112
+ "#083018",
113
+ "#094228",
114
+ "#0b4f30",
115
+ "#0b804b",
116
+ "#0d3472",
117
+ "#0d3b44",
118
+ "#149e60",
119
+ "#16a765",
120
+ "#16a766",
121
+ "#1a764d",
122
+ "#1c4587",
123
+ "#1e53b8",
124
+ "#202124",
125
+ "#285bac",
126
+ "#2a9c68",
127
+ "#2da2bb",
128
+ "#3c78d8",
129
+ "#3d188e",
130
+ "#3dc789",
131
+ "#41236d",
132
+ "#42d692",
133
+ "#434343",
134
+ "#43d692",
135
+ "#44b984",
136
+ "#464646",
137
+ "#4986e7",
138
+ "#4a86e8",
139
+ "#521d28",
140
+ "#54240e",
141
+ "#594c05",
142
+ "#633e04",
143
+ "#653e9b",
144
+ "#662e37",
145
+ "#666666",
146
+ "#684e07",
147
+ "#68dfa9",
148
+ "#6d9eeb",
149
+ "#711a36",
150
+ "#757575",
151
+ "#7858c3",
152
+ "#7a2e0b",
153
+ "#7a4706",
154
+ "#822111",
155
+ "#83334c",
156
+ "#89d3b2",
157
+ "#8a1c0a",
158
+ "#8e63ce",
159
+ "#98d7e4",
160
+ "#994a64",
161
+ "#999999",
162
+ "#a0eac9",
163
+ "#a2dcc1",
164
+ "#a46a21",
165
+ "#a479e2",
166
+ "#a4c2f4",
167
+ "#aa8831",
168
+ "#ac2b16",
169
+ "#b3efd3",
170
+ "#b65775",
171
+ "#b694e8",
172
+ "#b6cff5",
173
+ "#b99aff",
174
+ "#b9e4d0",
175
+ "#c2185b",
176
+ "#c2c2c2",
177
+ "#c6f3de",
178
+ "#c9daf8",
179
+ "#cc3a21",
180
+ "#cca6ac",
181
+ "#cccccc",
182
+ "#cf8933",
183
+ "#d0bcf1",
184
+ "#d5ae49",
185
+ "#d93025",
186
+ "#e07798",
187
+ "#e3d7ff",
188
+ "#e4d7f5",
189
+ "#e66550",
190
+ "#e7e7e7",
191
+ "#eaa041",
192
+ "#ebdbde",
193
+ "#efa093",
194
+ "#efefef",
195
+ "#f2b2a8",
196
+ "#f2c960",
197
+ "#f3f3f3",
198
+ "#f691b2",
199
+ "#f691b3",
200
+ "#f6c5be",
201
+ "#f7a7c0",
202
+ "#fad165",
203
+ "#fb4c2f",
204
+ "#fbc8d9",
205
+ "#fbd3e0",
206
+ "#fbe983",
207
+ "#fcda83",
208
+ "#fcdee8",
209
+ "#fce8b3",
210
+ "#fdedc1",
211
+ "#fef1d1",
212
+ "#ff7537",
213
+ "#ffad46",
214
+ "#ffad47",
215
+ "#ffbc6b",
216
+ "#ffc8af",
217
+ "#ffd6a2",
218
+ "#ffdeb5",
219
+ "#ffe6c7",
220
+ "#ffffff",
221
+ }
222
+ )
223
+
224
+
225
+ def _render_paginated_message_body(
226
+ raw: bytes, body_format: str, formatter: Callable
227
+ ) -> str:
228
+ """Render the outer message body, excluding attachments and attached messages."""
229
+ message = BytesParser(policy=default_email_policy).parsebytes(raw)
230
+ pending = [(message, 0)]
231
+ while pending:
232
+ part, depth = pending.pop()
233
+ if (
234
+ part.get_content_disposition() == "attachment"
235
+ or part.get_content_maintype() == "message"
236
+ ):
237
+ continue
238
+ if depth > 50:
239
+ raise ToolExecutionError("Message MIME nesting is too deep to paginate.")
240
+ if part.get_content_maintype() == "multipart" and not part.is_multipart():
241
+ raise ToolExecutionError(
242
+ "Malformed multipart message cannot be paginated completely."
243
+ )
244
+ if part.is_multipart():
245
+ pending.extend((child, depth + 1) for child in part.iter_parts())
246
+
247
+ def decode(part):
248
+ try:
249
+ return part.get_content()
250
+ except LookupError:
251
+ return (part.get_payload(decode=True) or b"").decode(
252
+ "utf-8", errors="replace"
253
+ )
254
+
255
+ def render(part):
256
+ if (
257
+ part.get_content_disposition() == "attachment"
258
+ or part.get_content_maintype() == "message"
259
+ ):
260
+ return ""
261
+ if part.get_content_type() == "multipart/alternative":
262
+ plain = part.get_body(preferencelist=("plain",))
263
+ html = part.get_body(preferencelist=("html",))
264
+ return formatter(
265
+ decode(plain) if plain is not None else "",
266
+ decode(html) if html is not None else "",
267
+ body_format=body_format,
268
+ truncate_limit=None,
269
+ )
270
+ if part.get_content_type() == "multipart/related":
271
+ children = list(part.iter_parts())
272
+ if not children:
273
+ return ""
274
+ start = part.get_param("start")
275
+ root = next(
276
+ (p for p in children if start and p.get("Content-ID") == start),
277
+ children[0],
278
+ )
279
+ return render(root)
280
+ if part.is_multipart():
281
+ return "\n".join(filter(None, (render(p) for p in part.iter_parts())))
282
+ if part.get_content_type() == "text/plain":
283
+ return decode(part)
284
+ if part.get_content_type() == "text/html":
285
+ return formatter(
286
+ "", decode(part), body_format=body_format, truncate_limit=None
287
+ )
288
+ return ""
289
+
290
+ return render(message)
291
+
292
+
293
+ async def _fetch_paginated_message_body(
294
+ service, message_id, body_format, formatter, limit
295
+ ):
296
+ """Read and render a bounded message for the page cache."""
297
+ response = await asyncio.to_thread(
298
+ service.users().messages().get(userId="me", id=message_id, format="raw").execute
299
+ )
300
+ encoded = response.get("raw")
301
+ if not isinstance(encoded, str) or not encoded:
302
+ raise ToolExecutionError("Gmail returned no raw message body to paginate.")
303
+ if len(encoded) > ((limit + 2) // 3) * 4:
304
+ raise ToolExecutionError("Message exceeds the paginated-read size limit.")
305
+ try:
306
+ raw = await asyncio.to_thread(
307
+ base64.b64decode,
308
+ encoded + "=" * (-len(encoded) % 4),
309
+ altchars=b"-_",
310
+ validate=True,
311
+ )
312
+ except (binascii.Error, ValueError) as exc:
313
+ raise ToolExecutionError("Gmail returned invalid raw message data.") from exc
314
+ ensure_within_file_size_limit(
315
+ len(raw),
316
+ file_id=message_id,
317
+ kind="message page",
318
+ max_bytes=limit,
319
+ )
320
+ try:
321
+ text = await asyncio.to_thread(
322
+ _render_paginated_message_body, raw, body_format, formatter
323
+ )
324
+ except RecursionError as exc:
325
+ raise ToolExecutionError(
326
+ "Message MIME nesting is too deep to paginate."
327
+ ) from exc
328
+ encoded_body = await asyncio.to_thread(text.encode, "utf-8")
329
+ ensure_within_file_size_limit(
330
+ len(encoded_body),
331
+ file_id=message_id,
332
+ kind="message page",
333
+ max_bytes=limit,
334
+ )
335
+ digest = await asyncio.to_thread(hashlib.sha256, encoded_body)
336
+ return text, len(raw), len(encoded_body), digest.hexdigest()
337
+
338
+
339
+ async def read_gmail_message_page(
340
+ service,
341
+ message_id: str,
342
+ declared_size: Optional[int],
343
+ body_format: str,
344
+ page_offset: int,
345
+ page_size: int,
346
+ expected_sha256: Optional[str],
347
+ formatter: Callable,
348
+ *,
349
+ account: str,
350
+ include_links: bool = False,
351
+ ) -> dict:
352
+ """Fetch an authorized body and return a bounded page using a bounded process-local cache."""
353
+ limit = min(
354
+ get_max_file_bytes() or MAX_PAGINATED_MESSAGE_BYTES, MAX_PAGINATED_MESSAGE_BYTES
355
+ )
356
+ ensure_within_file_size_limit(
357
+ declared_size,
358
+ file_id=message_id,
359
+ kind="message page",
360
+ max_bytes=limit,
361
+ )
362
+ key = (account.lower(), message_id, body_format, include_links) if account else None
363
+ with _PAGE_CACHE_LOCK:
364
+ now = monotonic()
365
+ for old_key, (expires, _) in list(_PAGE_CACHE.items()):
366
+ if expires <= now:
367
+ del _PAGE_CACHE[old_key]
368
+ cached = _PAGE_CACHE.get(key)
369
+ body = cached[1] if cached is not None else None
370
+ if body is None:
371
+ body = await _fetch_paginated_message_body(
372
+ service, message_id, body_format, formatter, limit
373
+ )
374
+ cost = sys.getsizeof(body[0]) + 256
375
+ if key is not None and cost <= _PAGE_CACHE_BYTES:
376
+ with _PAGE_CACHE_LOCK:
377
+ _PAGE_CACHE.pop(key, None)
378
+ while _PAGE_CACHE and (
379
+ len(_PAGE_CACHE) >= _PAGE_CACHE_ENTRIES
380
+ or sum(
381
+ sys.getsizeof(entry[1][0]) + 256
382
+ for entry in _PAGE_CACHE.values()
383
+ )
384
+ + cost
385
+ > _PAGE_CACHE_BYTES
386
+ ):
387
+ _PAGE_CACHE.popitem(last=False)
388
+ _PAGE_CACHE[key] = (monotonic() + _PAGE_CACHE_TTL, body)
389
+ text, raw_size, encoded_size, digest = body
390
+ for size in (raw_size, encoded_size):
391
+ ensure_within_file_size_limit(
392
+ size, file_id=message_id, kind="message page", max_bytes=limit
393
+ )
394
+ if expected_sha256 is not None and digest != expected_sha256:
395
+ raise UserInputError(
396
+ "Message representation changed; restart at page_offset=0."
397
+ )
398
+ if page_offset > len(text):
399
+ raise UserInputError("page_offset exceeds total_chars.")
400
+ end = min(page_offset + page_size, len(text))
401
+ return {
402
+ "message_id": message_id,
403
+ "body_format": body_format,
404
+ "body": text[page_offset:end],
405
+ "page_offset": page_offset,
406
+ "next_offset": end if end < len(text) else None,
407
+ "total_chars": len(text),
408
+ "complete": end == len(text),
409
+ "body_sha256": digest,
410
+ "scope": "Decoded outer message body, excluding attachments and attached messages.",
411
+ }
412
+
413
+
414
+ def _validate_label_color(field: str, value: str) -> str:
415
+ """Normalize one label color and check it against Gmail's fixed palette.
416
+
417
+ Gmail answers an unsupported color with a bare 400, so the check happens here
418
+ to tell the caller which value was wrong and what is allowed.
419
+ """
420
+ normalized = value.strip().lower()
421
+ if normalized not in GMAIL_LABEL_COLORS:
422
+ raise ToolExecutionError(
423
+ f"{field} '{value}' is not a Gmail label color. Gmail accepts only its "
424
+ f"own palette of {len(GMAIL_LABEL_COLORS)} colors, listed at "
425
+ "https://developers.google.com/gmail/api/reference/rest/v1/users.labels#Label"
426
+ )
427
+ return normalized
428
+
429
+
430
+ def build_label_color(
431
+ background_color: Optional[str] = None,
432
+ text_color: Optional[str] = None,
433
+ ) -> Optional[Dict[str, str]]:
434
+ """Build the `color` object for a Gmail label, or None when no color is given.
435
+
436
+ Gmail requires both halves whenever `color` is set, so a half-specified color
437
+ is rejected here rather than sent and refused.
438
+ """
439
+ if background_color is None and text_color is None:
440
+ return None
441
+ if background_color is None or text_color is None:
442
+ raise ToolExecutionError(
443
+ "background_color and text_color must be set together. Gmail requires "
444
+ "both when a label color is set."
445
+ )
446
+ return {
447
+ "backgroundColor": _validate_label_color("background_color", background_color),
448
+ "textColor": _validate_label_color("text_color", text_color),
449
+ }
450
+
451
+
452
+ def _normalize_email(address: str) -> str:
453
+ """Lowercase an email address and strip plus-addressing so that
454
+ e.g. 'Alex <alex+foo@scopestack.io>' normalizes to 'alex@scopestack.io'.
455
+
456
+ This is the key primitive for 'is this message from Alex?' checks - plus
457
+ addresses are Alex, not a third party.
458
+ """
459
+ _name, addr = parseaddr(address or "")
460
+ addr = addr.lower().strip()
461
+ if not addr or "@" not in addr:
462
+ return addr
463
+ local, _, domain = addr.partition("@")
464
+ local = local.split("+", 1)[0]
465
+ return f"{local}@{domain}"
466
+
467
+
468
+ def _new_attachment_id() -> str:
469
+ """Return a random attachment id in the shape Gmail web uses (``f_...``)."""
470
+ return f"f_{secrets.token_hex(5)}"
471
+
472
+
473
+ def _generate_gmail_web_url(
474
+ item_id: str, account_index: int = 0, user_google_email: Optional[str] = None
475
+ ) -> str:
476
+ """Return the Gmail web URL for a message or thread ID in any label (#all).
477
+
478
+ Selects the account by ``authuser`` email when known, else by index in the path.
479
+ """
480
+ if user_google_email:
481
+ authuser = quote(user_google_email, safe="@")
482
+ return f"https://mail.google.com/mail/?authuser={authuser}#all/{item_id}"
483
+ return f"https://mail.google.com/mail/u/{account_index}/#all/{item_id}"
484
+
485
+
486
+ def _http_error_status(error: HttpError) -> Optional[int]:
487
+ status = getattr(getattr(error, "resp", None), "status", None)
488
+ try:
489
+ return int(status)
490
+ except (TypeError, ValueError):
491
+ return None
492
+
493
+
494
+ def _is_quota_or_rate_limit_error(error: HttpError) -> bool:
495
+ details = str(error).lower()
496
+ content = getattr(error, "content", None)
497
+ if isinstance(content, bytes):
498
+ details = f"{details} {content.decode('utf-8', errors='ignore').lower()}"
499
+ elif content:
500
+ details = f"{details} {str(content).lower()}"
501
+ return any(marker.lower() in details for marker in GMAIL_QUOTA_ERROR_MARKERS)
502
+
503
+
504
+ def _is_benign_signature_http_error(error: HttpError) -> bool:
505
+ status = _http_error_status(error)
506
+ return status == 401 or (status == 403 and not _is_quota_or_rate_limit_error(error))
507
+
508
+
509
+ def _signature_fetch_tool_error(error: Exception) -> ToolExecutionError:
510
+ return ToolExecutionError(f"Failed to fetch Gmail send-as signatures: {error}")
511
+
512
+
513
+ def _is_retryable_error(error: Any) -> bool:
514
+ """Whether an error is transient and safe to retry.
515
+
516
+ Covers SSL errors, HTTP 429 (rate limit), 5xx, and quota/rate-limit markers
517
+ in the error body. Reads are idempotent so retrying these is safe.
518
+ """
519
+ if isinstance(error, ssl.SSLError):
520
+ return True
521
+ if isinstance(error, HttpError):
522
+ status = _http_error_status(error)
523
+ if status is not None and (status == 429 or status >= 500):
524
+ return True
525
+ return _is_quota_or_rate_limit_error(error)
526
+ return False
527
+
528
+
529
+ async def _fetch_with_retry(
530
+ build_request: Callable[[], Any],
531
+ item_id: str,
532
+ item_label: str,
533
+ log_prefix: str,
534
+ max_retries: int = 3,
535
+ ) -> tuple[str, Optional[dict], Optional[Exception]]:
536
+ """Execute a Gmail read request, retrying transient failures.
537
+
538
+ `build_request` is re-invoked per attempt so each retry gets a fresh
539
+ request object. Backs off exponentially (1s, 2s, 4s) on retryable errors;
540
+ anything else is returned to the caller immediately. Returns
541
+ `(item_id, response, error)` with exactly one of response/error set.
542
+ """
543
+ last_error: Optional[Exception] = None
544
+ for attempt in range(max_retries + 1):
545
+ try:
546
+ response = await asyncio.to_thread(build_request().execute)
547
+ return item_id, response, None
548
+ except Exception as error:
549
+ last_error = error
550
+ if not _is_retryable_error(error) or attempt == max_retries:
551
+ break
552
+ delay = 2**attempt
553
+ logger.warning(
554
+ f"[{log_prefix}] Retryable error for {item_label} {item_id} on "
555
+ f"attempt {attempt + 1}: {error}. Retrying in {delay}s..."
556
+ )
557
+ await asyncio.sleep(delay)
558
+
559
+ logger.error(f"[{log_prefix}] Failed to fetch {item_label} {item_id}: {last_error}")
560
+ return item_id, None, last_error
561
+
562
+
563
+ async def _fetch_body_data(
564
+ service, message_id: Optional[str], attachment_id: str, body: Dict[str, Any]
565
+ ) -> Optional[str]:
566
+ """Store an attachment-backed body part's data on ``body``; return why it failed."""
567
+ try:
568
+ ensure_within_file_size_limit(
569
+ body.get("size"), file_id=attachment_id, kind="message body"
570
+ )
571
+ _, response, error = await _fetch_with_retry(
572
+ lambda: (
573
+ service.users()
574
+ .messages()
575
+ .attachments()
576
+ .get(userId="me", messageId=message_id, id=attachment_id)
577
+ ),
578
+ item_id=attachment_id,
579
+ item_label="message body",
580
+ log_prefix="fetch_attachment_backed_bodies",
581
+ )
582
+ if error is not None:
583
+ return f"Could not fetch message body {attachment_id}: {error}"
584
+ response = response or {}
585
+ ensure_within_file_size_limit(
586
+ response.get("size"), file_id=attachment_id, kind="message body"
587
+ )
588
+ except FileTooLargeError as error:
589
+ logger.warning(f"Skipping message body of {message_id}: {error}")
590
+ return str(error)
591
+ data = response.get("data") or ""
592
+ try:
593
+ decoded = _decode_base64url(data)
594
+ except binascii.Error:
595
+ decoded = b""
596
+ if not decoded:
597
+ return f"Message body {attachment_id} came back empty or undecodable"
598
+ body["data"] = data
599
+ return None
600
+
601
+
602
+ async def fetch_attachment_backed_bodies(
603
+ service, messages: Iterable[Mapping[str, Any]]
604
+ ) -> List[str]:
605
+ """Fill in the text/plain and text/html bodies Gmail stores behind an attachmentId.
606
+
607
+ Returns why each body that is still missing could not be fetched.
608
+ """
609
+ errors: List[str] = []
610
+ for message in messages:
611
+ pending = [message.get("payload") or {}]
612
+ failures: Dict[str, str] = {}
613
+ wanted = {"text/plain", "text/html"}
614
+ while pending and wanted:
615
+ part = pending.pop(0)
616
+ mime_type = part.get("mimeType", "")
617
+ body = part.get("body") or {}
618
+ attachment_id = None if part.get("filename") else body.get("attachmentId")
619
+ if mime_type in wanted and not body.get("data") and attachment_id:
620
+ error = await _fetch_body_data(
621
+ service, message.get("id"), attachment_id, body
622
+ )
623
+ if error:
624
+ failures[mime_type] = error
625
+ if mime_type in wanted and body.get("data"):
626
+ wanted.discard(mime_type)
627
+ failures.pop(mime_type, None)
628
+ if mime_type.startswith("multipart/"):
629
+ pending.extend(part.get("parts") or [])
630
+ errors.extend(failures.values())
631
+ return errors
632
+
633
+
634
+ async def send_message_once(service, send_body: Dict[str, Any]) -> Dict[str, Any]:
635
+ """Send a message without retries, flagging failures that may have delivered it."""
636
+ try:
637
+ return await asyncio.to_thread(
638
+ service.users().messages().send(userId="me", body=send_body).execute,
639
+ num_retries=0,
640
+ )
641
+ except (
642
+ HttpError,
643
+ httplib2.HttpLib2ErrorWithResponse,
644
+ ssl.SSLError,
645
+ TimeoutError,
646
+ ConnectionError,
647
+ ) as error:
648
+ if isinstance(error, HttpError) and (_http_error_status(error) or 0) < 500:
649
+ raise
650
+ raise ToolExecutionError(
651
+ f"Gmail send failed with an ambiguous error ({error}), so the message "
652
+ "may already have been delivered. Check the Sent folder before sending again."
653
+ ) from error
654
+
655
+
656
+ def _retryable_result_ids(
657
+ results: Mapping[str, Mapping[str, Any]], item_ids: Iterable[str]
658
+ ) -> list[str]:
659
+ """IDs whose batch sub-request failed with a transient, retryable error.
660
+
661
+ The batch API reports per-sub-request errors inside an otherwise successful
662
+ response, so these are invisible to any client-side retry and have to be
663
+ re-fetched individually.
664
+ """
665
+ return [
666
+ item_id
667
+ for item_id in item_ids
668
+ if _is_retryable_error(results.get(item_id, {}).get("error"))
669
+ ]
670
+
671
+
672
+ def _parse_date_header(
673
+ date_str: str, internal_date_ms: str | int | None
674
+ ) -> tuple[Optional[str], Optional[datetime]]:
675
+ """Parse Gmail internalDate or a Date header to a UTC-aware datetime.
676
+
677
+ Prefer Gmail's internalDate because it reflects Gmail's message ordering;
678
+ fall back to the Date header when internalDate is unavailable or malformed.
679
+ Always returns UTC-aware datetimes so naive/aware comparisons don't raise
680
+ TypeError.
681
+
682
+ Returns (iso_string, datetime) or (None, None) if both sources fail.
683
+ """
684
+ if internal_date_ms is not None:
685
+ try:
686
+ ms = int(internal_date_ms)
687
+ dt = datetime.fromtimestamp(ms / 1000.0, tz=timezone.utc)
688
+ return dt.isoformat(), dt
689
+ except (TypeError, ValueError) as e:
690
+ logger.debug(
691
+ "Could not convert internalDate %r to timestamp; falling back to "
692
+ "Date header: %s",
693
+ internal_date_ms,
694
+ e,
695
+ )
696
+
697
+ if date_str:
698
+ try:
699
+ dt = parsedate_to_datetime(date_str)
700
+ # Normalize to UTC (parsedate_to_datetime may return naive or offset-aware).
701
+ if dt.tzinfo is None:
702
+ dt = dt.replace(tzinfo=timezone.utc)
703
+ else:
704
+ dt = dt.astimezone(timezone.utc)
705
+ return dt.isoformat(), dt
706
+ except (TypeError, ValueError) as e:
707
+ logger.debug(
708
+ "Could not parse Date header %r: %s",
709
+ date_str,
710
+ e,
711
+ )
712
+
713
+ return None, None
714
+
715
+
716
+ def _parse_message_id_chain(header_value: Optional[str]) -> list[str]:
717
+ """Extract RFC Message-IDs from a reply header value."""
718
+ if not header_value:
719
+ return []
720
+
721
+ message_ids = re.findall(r"<[^>]+>", header_value)
722
+ return message_ids or header_value.split()
723
+
724
+
725
+ def _is_email_reaction(payload: Mapping[str, Any]) -> bool:
726
+ """Return True if a message payload is a Gmail emoji reaction."""
727
+ return payload.get("mimeType") == EMAIL_REACTION_MIME_TYPE or any(
728
+ _is_email_reaction(part) for part in payload.get("parts") or []
729
+ )
730
+
731
+
732
+ def _derive_reply_headers(
733
+ thread_message_ids: list[str],
734
+ in_reply_to: Optional[str],
735
+ references: Optional[str],
736
+ target: Optional[Mapping[str, Any]] = None,
737
+ ) -> tuple[Optional[str], Optional[str]]:
738
+ """Fill reply headers, defaulting to the latest automatically eligible message.
739
+
740
+ Automatic targets are non-draft, non-trash messages with an RFC Message-ID.
741
+ """
742
+ derived_in_reply_to = in_reply_to
743
+ derived_references = references
744
+
745
+ if not thread_message_ids and not target:
746
+ return derived_in_reply_to, derived_references
747
+
748
+ target_message_id = target.get("message_id") if target else None
749
+ if not derived_in_reply_to:
750
+ # References describe ancestry; only In-Reply-To explicitly selects an
751
+ # older reply parent. Without one, rebuild both headers from the latest
752
+ # eligible message in the thread.
753
+ derived_in_reply_to = target_message_id or thread_message_ids[-1]
754
+ derived_references = None
755
+
756
+ if not derived_references:
757
+ if target_message_id and derived_in_reply_to == target_message_id:
758
+ reference_chain = _parse_message_id_chain(target.get("references"))
759
+ if not reference_chain:
760
+ parent_ids = _parse_message_id_chain(target.get("in_reply_to"))
761
+ if len(parent_ids) == 1:
762
+ reference_chain = parent_ids
763
+ if target_message_id not in reference_chain:
764
+ reference_chain.append(target_message_id)
765
+ derived_references = " ".join(reference_chain)
766
+ elif derived_in_reply_to and derived_in_reply_to in thread_message_ids:
767
+ reply_index = thread_message_ids.index(derived_in_reply_to)
768
+ derived_references = " ".join(thread_message_ids[: reply_index + 1])
769
+ elif derived_in_reply_to:
770
+ derived_references = derived_in_reply_to
771
+ else:
772
+ derived_references = " ".join(thread_message_ids)
773
+
774
+ return derived_in_reply_to, derived_references
775
+
776
+
777
+ def _derive_reply_all_recipients(
778
+ target: Mapping[str, Any],
779
+ exclude: set[str],
780
+ to: Optional[str],
781
+ cc: Optional[str],
782
+ ) -> tuple[Optional[str], Optional[str]]:
783
+ """Fill missing reply-all recipients from the message being answered.
784
+
785
+ To = whoever sent it (Reply-To when set, else From). Cc = every other
786
+ participant, minus `exclude` and minus anyone already in To. Caller-supplied
787
+ values win, mirroring _derive_reply_headers.
788
+
789
+ `exclude` applies to To as well as Cc, so replying to a message the account
790
+ sent itself derives no recipient rather than addressing the account; the
791
+ caller passes `to` explicitly for that case.
792
+
793
+ Only the authenticated address and the selected Send As alias can be excluded
794
+ reliably: a caller sending under several aliases still has to post-filter,
795
+ which is why this is opt-in rather than applied to every threaded send.
796
+ """
797
+ excluded = {addr.lower() for addr in exclude if addr}
798
+ sender = target.get("reply_to") or target.get("from") or ""
799
+
800
+ derived_to = to
801
+ if not derived_to:
802
+ derived_to = ", ".join(
803
+ addr
804
+ for _name, addr in getaddresses([sender])
805
+ if addr and addr.lower() not in excluded
806
+ )
807
+
808
+ derived_cc = cc
809
+ if derived_cc is None:
810
+ seen = {addr.lower() for _n, addr in getaddresses([derived_to or ""]) if addr}
811
+ seen |= excluded
812
+ others = []
813
+ # The sender leads the Cc candidates so an explicit `to` that redirects the
814
+ # reply still keeps the person being replied to on it. When To was derived
815
+ # from the sender they are already in `seen`, so this is a no-op there.
816
+ for _name, addr in getaddresses(
817
+ [sender, target.get("to", ""), target.get("cc", "")]
818
+ ):
819
+ if addr and addr.lower() not in seen:
820
+ seen.add(addr.lower())
821
+ others.append(addr)
822
+ derived_cc = ", ".join(others) or None
823
+
824
+ return derived_to or None, derived_cc
825
+
826
+
827
+ def thread_message_status(message: Mapping[str, Any]) -> str:
828
+ """Return a header suffix such as " [DRAFT, NOT SENT]" for draft or trashed mail."""
829
+ labels = set(message.get("labelIds") or ())
830
+ parts = []
831
+ if "DRAFT" in labels:
832
+ parts.append("DRAFT, NOT SENT")
833
+ if "TRASH" in labels:
834
+ parts.append("IN TRASH")
835
+ return f" [{', '.join(parts)}]" if parts else ""
836
+
837
+
838
+ def _analyze_thread_ownership_impl(
839
+ thread_response: dict,
840
+ user_google_email: str,
841
+ ) -> dict[str, Any]:
842
+ """Pure analysis of a Gmail thread API response. Takes the response from
843
+ users().threads().get(format='full') and returns structured ownership
844
+ metadata. Kept separate from the @server.tool wrapper so tests can call
845
+ it with fabricated thread data.
846
+ """
847
+ messages = thread_response.get("messages", []) or []
848
+ thread_id = thread_response.get("id", "")
849
+
850
+ if not messages:
851
+ return {
852
+ "thread_id": thread_id,
853
+ "thread_subject": None,
854
+ "last_sender": None,
855
+ "last_timestamp": None,
856
+ "ball_in_court_of": None,
857
+ "message_count_by_sender": {},
858
+ "participants": [],
859
+ "excluded_drafts": 0,
860
+ "message_count": 0,
861
+ }
862
+
863
+ normalized_user = _normalize_email(user_google_email)
864
+
865
+ # Thread subject: first message's Subject header
866
+ first_headers = {
867
+ h["name"].lower(): h["value"]
868
+ for h in messages[0].get("payload", {}).get("headers", [])
869
+ }
870
+ thread_subject = first_headers.get("subject") or None
871
+
872
+ sender_counter: Counter[str] = Counter()
873
+ participants: set[str] = set()
874
+ non_draft_participants: set[str] = set()
875
+ excluded_drafts = 0
876
+
877
+ last_non_draft = None # (datetime, message_dict, headers_dict)
878
+
879
+ for message in messages:
880
+ label_ids = message.get("labelIds", []) or []
881
+ is_draft = "DRAFT" in label_ids
882
+
883
+ raw_headers = message.get("payload", {}).get("headers", [])
884
+ headers = {h["name"].lower(): h["value"] for h in raw_headers}
885
+
886
+ from_addr = headers.get("from", "")
887
+ _name, from_email = parseaddr(from_addr)
888
+ from_norm = _normalize_email(from_email) if from_email else ""
889
+
890
+ # Collect participants from From/To/Cc using getaddresses (RFC-correct
891
+ # parsing of quoted display names with embedded commas). Read the raw
892
+ # list so repeated fields are combined rather than silently overwritten.
893
+ header_values = [
894
+ h["value"]
895
+ for h in raw_headers
896
+ if h["name"].lower() in {"from", "to", "cc"} and h["value"]
897
+ ]
898
+ message_participants = set()
899
+ for _n, addr in getaddresses([v for v in header_values if v]):
900
+ norm = _normalize_email(addr) if addr else ""
901
+ if norm and "@" in norm:
902
+ participants.add(norm)
903
+ message_participants.add(norm)
904
+
905
+ if is_draft:
906
+ excluded_drafts += 1
907
+ continue
908
+
909
+ non_draft_participants.update(message_participants)
910
+
911
+ if from_norm and "@" in from_norm:
912
+ sender_counter[from_norm] += 1
913
+
914
+ _iso, dt = _parse_date_header(
915
+ headers.get("date", ""), message.get("internalDate")
916
+ )
917
+ if dt is not None:
918
+ if last_non_draft is None or dt >= last_non_draft[0]:
919
+ last_non_draft = (dt, message, headers)
920
+
921
+ if last_non_draft is None:
922
+ # All messages were drafts - no sent state to reason about
923
+ return {
924
+ "thread_id": thread_id,
925
+ "thread_subject": thread_subject,
926
+ "last_sender": None,
927
+ "last_timestamp": None,
928
+ "ball_in_court_of": None,
929
+ "message_count_by_sender": dict(sender_counter),
930
+ "participants": sorted(participants),
931
+ "excluded_drafts": excluded_drafts,
932
+ "message_count": len(messages),
933
+ }
934
+
935
+ last_dt, _last_message, last_headers = last_non_draft
936
+ last_sender_raw = last_headers.get("from", "")
937
+ _n, last_sender_email = parseaddr(last_sender_raw)
938
+ last_sender_norm = _normalize_email(last_sender_email) if last_sender_email else ""
939
+
940
+ # Ball-in-court: "user" = user owes reply, "them" = other party owes reply,
941
+ # None = unresolvable. Use non-draft participants, so outbound-only threads
942
+ # still see the recipient while draft-only recipients are ignored.
943
+ external_participants = (
944
+ non_draft_participants - {normalized_user}
945
+ if normalized_user
946
+ else non_draft_participants
947
+ )
948
+ if not normalized_user or "@" not in normalized_user or "@" not in last_sender_norm:
949
+ ball_in_court_of = None
950
+ elif not external_participants:
951
+ ball_in_court_of = None
952
+ elif last_sender_norm == normalized_user:
953
+ ball_in_court_of = "them"
954
+ else:
955
+ ball_in_court_of = "user"
956
+
957
+ return {
958
+ "thread_id": thread_id,
959
+ "thread_subject": thread_subject,
960
+ "last_sender": last_sender_raw or None,
961
+ "last_timestamp": last_dt.isoformat(),
962
+ "ball_in_court_of": ball_in_court_of,
963
+ "message_count_by_sender": dict(sender_counter),
964
+ "participants": sorted(participants),
965
+ "excluded_drafts": excluded_drafts,
966
+ "message_count": len(messages),
967
+ }
968
+
969
+
970
+ class _HTMLBlockTextExtractor(HTMLParser):
971
+ """Extract text from HTML, preserving block-level line breaks.
972
+
973
+ _HTMLTextExtractor (in gmail_tools.py) is tuned for *reading* arbitrary
974
+ message bodies, where flowing single-line text is preferred -- it inserts
975
+ no separator at all between block elements (</div><div> etc.), and its
976
+ get_text() collapses every whitespace run, including newlines, to a
977
+ single space. That is the wrong shape whenever the output has to keep the
978
+ author's structure: Gmail signatures are laid out line-by-line (name /
979
+ title / phone / ...) using <br> or one <div>/<p> per line, and the
980
+ text/plain alternative of an outgoing HTML message has to preserve
981
+ paragraph breaks because it is what non-HTML clients actually display.
982
+ Run through the general extractor, adjacent lines end up concatenated
983
+ with zero whitespace between them (e.g. "-Erik" immediately followed by
984
+ "Erik Holzhauer" with no break at all), which no amount of whitespace
985
+ collapsing afterward can repair since there was never a separating
986
+ character to begin with. This extractor treats block boundaries as
987
+ real newlines and only collapses horizontal whitespace within a line.
988
+ """
989
+
990
+ # Elements whose boundaries are visible line breaks once the markup is
991
+ # gone. Table cells are deliberately absent: a line per cell would wreck
992
+ # table-based layouts, so handle_starttag separates them with a space.
993
+ _BLOCK_TAGS = frozenset(
994
+ {
995
+ "address",
996
+ "article",
997
+ "aside",
998
+ "blockquote",
999
+ "dd",
1000
+ "div",
1001
+ "dl",
1002
+ "dt",
1003
+ "fieldset",
1004
+ "figcaption",
1005
+ "figure",
1006
+ "footer",
1007
+ "form",
1008
+ "h1",
1009
+ "h2",
1010
+ "h3",
1011
+ "h4",
1012
+ "h5",
1013
+ "h6",
1014
+ "header",
1015
+ "hr",
1016
+ "li",
1017
+ "main",
1018
+ "nav",
1019
+ "ol",
1020
+ "p",
1021
+ "pre",
1022
+ "section",
1023
+ "table",
1024
+ "tbody",
1025
+ "tfoot",
1026
+ "thead",
1027
+ "tr",
1028
+ "ul",
1029
+ }
1030
+ )
1031
+
1032
+ def __init__(self):
1033
+ super().__init__()
1034
+ self._text = []
1035
+ self._skip = False
1036
+
1037
+ def _append_line_break(self, *, force: bool = False) -> None:
1038
+ """Append a structural break, optionally preserving an empty line."""
1039
+ if not self._text:
1040
+ return
1041
+ if force or self._text[-1] != "\n":
1042
+ self._text.append("\n")
1043
+
1044
+ def handle_starttag(self, tag, attrs):
1045
+ if tag in ("script", "style"):
1046
+ self._skip = True
1047
+ return
1048
+ if self._skip:
1049
+ return
1050
+ if tag == "br":
1051
+ # Unlike a block boundary, consecutive <br> tags intentionally
1052
+ # represent empty lines.
1053
+ self._append_line_break(force=True)
1054
+ elif tag in self._BLOCK_TAGS:
1055
+ # A nested block starts a new visual line even when its parent
1056
+ # already contains text (for example, Name<div>Title</div>).
1057
+ self._append_line_break()
1058
+ if ("data-smartmail", "gmail_signature") in attrs:
1059
+ self._append_line_break(force=True)
1060
+ elif tag in ("td", "th"):
1061
+ # Separating at the start tag also covers omitted </td> and </th>.
1062
+ if self._text and not self._text[-1].endswith((" ", "\n")):
1063
+ self._text.append(" ")
1064
+
1065
+ def handle_endtag(self, tag):
1066
+ # Closing a block ends its visual line. _append_line_break avoids a
1067
+ # duplicate when the block already ended with a nested block or <br>.
1068
+ if tag in ("script", "style"):
1069
+ self._skip = False
1070
+ elif tag in self._BLOCK_TAGS and not self._skip:
1071
+ self._append_line_break()
1072
+
1073
+ def handle_data(self, data):
1074
+ if not self._skip:
1075
+ # HTML collapses source whitespace. Convert it here so formatting
1076
+ # newlines in pretty-printed markup cannot become visible breaks;
1077
+ # only the structural delimiters above emit "\n".
1078
+ normalized = re.sub(r"\s+", " ", data)
1079
+ if normalized == " " and (not self._text or self._text[-1] == "\n"):
1080
+ return
1081
+ self._text.append(normalized)
1082
+
1083
+ def get_text(self) -> str:
1084
+ raw = "".join(self._text)
1085
+ # Collapse horizontal whitespace within each line, but keep the
1086
+ # newlines that mark real line/paragraph breaks. Adjacent block
1087
+ # boundaries (e.g. </div><div>) produce back-to-back newlines,
1088
+ # which the re.sub below caps at one blank line.
1089
+ lines = [" ".join(line.split()) for line in raw.splitlines()]
1090
+ text = "\n".join(lines)
1091
+ text = re.sub(r"\n{3,}", "\n\n", text)
1092
+ return text.strip()
1093
+
1094
+
1095
+ def _decode_base64url(data: str) -> bytes:
1096
+ """Decode Gmail base64url data, which may arrive without padding."""
1097
+ return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
1098
+
1099
+
1100
+ def decode_part_body(part: Mapping[str, Any]) -> str:
1101
+ """Decode a Gmail payload part's body.
1102
+
1103
+ Gmail converts inline ``format="full"`` data to UTF-8 but serves
1104
+ attachment-backed bodies in their declared charset.
1105
+ """
1106
+ raw = _decode_base64url(part["body"]["data"])
1107
+ headers = Message()
1108
+ for header in part.get("headers", []):
1109
+ headers[header["name"]] = header["value"]
1110
+ charset = headers.get_content_charset() or "utf-8"
1111
+ attempts = [(charset, "strict"), ("utf-8", "strict"), (charset, "ignore")]
1112
+ with contextlib.suppress(LookupError):
1113
+ name = codecs.lookup(charset).name
1114
+ if name in {"ascii", "cp1252", "iso8859-1"}:
1115
+ # WHATWG reads these labels as windows-1252, and they often mislabel UTF-8.
1116
+ attempts = [("utf-8", "strict"), ("cp1252", "strict"), ("cp1252", "ignore")]
1117
+ elif not part["body"].get("attachmentId") and not name.startswith("iso2022"):
1118
+ # Raw ISO-2022 bytes are also valid UTF-8, so that codec stays first.
1119
+ attempts = [("utf-8", "strict"), (charset, "strict"), (charset, "ignore")]
1120
+ for codec, errors in attempts:
1121
+ try:
1122
+ return raw.decode(codec, errors)
1123
+ except (LookupError, UnicodeError):
1124
+ continue
1125
+ return raw.decode("utf-8", errors="ignore")
1126
+
1127
+
1128
+ def html_to_text_preserving_breaks(html_content: str) -> str:
1129
+ """Convert HTML to plain text, keeping block boundaries as line breaks.
1130
+
1131
+ Falls back to the original markup if parsing fails, so a malformed body is
1132
+ still delivered as *something* rather than an empty part.
1133
+ """
1134
+ try:
1135
+ parser = _HTMLBlockTextExtractor()
1136
+ parser.feed(html_content)
1137
+ # feed() withholds any tail that could still turn out to be an
1138
+ # incomplete construct -- a trailing "&" or an unterminated entity.
1139
+ # close() flushes it; without this a body ending in "Tom &amp" comes
1140
+ # back empty rather than merely losing the entity.
1141
+ parser.close()
1142
+ return parser.get_text()
1143
+ except Exception:
1144
+ return html_content
1145
+
1146
+
1147
+ class _HTMLLinkExtractor(HTMLParser):
1148
+ """Collect http(s) anchor URLs mapped to their visible text, in document order."""
1149
+
1150
+ def __init__(self):
1151
+ super().__init__()
1152
+ self.links: Dict[str, str] = {}
1153
+ self._href: Optional[str] = None
1154
+ self._text: List[str] = []
1155
+
1156
+ def _flush(self) -> None:
1157
+ if self._href is not None and not self.links.get(self._href):
1158
+ self.links[self._href] = " ".join("".join(self._text).split())
1159
+ self._href = None
1160
+ self._text = []
1161
+
1162
+ def handle_starttag(self, tag, attrs):
1163
+ if tag == "br":
1164
+ self.handle_data(" ")
1165
+ if tag != "a":
1166
+ return
1167
+ self._flush()
1168
+ href = re.sub(r"[\t\n\r]", "", dict(attrs).get("href") or "").strip()
1169
+ if href.lower().startswith(("http://", "https://")):
1170
+ self._href = href
1171
+
1172
+ def handle_endtag(self, tag):
1173
+ if tag == "a":
1174
+ self._flush()
1175
+
1176
+ def handle_data(self, data):
1177
+ if self._href is not None:
1178
+ self._text.append(data)
1179
+
1180
+ def parse_marked_section(self, i, report=1):
1181
+ # Older CPython patch releases raise on unknown <![...]> sections.
1182
+ try:
1183
+ return super().parse_marked_section(i, report)
1184
+ except AssertionError:
1185
+ return self.parse_bogus_comment(i)
1186
+
1187
+ def close(self):
1188
+ super().close()
1189
+ self._flush()
1190
+
1191
+
1192
+ _TEXT_URL_RE = re.compile(r"https?://[^\s<>\"]+", re.IGNORECASE)
1193
+
1194
+
1195
+ def format_html_links(
1196
+ html_body: str, known_text: str, limit: Optional[int] = None
1197
+ ) -> str:
1198
+ """Return a LINKS section of http(s) anchors missing from ``known_text``, capped at ``limit``."""
1199
+ if not html_body:
1200
+ return ""
1201
+ parser = _HTMLLinkExtractor()
1202
+ parser.feed(html_body)
1203
+ parser.close()
1204
+ shown = {
1205
+ url
1206
+ for token in _TEXT_URL_RE.findall(known_text)
1207
+ for url in (token, token.rstrip(".,;:!?)]"))
1208
+ }
1209
+ lines = [
1210
+ f"- {text}: {url}" if text and text != url else f"- {url}"
1211
+ for url, text in parser.links.items()
1212
+ if url not in shown
1213
+ ]
1214
+ if limit is not None:
1215
+ kept = sum(
1216
+ size <= limit
1217
+ for size in itertools.accumulate(len(line) + 1 for line in lines)
1218
+ )
1219
+ if kept < len(lines):
1220
+ lines = lines[:kept] + [f"[{len(lines) - kept} more links omitted]"]
1221
+ return "\n\n--- LINKS ---\n" + "\n".join(lines) if lines else ""
1222
+
1223
+
1224
+ _HTML_BLOCK_TAGS = frozenset(
1225
+ {
1226
+ "address",
1227
+ "aside",
1228
+ "fieldset",
1229
+ "figure",
1230
+ "footer",
1231
+ "header",
1232
+ "main",
1233
+ "nav",
1234
+ "p",
1235
+ "div",
1236
+ "br",
1237
+ "hr",
1238
+ "ul",
1239
+ "ol",
1240
+ "li",
1241
+ "dl",
1242
+ "dt",
1243
+ "dd",
1244
+ "table",
1245
+ "thead",
1246
+ "tbody",
1247
+ "tfoot",
1248
+ "tr",
1249
+ "td",
1250
+ "th",
1251
+ "blockquote",
1252
+ "pre",
1253
+ "h1",
1254
+ "h2",
1255
+ "h3",
1256
+ "h4",
1257
+ "h5",
1258
+ "h6",
1259
+ "html",
1260
+ "head",
1261
+ "title",
1262
+ "meta",
1263
+ "link",
1264
+ "body",
1265
+ "center",
1266
+ "section",
1267
+ "article",
1268
+ }
1269
+ )
1270
+ _HTML_VOID_TAGS = frozenset(
1271
+ {"area", "br", "col", "embed", "hr", "img", "input", "link", "meta", "wbr"}
1272
+ )
1273
+ _HTML_TAG_RE = re.compile(
1274
+ r"<\s*(/?)\s*([a-zA-Z][a-zA-Z0-9]*)(?:\"[^\"]*\"|'[^']*'|[^'\">])*>"
1275
+ )
1276
+ # Elements whose contents are not rendered as flowing text; a <br> inside them
1277
+ # would corrupt CSS/JS or show up literally.
1278
+ _HTML_RAW_TEXT_RE = re.compile(r"<\s*(?:pre|style|script|textarea)\b", re.IGNORECASE)
1279
+ _NEWLINE_RUN_RE = re.compile(r"((?:\r?\n)+)")
1280
+ _ESCAPED_LT = r"&(?:lt|#0*60|#x0*3c);"
1281
+ _ESCAPED_GT = r"&(?:gt|#0*62|#x0*3e);"
1282
+ # Non-space attribute start avoids quadratic backtracking against \s+.
1283
+ _ESCAPED_HTML_OPENING_TAG_RE = re.compile(
1284
+ rf"^\s*{_ESCAPED_LT}\s*[A-Za-z][A-Za-z0-9-]*(?:\s+[^<>\s][^<>]*|\s*(?:/\s*)?)(?:>|{_ESCAPED_GT})",
1285
+ re.IGNORECASE,
1286
+ )
1287
+ _RAW_HTML_TAG_RE = re.compile(r"<\s*/?\s*[A-Za-z][A-Za-z0-9-]*(?:\s|/|>)")
1288
+
1289
+
1290
+ def _reject_entity_escaped_html_body(
1291
+ body: Optional[str], body_format: Literal["plain", "html"]
1292
+ ) -> None:
1293
+ """Reject an html body that opens with an escaped tag and contains no real tag."""
1294
+ if not body or body_format != "html":
1295
+ return
1296
+ if not _ESCAPED_HTML_OPENING_TAG_RE.match(body) or _RAW_HTML_TAG_RE.search(body):
1297
+ return
1298
+ raise UserInputError(
1299
+ "body_format='html' but the body's markup is HTML-entity-escaped "
1300
+ "(e.g. '&lt;div&gt;'), so the recipient would see the tags as literal "
1301
+ "text. Resend with real markup such as '<div>'. To show escaped text "
1302
+ "on purpose, wrap the body in a real tag such as '<p>...</p>'."
1303
+ )
1304
+
1305
+
1306
+ def html_newlines_to_br(html_body: str) -> str:
1307
+ """Turn bare newlines inside an HTML body into ``<br>`` tags.
1308
+
1309
+ LLM callers routinely pass ``body_format="html"`` with paragraphs separated
1310
+ by ``\\n`` and no block markup at all. Browsers collapse that whitespace, so
1311
+ the recipient gets one run-on paragraph. Only newlines that separate
1312
+ *content* (text or inline tags such as ``<b>``/``<a>``) become ``<br>``;
1313
+ newlines that merely sit next to a block-level tag (``<p>``, ``<li>``,
1314
+ ``<div>``...), just inside an inline element, before indentation, or at
1315
+ either end of the body are formatting whitespace and are left alone, so a
1316
+ well-formed HTML body -- including an appended Gmail signature -- comes
1317
+ back byte-identical. Bodies containing ``<pre>``, ``<style>``, ``<script>``
1318
+ or ``<textarea>`` are never touched.
1319
+
1320
+ Apply this only to caller-authored HTML, never to a composed body that
1321
+ embeds third-party markup such as a quoted or forwarded message.
1322
+ """
1323
+ if not html_body or "\n" not in html_body:
1324
+ return html_body
1325
+ if _HTML_RAW_TEXT_RE.search(html_body):
1326
+ return html_body
1327
+
1328
+ # Each token is (is_tag, raw, edge_after, edge_before): whether whitespace
1329
+ # right after / right before the tag is formatting rather than content.
1330
+ tokens: List[tuple] = []
1331
+ pos = 0
1332
+ for match in _HTML_TAG_RE.finditer(html_body):
1333
+ if match.start() > pos:
1334
+ tokens.append((False, html_body[pos : match.start()], False, False))
1335
+ closing, name = bool(match.group(1)), match.group(2).lower()
1336
+ block = name in _HTML_BLOCK_TAGS
1337
+ opens_inline = not closing and name not in _HTML_VOID_TAGS
1338
+ tokens.append((True, match.group(0), block or opens_inline, block or closing))
1339
+ pos = match.end()
1340
+ if pos < len(html_body):
1341
+ tokens.append((False, html_body[pos:], False, False))
1342
+
1343
+ out: List[str] = []
1344
+ for index, (is_tag, text, _, _) in enumerate(tokens):
1345
+ if is_tag:
1346
+ out.append(text)
1347
+ continue
1348
+ prev_is_edge = index == 0 or tokens[index - 1][2]
1349
+ next_is_edge = index + 1 == len(tokens) or tokens[index + 1][3]
1350
+ pieces = _NEWLINE_RUN_RE.split(text)
1351
+ content = [i for i, piece in enumerate(pieces) if piece.strip()]
1352
+ first_content = content[0] if content else len(pieces)
1353
+ last_content = content[-1] if content else -1
1354
+ rebuilt: List[str] = []
1355
+ for piece_index, piece in enumerate(pieces):
1356
+ # re.split with one capture group puts newline runs at odd indices.
1357
+ if piece_index % 2 == 0:
1358
+ rebuilt.append(piece)
1359
+ continue
1360
+ indented = bool(pieces[piece_index + 1])
1361
+ if (piece_index < first_content and prev_is_edge) or (
1362
+ piece_index > last_content and (next_is_edge or indented)
1363
+ ):
1364
+ # Whitespace at a block or element edge, or indentation before
1365
+ # the next tag: formatting, not content.
1366
+ rebuilt.append(piece)
1367
+ continue
1368
+ rebuilt.append("<br>" * min(piece.count("\n"), 2) + "\n")
1369
+ out.append("".join(rebuilt))
1370
+ return "".join(out)
1371
+
1372
+
1373
+ # A body that already opens with a ``<div ... dir=...>`` container; group
1374
+ # ``dir`` spans the attribute value (quoted or bare). Attributes before ``dir``
1375
+ # are consumed whole (name plus quoted or bare value), so ``dir=`` text inside
1376
+ # another attribute's quoted value is never mistaken for the attribute itself.
1377
+ _HTML_ATTR_VALUE = r"(?:\"[^\"]*\"|'[^']*'|[^\s\"'=<>`]+)"
1378
+ _LEADING_DIR_DIV_RE = re.compile(
1379
+ r"\s*<div"
1380
+ rf"(?:\s+(?!dir\s*=)[^\s\"'>/=]+(?:\s*=\s*{_HTML_ATTR_VALUE})?)*"
1381
+ rf"\s+dir\s*=\s*(?P<dir>{_HTML_ATTR_VALUE})",
1382
+ re.IGNORECASE,
1383
+ )
1384
+
1385
+
1386
+ def _force_leading_dir(body: str, direction: str) -> str:
1387
+ """Point a body's own leading ``<div dir=...>`` container at ``direction``."""
1388
+ wrapper = _LEADING_DIR_DIV_RE.match(body)
1389
+ if wrapper is None:
1390
+ return body
1391
+ return f'{body[: wrapper.start("dir")]}"{direction}"{body[wrapper.end("dir") :]}'
1392
+
1393
+
1394
+ def _resolve_direction(direction: TextDirection, text: str) -> str:
1395
+ """Resolve ``"auto"`` to the base direction of ``text``."""
1396
+ return base_text_direction(text) if direction == "auto" else direction
1397
+
1398
+
1399
+ def _derive_web_bodies(
1400
+ body: str, body_format: Literal["plain", "html"], direction: TextDirection
1401
+ ) -> tuple[str, str]:
1402
+ """Derive the (text/plain, text/html) parts of a Gmail-web compose.
1403
+
1404
+ Plain text becomes Gmail's typed ``<div>`` structure inside the direction
1405
+ container; HTML is wrapped in that container unless it already starts with
1406
+ one, and its plain part keeps block breaks.
1407
+ """
1408
+ if body_format == "plain":
1409
+ html_part = plain_body_to_html(body)
1410
+ return body, new_message_html(html_part, _resolve_direction(direction, body))
1411
+ plain_part = html_to_text_preserving_breaks(body).strip()
1412
+ if _LEADING_DIR_DIV_RE.match(body) is None:
1413
+ resolved = _resolve_direction(direction, plain_part)
1414
+ return plain_part, new_message_html(body, resolved)
1415
+ # Keep the caller's own container; an explicit direction wins over its dir.
1416
+ if direction == "auto":
1417
+ return plain_part, body
1418
+ return plain_part, _force_leading_dir(body, direction)
1419
+
1420
+
1421
+ def _parse_message_date(value: str) -> Optional[datetime]:
1422
+ """Parse a Date header in the sender's own offset, or return None.
1423
+
1424
+ Gmail shows the sender's wall-clock time, not UTC.
1425
+ """
1426
+ try:
1427
+ return parsedate_to_datetime(value)
1428
+ except (TypeError, ValueError):
1429
+ return None
1430
+
1431
+
1432
+ def _fill_missing_body(plain: str, html_body: str) -> tuple[str, str]:
1433
+ """Derive whichever of a message's plain or HTML body is missing."""
1434
+ if not plain and html_body:
1435
+ plain = html_to_text_preserving_breaks(html_body).strip()
1436
+ if not html_body and plain:
1437
+ html_body = plain_body_to_html(plain)
1438
+ return plain, html_body
1439
+
1440
+
1441
+ def _web_quote_attribution(
1442
+ target: Mapping[str, Any],
1443
+ ) -> Optional[tuple[str, str, datetime]]:
1444
+ """Return the (name, email, date) of Gmail's reply attribution, or None if unparseable."""
1445
+ parent_name, parent_email = parseaddr(target.get("from") or "")
1446
+ parent_dt = _parse_message_date(target.get("date") or "")
1447
+ if "@" not in parent_email or parent_dt is None:
1448
+ return None
1449
+ return parent_name.strip() or parent_email, parent_email, parent_dt
1450
+
1451
+
1452
+ def _resolve_reply_quote(
1453
+ target: Optional[Mapping[str, Any]], web_path: bool
1454
+ ) -> tuple[Optional[Mapping[str, Any]], str]:
1455
+ """Return the parent to quote, or None and a tool-result note saying why not."""
1456
+ if target is None:
1457
+ reason = "the message being replied to could not be loaded from the thread"
1458
+ elif target.get("body_error"):
1459
+ reason = f"its body could not be fetched ({target['body_error']})"
1460
+ elif web_path and _web_quote_attribution(target) is None:
1461
+ reason = "it has no parseable From address or Date header"
1462
+ else:
1463
+ return target, ""
1464
+ return None, f" Note: the original message was not quoted because {reason}."
1465
+
1466
+
1467
+ def _build_web_reply_bodies(
1468
+ new_plain: str, new_html: str, target: Mapping[str, Any]
1469
+ ) -> tuple[str, str]:
1470
+ """Append a Gmail-web ``gmail_quote`` reply trail to both body parts.
1471
+
1472
+ ``target`` is the parent message from the thread reply context. When it
1473
+ lacks a usable sender address or date (see ``_web_quote_attribution``), the
1474
+ bodies are returned unchanged so the reply still sends, just without a quote.
1475
+ """
1476
+ attribution = _web_quote_attribution(target)
1477
+ if attribution is None:
1478
+ return new_plain, new_html
1479
+ parent_name, parent_email, parent_dt = attribution
1480
+ parent_text, parent_html = _fill_missing_body(
1481
+ target.get("text_body") or "", target.get("html_body") or ""
1482
+ )
1483
+
1484
+ attr_plain = format_attribution_plain(parent_name, parent_email, parent_dt)
1485
+ attr_html = format_attribution_html(parent_name, parent_email, parent_dt)
1486
+ reply_plain = f"{new_plain}\n\n{attr_plain}\n\n{build_quote_plain(parent_text)}"
1487
+ reply_html = f"{new_html}<br>{build_quote_container_html(attr_html, parent_html)}"
1488
+ return reply_plain, reply_html
1489
+
1490
+
1491
+ def _build_forward_content(
1492
+ headers: Mapping[str, str],
1493
+ bodies: Mapping[str, str],
1494
+ forward_message: Optional[str],
1495
+ forward_message_format: Literal["plain", "html"],
1496
+ subject_override: Optional[str],
1497
+ direction: TextDirection = "auto",
1498
+ ) -> tuple[str, str, str]:
1499
+ """Build the (subject, text/plain, text/html) of a Gmail-web forward.
1500
+
1501
+ An explicit ``subject_override`` wins over the derived 'Fwd: <subject>'.
1502
+ The optional note leads the body and sets its base direction.
1503
+ """
1504
+ orig_subject = headers.get("Subject", "(no subject)")
1505
+ orig_from = headers.get("From", "(unknown sender)")
1506
+ orig_date = headers.get("Date", "(unknown date)")
1507
+
1508
+ if subject_override:
1509
+ subject = subject_override
1510
+ elif orig_subject.lower().lstrip().startswith(("fwd:", "fw:")):
1511
+ subject = orig_subject
1512
+ else:
1513
+ subject = f"Fwd: {orig_subject}"
1514
+
1515
+ from_name, from_email = parseaddr(orig_from)
1516
+ if "@" not in from_email:
1517
+ # No usable address: show the raw From as text, never as a dead mailto link.
1518
+ from_name, from_email = orig_from, ""
1519
+ orig_dt = _parse_message_date(orig_date)
1520
+ header = {
1521
+ "from_name": from_name.strip(),
1522
+ "from_email": from_email,
1523
+ "date": format_gmail_date(orig_dt) if orig_dt else orig_date,
1524
+ "subject": orig_subject,
1525
+ "to": headers.get("To", ""),
1526
+ }
1527
+ orig_plain, orig_html = _fill_missing_body(
1528
+ bodies.get("text", ""), bodies.get("html", "")
1529
+ )
1530
+ forward_plain = build_forwarded_plain(**header, orig_plain=orig_plain)
1531
+ container = build_forwarded_container_html(**header, orig_html=orig_html)
1532
+
1533
+ if not forward_message:
1534
+ # Nothing user-authored to orient, so "auto" stays ltr.
1535
+ resolved = "ltr" if direction == "auto" else direction
1536
+ return subject, forward_plain, new_message_html(f"<br>{container}", resolved)
1537
+
1538
+ if forward_message_format == "html":
1539
+ note_html = html_newlines_to_br(forward_message)
1540
+ note_plain = html_to_text_preserving_breaks(note_html).strip()
1541
+ if direction != "auto":
1542
+ # As on a regular send, an explicit direction wins over the note's dir.
1543
+ note_html = _force_leading_dir(note_html, direction)
1544
+ else:
1545
+ note_plain, note_html = forward_message, plain_body_to_html(forward_message)
1546
+
1547
+ if note_plain:
1548
+ forward_plain = f"{note_plain}\n\n{forward_plain}"
1549
+ # The note sets the base direction; the original keeps its own dir markup.
1550
+ forward_html = new_message_html(
1551
+ f"{note_html}<br><br>{container}", _resolve_direction(direction, note_plain)
1552
+ )
1553
+ return subject, forward_plain, forward_html
1554
+
1555
+
1556
+ _REPLY_PREFIX_RE = re.compile(r"^\s*(?:\[[^\]]*\]\s*)*re\s*:", re.IGNORECASE)
1557
+
1558
+
1559
+ def _reply_subject(subject: str, in_reply_to: Optional[str]) -> str:
1560
+ """Prefix ``Re:`` onto a reply's subject unless one follows any ``[tag]`` prefixes."""
1561
+ if in_reply_to and not _REPLY_PREFIX_RE.match(subject):
1562
+ return f"Re: {subject}"
1563
+ return subject
1564
+
1565
+
1566
+ def _inherit_reply_subject(thread_id: str, target: Optional[Mapping[str, Any]]) -> str:
1567
+ """Return the replied-to message's subject, raising when it has none."""
1568
+ subject = (target or {}).get("subject") or ""
1569
+ if not subject.strip():
1570
+ raise UserInputError(
1571
+ f"Could not inherit a subject from thread '{thread_id}'. Pass 'subject' explicitly."
1572
+ )
1573
+ return subject
1574
+
1575
+
1576
+ def _checked_header(field: str, value: str) -> str:
1577
+ """Reject CR/LF in a caller-supplied header value (RFC 5322 injection)."""
1578
+ if "\r" in value or "\n" in value:
1579
+ raise ValueError(f"Invalid {field} header value: line breaks not allowed.")
1580
+ return value
1581
+
1582
+
1583
+ MessagePriority = Literal["high", "normal", "low"]
1584
+
1585
+ PRIORITY_DESCRIPTION = (
1586
+ "'high' or 'low' sets the Importance/X-Priority headers that Outlook, Apple Mail "
1587
+ "and Thunderbird flag; Gmail ignores them. 'normal' adds none."
1588
+ )
1589
+
1590
+ _PRIORITY_HEADERS: Dict[str, tuple[tuple[str, str], ...]] = {
1591
+ "high": (
1592
+ ("Importance", "High"),
1593
+ ("X-Priority", "1 (Highest)"),
1594
+ ("Priority", "urgent"),
1595
+ ),
1596
+ "normal": (),
1597
+ "low": (
1598
+ ("Importance", "Low"),
1599
+ ("X-Priority", "5 (Lowest)"),
1600
+ ("Priority", "non-urgent"),
1601
+ ),
1602
+ }
1603
+
1604
+
1605
+ def _priority_headers(priority: str) -> tuple[tuple[str, str], ...]:
1606
+ """Return the headers that mark a message with ``priority``."""
1607
+ if priority not in _PRIORITY_HEADERS:
1608
+ raise ValueError("priority must be one of 'high', 'normal' or 'low'.")
1609
+ return _PRIORITY_HEADERS[priority]
1610
+
1611
+
1612
+ def _prepare_gmail_message_web(
1613
+ subject: str,
1614
+ plain_body: str,
1615
+ html_body: str,
1616
+ to: Optional[str] = None,
1617
+ cc: Optional[str] = None,
1618
+ bcc: Optional[str] = None,
1619
+ in_reply_to: Optional[str] = None,
1620
+ references: Optional[str] = None,
1621
+ from_email: Optional[str] = None,
1622
+ from_name: Optional[str] = None,
1623
+ priority: MessagePriority = "normal",
1624
+ ) -> str:
1625
+ """Assemble a Gmail-web faithful ``multipart/alternative`` raw message.
1626
+
1627
+ ``plain_body`` and ``html_body`` are the finished text/plain and text/html
1628
+ parts. Headers are authored in Gmail's order; To/Cc/Bcc are validated and
1629
+ their non-ASCII display names RFC 2047 encoded. Message-ID is left for
1630
+ Gmail to assign. Returns the base64url raw message.
1631
+ """
1632
+ subject = _reply_subject(_checked_header("Subject", subject), in_reply_to)
1633
+ if not subject.isascii():
1634
+ # Encode after the check: a long encoded subject folds with a legal CRLF.
1635
+ subject = Header(subject, "utf-8", header_name="Subject").encode(
1636
+ maxlinelen=76, linesep="\r\n"
1637
+ )
1638
+
1639
+ headers: List[tuple[str, str]] = [("MIME-Version", "1.0")]
1640
+ if references:
1641
+ # Fold the References chain with CRLF + TAB per RFC 5322 continuation.
1642
+ folded = "\r\n\t".join(_checked_header("References", references).split())
1643
+ headers.append(("References", folded))
1644
+ if in_reply_to:
1645
+ headers.append(("In-Reply-To", _checked_header("In-Reply-To", in_reply_to)))
1646
+ if bcc:
1647
+ headers.append(("Bcc", format_address_list(_checked_header("Bcc", bcc))))
1648
+ headers.append(("Subject", subject))
1649
+ if from_email:
1650
+ headers.append(("From", format_display_address(from_name, from_email)))
1651
+ if to:
1652
+ headers.append(("To", format_address_list(_checked_header("To", to))))
1653
+ if cc:
1654
+ headers.append(("Cc", format_address_list(_checked_header("Cc", cc))))
1655
+
1656
+ headers.extend(_priority_headers(priority))
1657
+
1658
+ message = assemble_alternative(
1659
+ headers=headers,
1660
+ plain_text=plain_body,
1661
+ html_text=html_body,
1662
+ boundary=gmail_boundary(),
1663
+ )
1664
+ return encode_raw(message)
1665
+
1666
+
1667
+ def _build_web_compose_raw(
1668
+ *,
1669
+ subject: str,
1670
+ body: str,
1671
+ body_format: Literal["plain", "html"],
1672
+ to: Optional[str],
1673
+ cc: Optional[str],
1674
+ bcc: Optional[str],
1675
+ from_email: str,
1676
+ from_name: Optional[str],
1677
+ in_reply_to: Optional[str],
1678
+ references: Optional[str],
1679
+ direction: TextDirection,
1680
+ reply_target: Optional[Mapping[str, Any]],
1681
+ priority: MessagePriority,
1682
+ ) -> str:
1683
+ """Build a Gmail-web raw message for the attachment-free send/draft paths.
1684
+
1685
+ Both body parts are derived from ``body``; when ``reply_target`` (the
1686
+ parent from the thread reply context) is given, Gmail's reply trail is
1687
+ appended to them.
1688
+ """
1689
+ plain_part, html_part = _derive_web_bodies(body, body_format, direction)
1690
+ if reply_target:
1691
+ plain_part, html_part = _build_web_reply_bodies(
1692
+ plain_part, html_part, reply_target
1693
+ )
1694
+ return _prepare_gmail_message_web(
1695
+ subject=subject,
1696
+ plain_body=plain_part,
1697
+ html_body=html_part,
1698
+ to=to,
1699
+ cc=cc,
1700
+ bcc=bcc,
1701
+ in_reply_to=in_reply_to,
1702
+ references=references,
1703
+ from_email=from_email,
1704
+ from_name=from_name,
1705
+ priority=priority,
1706
+ )
1707
+
1708
+
1709
+ def _signature_html_to_text(signature_html: str) -> str:
1710
+ """Convert Gmail signature HTML to plain text, preserving line breaks."""
1711
+ return html_to_text_preserving_breaks(signature_html)
1712
+
1713
+
1714
+ _MARGIN_BLOCK_TAGS = frozenset(
1715
+ {
1716
+ "blockquote",
1717
+ "dl",
1718
+ "figure",
1719
+ "h1",
1720
+ "h2",
1721
+ "h3",
1722
+ "h4",
1723
+ "h5",
1724
+ "h6",
1725
+ "ol",
1726
+ "p",
1727
+ "pre",
1728
+ "ul",
1729
+ }
1730
+ )
1731
+ _END_TAG_RE = re.compile(r"</([a-zA-Z][a-zA-Z0-9]*)\s*>\s*")
1732
+ _TRAILING_BREAK_RE = re.compile(r"<[bh]r\b[^<>]*>\s*\Z", re.IGNORECASE)
1733
+ _RESTYLED_MARGIN_RE = re.compile(
1734
+ rf"<style\b[^<>]*>[^<]*margin|<(?:{'|'.join(sorted(_MARGIN_BLOCK_TAGS))})\b[^<>]*margin",
1735
+ re.IGNORECASE,
1736
+ )
1737
+
1738
+
1739
+ def _html_signature_separator(body: str) -> str:
1740
+ """Return markup leaving one blank line between an HTML body and a signature."""
1741
+ body = body.rstrip()
1742
+ while body.endswith("-->") and (start := body.rfind("<!--")) != -1:
1743
+ body = body[:start].rstrip()
1744
+ if not body:
1745
+ return ""
1746
+ if _TRAILING_BREAK_RE.search(body):
1747
+ return "<br>"
1748
+ closed_tags = set()
1749
+ end = len(body)
1750
+ while match := _END_TAG_RE.fullmatch(body, body.rfind("</", 0, end), end):
1751
+ closed_tags.add(match[1].lower())
1752
+ end = match.start()
1753
+ if closed_tags & _MARGIN_BLOCK_TAGS and not _RESTYLED_MARGIN_RE.search(body):
1754
+ return ""
1755
+ if closed_tags & _HTMLBlockTextExtractor._BLOCK_TAGS:
1756
+ return "<br>"
1757
+ return "<br><br>"
1758
+
1759
+
1760
+ def _wrap_signature_html(signature_html: str) -> str:
1761
+ """Wrap signature HTML in the marker Gmail clients use to detect a signed draft."""
1762
+ return (
1763
+ '<div data-smartmail="gmail_signature">'
1764
+ f'<div dir="ltr">{signature_html}</div></div>'
1765
+ )
1766
+
1767
+
1768
+ async def _get_send_as_entries(service) -> List[Dict[str, Any]]:
1769
+ """Fetch the account's Gmail send-as settings."""
1770
+ try:
1771
+ response = await asyncio.to_thread(
1772
+ service.users().settings().sendAs().list(userId="me").execute
1773
+ )
1774
+ except HttpError as e:
1775
+ if _is_benign_signature_http_error(e):
1776
+ logger.info(
1777
+ "Skipping Gmail send-as lookup: missing auth/scope for settings endpoint."
1778
+ )
1779
+ return []
1780
+ logger.error(f"Failed to fetch Gmail send-as settings: {e}", exc_info=True)
1781
+ raise _signature_fetch_tool_error(e) from e
1782
+ except Exception as e:
1783
+ logger.error(f"Failed to fetch Gmail send-as settings: {e}", exc_info=True)
1784
+ raise _signature_fetch_tool_error(e) from e
1785
+
1786
+ return response.get("sendAs", [])
1787
+
1788
+
1789
+ def _find_send_as_entry(
1790
+ send_as_entries: List[Dict[str, Any]], from_email: str
1791
+ ) -> Optional[Dict[str, Any]]:
1792
+ """Find a send-as entry by email address, case-insensitively."""
1793
+ from_email_normalized = from_email.strip().lower()
1794
+ return next(
1795
+ (
1796
+ entry
1797
+ for entry in send_as_entries
1798
+ if entry.get("sendAsEmail", "").strip().lower() == from_email_normalized
1799
+ ),
1800
+ None,
1801
+ )
1802
+
1803
+
1804
+ def _send_as_entry_is_usable(entry: Dict[str, Any]) -> bool:
1805
+ """True unless Gmail reports this send-as entry as pending verification."""
1806
+ return entry.get("verificationStatus") != "pending"
1807
+
1808
+
1809
+ async def _get_send_as_identity_and_signature(
1810
+ service,
1811
+ from_email: Optional[str],
1812
+ fallback_email: str,
1813
+ require_match: bool = True,
1814
+ ) -> tuple[str, str, str]:
1815
+ """Resolve (sender_email, display_name, signature_html) for a send-as identity.
1816
+
1817
+ ``display_name`` is the name Gmail web renders in the From line, or "" when
1818
+ unset. With require_match, raises when from_email is not a usable send-as
1819
+ address, since Gmail would silently send from the default address instead;
1820
+ without it, an unlisted from_email takes the primary entry's signature.
1821
+ Validation is skipped when the send-as list is unreadable.
1822
+ """
1823
+ send_as_entries = await _get_send_as_entries(service)
1824
+ selected_entry = None
1825
+
1826
+ if from_email:
1827
+ if not send_as_entries:
1828
+ return from_email, "", ""
1829
+ selected_entry = _find_send_as_entry(send_as_entries, from_email)
1830
+ if not require_match:
1831
+ selected_entry = selected_entry or next(
1832
+ (entry for entry in send_as_entries if entry.get("isPrimary")),
1833
+ send_as_entries[0],
1834
+ )
1835
+ elif selected_entry is None or not _send_as_entry_is_usable(selected_entry):
1836
+ accepted = [
1837
+ entry.get("sendAsEmail", "")
1838
+ for entry in send_as_entries
1839
+ if _send_as_entry_is_usable(entry)
1840
+ ]
1841
+ raise ToolExecutionError(
1842
+ f"'{from_email}' is not an accepted 'Send mail as' address for this "
1843
+ f"mailbox, and Gmail would silently send from the default address "
1844
+ f"instead. Accepted: {', '.join(accepted) or '(none)'}. Add the "
1845
+ f"address under Gmail Settings > Accounts > Send mail as, or omit "
1846
+ f"from_email to use the default sender."
1847
+ )
1848
+ else:
1849
+ selected_entry = next(
1850
+ (entry for entry in send_as_entries if entry.get("isDefault")), None
1851
+ )
1852
+ if selected_entry is None:
1853
+ selected_entry = next(
1854
+ (entry for entry in send_as_entries if entry.get("isPrimary")), None
1855
+ )
1856
+ if selected_entry is None and send_as_entries:
1857
+ selected_entry = send_as_entries[0]
1858
+
1859
+ sender_email = from_email or fallback_email
1860
+ display_name = ""
1861
+ signature_html = ""
1862
+ if selected_entry:
1863
+ if not from_email:
1864
+ sender_email = selected_entry.get("sendAsEmail") or fallback_email
1865
+ display_name = (selected_entry.get("displayName") or "").strip()
1866
+ signature_html = selected_entry.get("signature", "") or ""
1867
+
1868
+ return sender_email, display_name, signature_html
1869
+
1870
+
1871
+ async def modify_gmail_thread_labels(
1872
+ service,
1873
+ thread_ids: Iterable[str],
1874
+ add_label_ids: Optional[List[str]] = None,
1875
+ remove_label_ids: Optional[List[str]] = None,
1876
+ ) -> Dict[str, str]:
1877
+ """Apply label changes to whole threads, retrying transient errors per thread.
1878
+
1879
+ Returns ``{thread_id: "applied" | "not_found" | "failed: <reason>"}``.
1880
+ """
1881
+ body: Dict[str, Any] = {}
1882
+ if add_label_ids:
1883
+ body["addLabelIds"] = list(add_label_ids)
1884
+ if remove_label_ids:
1885
+ body["removeLabelIds"] = list(remove_label_ids)
1886
+ outcomes: Dict[str, str] = {}
1887
+ for thread_id in thread_ids:
1888
+ _, _, error = await _fetch_with_retry(
1889
+ lambda tid=thread_id: (
1890
+ service.users().threads().modify(userId="me", id=tid, body=body)
1891
+ ),
1892
+ thread_id,
1893
+ "thread",
1894
+ "modify_gmail_thread_labels",
1895
+ )
1896
+ if error is None:
1897
+ outcomes[thread_id] = "applied"
1898
+ elif isinstance(error, HttpError) and _http_error_status(error) == 404:
1899
+ outcomes[thread_id] = "not_found"
1900
+ elif isinstance(error, HttpError):
1901
+ outcomes[thread_id] = (
1902
+ f"failed: HTTP {_http_error_status(error)} {error.reason}"
1903
+ )
1904
+ else:
1905
+ outcomes[thread_id] = f"failed: {type(error).__name__}"
1906
+ return outcomes
1907
+
1908
+
1909
+ def _format_id_list(ids: List[str], limit: int = 10) -> str:
1910
+ """Join IDs for a result message, truncating very long lists."""
1911
+ shown = ", ".join(ids[:limit])
1912
+ if len(ids) > limit:
1913
+ shown += f", … (+{len(ids) - limit} more)"
1914
+ return shown
1915
+
1916
+
1917
+ def format_thread_label_outcomes(
1918
+ thread_ids: List[str], outcomes: Dict[str, str], action_summary: str
1919
+ ) -> str:
1920
+ """Summarise per-thread results of a thread-level label change."""
1921
+ applied = [t for t in thread_ids if outcomes.get(t) == "applied"]
1922
+ missing = [t for t in thread_ids if outcomes.get(t) == "not_found"]
1923
+ failed = [
1924
+ f"{t} ({outcomes[t]})"
1925
+ for t in thread_ids
1926
+ if outcomes.get(t, "").startswith("failed")
1927
+ ]
1928
+ lines = [
1929
+ f"Label changes for {len(thread_ids)} thread ID(s): {action_summary}",
1930
+ f"Applied: {len(applied)}/{len(thread_ids)}",
1931
+ ]
1932
+ if missing:
1933
+ lines.append(
1934
+ f"No such thread ({len(missing)}): {_format_id_list(missing)}\n"
1935
+ " One possible cause is passing a MESSAGE id where a THREAD id is required."
1936
+ )
1937
+ if failed:
1938
+ lines.append(f"Failed ({len(failed)}): {_format_id_list(failed)}")
1939
+ return "\n".join(lines)
1940
+
1941
+
1942
+ # users.messages.batchModify accepts at most 1000 IDs per call.
1943
+ GMAIL_BATCH_MODIFY_LIMIT = 1000
1944
+ FILTER_APPLY_DEFAULT_MAX_MESSAGES = 5000
1945
+
1946
+
1947
+ def _quote_search_term(value: Any) -> str:
1948
+ """Group a multi-word value so Gmail search treats it as one operand."""
1949
+ text = str(value).strip()
1950
+ if " " in text:
1951
+ return f"({text})"
1952
+ return text
1953
+
1954
+
1955
+ def filter_criteria_to_query(criteria: Mapping[str, Any]) -> str:
1956
+ """Translate Gmail filter criteria into the equivalent search query.
1957
+
1958
+ Covers from, to, subject, query, negatedQuery, hasAttachment and size.
1959
+ ``excludeChats`` has no search operator and is ignored (callers report it).
1960
+ Raises ValueError for ``size`` without an explicit ``sizeComparison``.
1961
+ """
1962
+ parts: List[str] = []
1963
+ if criteria.get("from"):
1964
+ parts.append(f"from:{_quote_search_term(criteria['from'])}")
1965
+ if criteria.get("to"):
1966
+ parts.append(f"to:{_quote_search_term(criteria['to'])}")
1967
+ if criteria.get("subject"):
1968
+ parts.append(f"subject:{_quote_search_term(criteria['subject'])}")
1969
+ if criteria.get("query"):
1970
+ parts.append(f"({criteria['query']})")
1971
+ if criteria.get("negatedQuery"):
1972
+ parts.append(f"-({criteria['negatedQuery']})")
1973
+ if criteria.get("hasAttachment"):
1974
+ parts.append("has:attachment")
1975
+ if criteria.get("size"):
1976
+ op = criteria.get("sizeComparison")
1977
+ if op not in ("larger", "smaller"):
1978
+ raise ValueError(
1979
+ "size criteria need sizeComparison 'larger' or 'smaller' to be "
1980
+ f"translated into a search query (got {op!r})"
1981
+ )
1982
+ parts.append(f"{op}:{int(criteria['size'])}")
1983
+ return " ".join(parts)
1984
+
1985
+
1986
+ async def update_gmail_filter(
1987
+ service,
1988
+ filter_id: str,
1989
+ criteria: Optional[Mapping[str, Any]] = None,
1990
+ filter_action: Optional[Mapping[str, Any]] = None,
1991
+ ) -> Dict[str, Any]:
1992
+ """Replace a filter, keeping the parts the caller did not pass.
1993
+
1994
+ Gmail has no filter update endpoint, so the new filter is created FIRST and
1995
+ the old one deleted afterwards: a failure never leaves the mailbox without
1996
+ the rule. Returns the new filter; the filter ID changes.
1997
+ """
1998
+ filters = service.users().settings().filters()
1999
+ old = await asyncio.to_thread(filters.get(userId="me", id=filter_id).execute)
2000
+ body = {
2001
+ "criteria": dict(criteria) if criteria else old.get("criteria", {}),
2002
+ "action": dict(filter_action) if filter_action else old.get("action", {}),
2003
+ }
2004
+ created = await asyncio.to_thread(filters.create(userId="me", body=body).execute)
2005
+ try:
2006
+ await asyncio.to_thread(filters.delete(userId="me", id=filter_id).execute)
2007
+ except Exception as error:
2008
+ raise ToolExecutionError(
2009
+ f"Created the new filter {created.get('id', '(unknown)')} but could "
2010
+ f"not delete the old filter {filter_id}: both are active now. "
2011
+ f"Delete {filter_id} manually. Cause: {error}"
2012
+ ) from error
2013
+ created.setdefault("criteria", body["criteria"])
2014
+ created.setdefault("action", body["action"])
2015
+ return created
2016
+
2017
+
2018
+ async def apply_gmail_filter_to_existing(
2019
+ service,
2020
+ criteria: Mapping[str, Any],
2021
+ filter_action: Mapping[str, Any],
2022
+ dry_run: bool = False,
2023
+ max_messages: int = FILTER_APPLY_DEFAULT_MAX_MESSAGES,
2024
+ ) -> Dict[str, Any]:
2025
+ """Apply a filter's label actions to messages already in the mailbox.
2026
+
2027
+ Gmail filters only act on new mail. Only matching messages change, not the
2028
+ rest of their threads, mirroring how the filter treats incoming mail.
2029
+ Forwarding is never applied retroactively.
2030
+ Returns a summary dict (query, matched, truncated, applied, notes).
2031
+ """
2032
+ query = filter_criteria_to_query(criteria)
2033
+ if not query:
2034
+ raise ValueError("Filter criteria produce an empty search query; refusing.")
2035
+ add = list(filter_action.get("addLabelIds") or [])
2036
+ remove = list(filter_action.get("removeLabelIds") or [])
2037
+ notes: List[str] = []
2038
+ if filter_action.get("forward"):
2039
+ notes.append("Forwarding is not applied to existing mail.")
2040
+ if criteria.get("excludeChats"):
2041
+ notes.append("excludeChats has no search equivalent and was ignored.")
2042
+
2043
+ ids: List[str] = []
2044
+ page_token: Optional[str] = None
2045
+ while len(ids) < max_messages:
2046
+ params: Dict[str, Any] = {"userId": "me", "q": query, "maxResults": 500}
2047
+ if page_token:
2048
+ params["pageToken"] = page_token
2049
+ response = await asyncio.to_thread(
2050
+ service.users().messages().list(**params).execute
2051
+ )
2052
+ ids.extend(m["id"] for m in response.get("messages") or [])
2053
+ page_token = response.get("nextPageToken")
2054
+ if not page_token:
2055
+ break
2056
+ truncated = len(ids) > max_messages or bool(page_token)
2057
+ ids = ids[:max_messages]
2058
+
2059
+ applied = 0
2060
+ if not dry_run and ids and (add or remove):
2061
+ body: Dict[str, Any] = {}
2062
+ if add:
2063
+ body["addLabelIds"] = add
2064
+ if remove:
2065
+ body["removeLabelIds"] = remove
2066
+ for start in range(0, len(ids), GMAIL_BATCH_MODIFY_LIMIT):
2067
+ chunk = ids[start : start + GMAIL_BATCH_MODIFY_LIMIT]
2068
+ await asyncio.to_thread(
2069
+ service.users()
2070
+ .messages()
2071
+ .batchModify(userId="me", body={"ids": chunk, **body})
2072
+ .execute
2073
+ )
2074
+ applied += len(chunk)
2075
+ if not add and not remove:
2076
+ notes.append("The filter has no label actions; nothing to apply.")
2077
+ return {
2078
+ "query": query,
2079
+ "matched": len(ids),
2080
+ "truncated": truncated,
2081
+ "applied": applied,
2082
+ "add": add,
2083
+ "remove": remove,
2084
+ "notes": notes,
2085
+ }
2086
+
2087
+
2088
+ def format_filter_apply_result(result: Mapping[str, Any], dry_run: bool) -> str:
2089
+ """Human-readable summary for apply_gmail_filter_to_existing."""
2090
+ matched = f"{result['matched']}{'+' if result['truncated'] else ''}"
2091
+ lines = [
2092
+ "DRY RUN: nothing changed."
2093
+ if dry_run
2094
+ else f"Applied to {result['applied']} messages.",
2095
+ f"Query: {result['query']}",
2096
+ f"Matching messages: {matched}",
2097
+ ]
2098
+ if result["add"]:
2099
+ lines.append(f"Add labels: {', '.join(result['add'])}")
2100
+ if result["remove"]:
2101
+ lines.append(f"Remove labels: {', '.join(result['remove'])}")
2102
+ lines.extend(result["notes"])
2103
+ if result["truncated"] and not dry_run:
2104
+ lines.append(
2105
+ "Stopped at max_messages; raise it to process the remaining matches."
2106
+ )
2107
+ return "\n".join(lines)