Repository navigation
feat(email): read Gmail from the flagship agent's email tools - #4085
Conversation
Drives a real httpx client over MockTransport so the outgoing request shape is what gets asserted, not that a stub was called.
Errors are built from Gmail's structured reason and extendedHelp fields only, never the raw response body -- that text is upstream-controlled and ends up in front of a user.
Key-set equality passes while every value is wrong, so each field is asserted by type and format: UTC-suffixed received, bool unread/flagged, RFC 5322 address parsing, unescaped snippet, user-only labels, raw body. Fixtures come from the real mbox translator, not hand-authored dicts.
Same key set and same value formats as the Graph backend, so the tools and the inbox-triage skill never learn which mailbox answered.
Asserts labelIds are IDs from Gmail's documented system set rather than display names, that metadataHeaders rides with format=metadata, that a failed fetch raises instead of shortening the list, and that a zero-result listing with the messages key omitted returns an empty inbox rather than raising.
Gmail's list returns id stubs, so every message costs a get. Fanning them over a small pool keeps a 25-message listing inside the agent's tool timeout, and forcing the results means a failed fetch raises instead of quietly returning a smaller inbox.
list_mail_folders had no shape test on either backend, so this writes the folder parity harness from scratch: Gmail INBOX against the case-insensitive lookup the tool performs, and SENT/SPAM mixed among user labels.
Completes the five reads. Folder counts come from labels.get because labels.list omits them, and reading a body needs format=full since metadata mode strips the MIME parts.
Separates what a new consent requests from what confers read, so an existing broader connection is reused rather than forcing a browser reconnect, and a first-time user is still only asked to read.
The grant ledger matches scopes exactly with no implication, so insisting on gmail.readonly would send a user whose connection already carries gmail.modify through a browser reconnect. Resolving against what the connection holds reuses it, while a new consent is still asked for read only. Narrows what is requested and never widens it, which is why it sits beside the mixin rather than inside the connectors primitive.
…tates A boolean granted-or-not would tell a user to grant in exactly the case where granting cannot work, so each provider is classified separately and each state carries its own remedy. Also gates the one-shot re-resolve, so a grant made mid-session does not need a restart.
…dness connected_mailbox_providers() reports every stored OAuth blob, which on a box with both accounts distinguishes nothing. Selection now classifies each provider as not connected, needing reauth, missing scopes, or ungranted, and the failure names each mailbox's own state and remedy -- telling a user to grant a mailbox they never connected is the wrong advice. A grant made mid-session re-resolves the backend once instead of needing a restart.
providers/google.py claims a test enforces that every declared scope has a consent description. No such test existed, so a newly declared scope would have rendered as a raw URL in the dialog. This adds it.
…tion The consent declaration asks for gmail.readonly only, so a first-time user is never shown read, modify and send. Corrects the spec's claim that the Gmail backend is a relocation of the sidecar's -- the credentials are shared, the code is not.
python util/lint.py --all now exits 0.
The id arrives from the model and is interpolated into the URL path, so a value like ../labels/INBOX would reach a different endpoint.
wc -l at this commit, not the figures the plan was written against.
The previous assertion allowed 0.8s where serial would take 1.25s — about 36% headroom, which a contended runner eats. It now counts peak in-flight requests instead, so it holds under any load, and it also pins the upper bound so an unbounded fan-out cannot pass. Verified both ways: 5 consecutive green runs, and forcing the pool to one worker fails it.
…ector-derived The repo already decided this and guards it: an env var picks a mailbox without consulting the grant ledger, which is the gate that makes the choice auditable. Switching mailboxes now means revoking the grant for the one that won, which check_mailbox_access names and the guide documents. Discoverability is unchanged -- provider, provider_source and alternatives still say which mailbox answered and what else was available. Also asserts the three banned env var names have no effect, so the override cannot return under a different spelling.
|
Re-verified after syncing this branch onto current The 🔍 Technical detailsHead under test: Local suites — (The first count is 122 rather than the 113 in the test plan because the base sync brought in the tests added by #4088.) Upstream contract change, checked for a parity gap. The Gmail arm added here already carries the equivalent guard — The { "type": "result", "subtype": "success", "is_error": true,
"duration_ms": 88895, "num_turns": 14,
"total_cost_usd": 1.1641380000000001 }Fourteen turns and $1.16 billed rules out a spend/quota rejection, and no Not claimed: no eval was run. The judge is rejected on the Anthropic org's monthly spend limit (#4080), so an eval result here would be fabricated. |
Closes amd#4086 Asking the agent "what needs me today?" makes it read several emails in one go. Each single message was already capped at 12,000 characters, but nothing capped the pile — read four or five long quoted threads and the model quietly ran out of room, losing the earlier half of its own conversation and answering from a partial view with no error anywhere. Mail reading now has a per-turn character budget sized from the machine's real context window, and once a turn has spent it the next read is refused with a result that tells the model to stop, answer from what it already read, and say so. The budget resets on the next turn. The bound sits in the shared mixin, above both mailbox backends, so Gmail and Outlook behave identically; neither backend file is touched. <details> <summary>🔍 Technical details</summary> **No new tuning constant.** The turn budget is `Agent._truncation_budget()[0]` — the same per-tool-result character cap already applied to any other large tool output, derived from the device profile via `budget_for_ctx`. Policy in one sentence: all the mail bodies a turn pulls in together may occupy what one large tool result is allowed to. It is therefore profile-derived by construction, and already correct for a `-FLM` NPU model, a cloud/gateway session, and Claude's 200K window. | profile | ctx | turn budget | measured spend at refusal | % of window at the issue's worst ratio (3.02) | |---|---|---|---|---| | NPU | 32,768 | 30,000 chars | 36,000 chars after 3 reads | 36% | | GPU/CPU | 65,536 | 60,000 chars | 60,000 chars after 5 reads | 30% | **Admission rule.** A read is admitted while `used < budget`, so at most one message crosses the line and that one is itself capped at `_MAX_BODY_CHARS` — a turn can never admit an unbounded pile. Refusing earlier (when `budget - used < _MAX_BODY_CHARS`) would make the bound strictly ≤ budget but costs a whole read whenever bodies are small: two reads on NPU, too stingy for the triage case the issue is about. **Turn detection.** `Agent` gains a monotonic `_turn_seq`, incremented in `_process_query_impl` — the single path every entry point (CLI, UI, API server, sidecar, hub servers) goes through. The mixin reads it with `getattr` and resets its ledger when it moves. `_on_task_start` was not usable: `EmailToolsMixin` is listed after `ChatAgent` in `GaiaAgent`'s bases, so `Agent`'s no-op would win the MRO — the exact trap `ProjectMapMixin.__init_subclass__` exists to catch — and reordering would put a tool mixin ahead of the base agent, which the comment at `gaia_agent/agent.py:236` warns against. **Replaced rather than adapted** the retired sidecar's `context_budget.py`. The flagship wheel cannot import it (hub package, not a dependency) and its numbers are pinned to that sidecar's 16K eval target. What carried over is the method: derive from the device profile, and be pessimistic about chars per token. **Out of scope, stated:** `list_inbox` / `search_email` return previews bounded by `limit <= 100` and are not charged; `_MAX_BODY_CHARS` (amd#4085's constant) is unchanged; neither message-id guard was touched — they differ deliberately between the two backends. </details> ## Test plan - [x] `pytest tests/unit/agents/` — **1234 passed, 50 skipped** - [x] `python util/lint.py --black --isort` — both PASS - [x] **Mutation check: the guard was disabled (`if used >= budget` → `if False`) and 5 of the 6 new tests failed**; reverted to a byte-identical tree (`git status` clean). The sixth is the profile-derivation test, which correctly does not depend on the guard. - [x] **The budget observed firing**, driving 14,000-char bodies through one turn on each profile: ``` === NPU profile: ctx 32768 tokens, turn budget 30000 chars === read #1: OK body 12000 chars (truncated=True), turn total 12000/30000 read #2: OK body 12000 chars (truncated=True), turn total 24000/30000 read #3: OK body 12000 chars (truncated=True), turn total 36000/30000 read #4: REFUSED {"action": "read_email", "success": false, "turn_budget_exhausted": true, "messages_read_this_turn": 3, "budget_chars": 30000, "budget_used_chars": 36000} error -> This turn has already read 3 message body(ies), filling this turn's mail-reading budget (36000 of 30000 chars) — further reads are refused so the conversation does not silently overflow the context window. Answer from the messages already read, tell the user reading stopped here, and ask them to narrow the request or continue in a new turn. See https://amd-gaia.ai/docs/guides/email turn charged 36000 chars = ~11921 tokens at the worst measured ratio = 36% of the window invariant: charged (36000) <= budget + per-message cap (42000) -> True new turn (_turn_seq 1 -> 2): reading resumes === GPU/CPU profile: ctx 65536 tokens, turn budget 60000 chars === read #1..#5: OK, turn total 60000/60000 read #6: REFUSED budget_chars 60000, budget_used_chars 60000, messages_read_this_turn 5 turn charged 60000 chars = ~19868 tokens at the worst measured ratio = 30% of the window new turn (_turn_seq 1 -> 2): reading resumes ``` - [ ] Not run: `gaia eval` — the judge credential is failing intermittently in CI and would not produce an attributable signal.
Part of #4052 — deliberately not closing it. Criteria 1-4 (the Gmail backend, shape parity with the Outlook arm, read-only consent declaration, and the four-state no-mailbox error) are met and covered by tests here. Two are not, and neither can be met by code:
Leaving #4052 open keeps those visible rather than closing them by implication.
The flagship agent could only read Outlook. Ask it about your Gmail and it answered
Agent 'installed:gaia' has no grant for microsoft— a Microsoft error, on a machine where Google was the connected mailbox. Now the same five email tools read either mailbox, pick the right one on their own, and when neither is usable they say which mailbox is in which state and give you the one command that fixes it.A first-time Google user is asked to read your email and nothing more. If your Google account was already connected for the Email Triage Agent it carries the broader
gmail.modifyscope; the flagship reuses that rather than sending you back through a browser, and needs only a local grant-ledger write.Two things the reviewer should know
The spec was wrong and this PR corrects it. Issue #4052 and
docs/plans/email-triage-skill.mdx:134both describe this as "a backend relocation" of the sidecar'sgmail_backend.py. The credentials are genuinely shared; the code is not.🔍 Why it could not be a relocation
_email/graph.py:10-14already states the rule this follows: the flagship must not depend on the standalone email package it is meant to replace.gmail_backend.py:59-63importsgaia_agent_email.google_errorsandgaia_agent_email.scopes— both sidecar-package modules.LiveGmailBackendnever emits the provider-neutral shape.list_messages(:790-811) returns{"messages":[{"id","threadId"}]}— id stubs, no headers — andget_message(:813-819) returns the raw Gmail resource. The flattening lives ingaia_agent_email/tools/read_tools.py(3414 lines), which does not come along. Without it none ofmessage_summary's shape exists, and that shape is the whole reason the skill never learns which mailbox answered.Measured:
gmail.pyis 425 lines againstgmail_backend.py's 1256, matching what Phase 0 did (242 vsoutlook_backend.py's 722). The plan doc is corrected in this PR — both the "relocated from" table row and the "largely a relocation, not a rewrite" paragraph above it.One pre-existing flaw is deliberately not fixed here.
graph.py:119interpolates rawresponse.text[:300]into a user-facing error string. It lives in the Outlook backend, which this change does not otherwise touch, and folding an unrelated cleanup into a feature PR blurs the diff. The new Gmail backend does not copy the pattern: its errors are built only from Gmail's structuredreasonfield and anextendedHelplink rejected unless it starts withhttps://. Tracked separately in #4082.Test plan
python -m pytest tests/unit/agents/tools/ -q→ 113 passed. Includes all 33 pre-existing email tests, unmodified.python -m pytest hub/agents/gaia/python/tests/test_gaia_agent.py -q→ 22 passed (19 before, 3 added). Thetools_count: 80drift guard still holds: no tool was added or renamed.python util/lint.py --all→ exit 0. Black, isort, Pylint, Flake8, Import Validation and Bandit all PASS.python -m pytest tests/unit/ -q -p no:randomly→ 24 failing node ids on this branch, 28 on a clean checkout of the base commit. Zero failures are unique to this branch; the branch fixes none of them either (the 4-test difference is agaiaconsole-script PATH check, environment state). Both runs captured in full.Shape parity is asserted by value type and format, not key presence — a green key-set test passes while every value is wrong.
receivedisZ-suffixed UTC built from epoch-millis (a naivefromtimestampbreaks "what came in today");fromsurvives both"Doe, Jane" <j@x>and=?UTF-8?B?…?=;previewis entity-unescaped;CATEGORY_PROMOTIONSnever reaches the field the triage skill reads as user tags; an inline base64 attachment is asserted absent from the body.Outgoing request shape is asserted too, over a real
httpx.MockTransport:labelIdsare checked against Gmail's documented system-label IDs (Gmail 400s on names),metadataHeadersis asserted to ride withformat=metadata, a failed fetch is asserted to raise rather than silently shorten a listing, and the empty-mailbox path is driven by a transport that omits themessageskey the way the real API does.Not closed by this PR
read_emailcaps one body at 12,000 characters and marks the truncation visibly, which is ~12% of the 32K NPU context at the worst density I measured (3.0 chars/token, for quoted thread history — plain text runs 4.7 and HTML 3.7). But the cap is per message: an agent reading eight messages while triaging can still exhaust the window, and nothing tracks the running total. Out of scope here; tracked separately.q-parameter test that is present.