Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(tools): slim Gmail reads + cap all tool output before the brain
Ruben Lütkea891ec033afa
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.pyindex 7e66de1c7e..a316e6fc56 100644--- a/jarvis/brain/tool_use_loop.py+++ b/jarvis/brain/tool_use_loop.py@@ -26,6 +26,27 @@ from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL, ToolExecutorfrom .iteration_budget import IterationBudgetfrom .streaming import StreamingAggregate, aggregate, aggregate_with_consumer+# Central backstop for tool-output bloat: no tool result may exceed this many+# chars in the tool-role message fed back to the brain. Individual tools should+# self-slim (a raw Gmail ``format=full`` message is ~23k chars of headers ++# base64), but this cap guarantees a bound for EVERY tool — present and future —+# so one verbose provider can never flood the context, slow the turn and crowd+# out the answer (live bug 2026-07-01). The event-bus/DB preview cap+# (``safe_preview``) is a separate path and never touched what the model saw.+_MAX_TOOL_RESULT_CHARS = 8000+++def _cap_tool_result_json(serialized: str) -> str:+ """Truncate an over-long serialized tool result, leaving an honest marker so+ the model knows the payload was clipped (rather than silently ending)."""+ if len(serialized) <= _MAX_TOOL_RESULT_CHARS:+ return serialized+ kept = serialized[:_MAX_TOOL_RESULT_CHARS]+ return (+ f"{kept}… [truncated: tool output was {len(serialized)} chars, "+ f"capped at {_MAX_TOOL_RESULT_CHARS}]"+ )+def _images_from_artifacts(artifacts: object) -> list[ImageBlock]:"""Extract ImageBlocks from a tool's artifacts (Wave 2 on-demand vision).@@ -747,13 +768,18 @@ class ToolUseLoop:if readback is not None:suppress_output = readback- # Append tool result as a new message+ # Append tool result as a new message. Cap it centrally so no+ # tool can flood the brain's context with an unbounded raw payload+ # (the actual image artifacts still ride separately as a user-role+ # message below, so clipping this text never blinds vision).current_messages.append(BrainMessage(role="tool",content=[{"type": "tool_result","tool_use_id": call_id,- "content": json.dumps(tool_result_payload, ensure_ascii=False, default=str),+ "content": _cap_tool_result_json(+ json.dumps(tool_result_payload, ensure_ascii=False, default=str)+ ),}],tool_call_id=call_id,name=tool_name,diff --git a/jarvis/plugins/tool/gmail_rest.py b/jarvis/plugins/tool/gmail_rest.pyindex 7cdbf41d0b..bc41f12136 100644--- a/jarvis/plugins/tool/gmail_rest.py+++ b/jarvis/plugins/tool/gmail_rest.py@@ -31,6 +31,72 @@ _NEEDS_RECONNECT = ("please reconnect Gmail in the Plugins view.")+# A raw Gmail ``format=full`` message is ~20k+ chars of Received/ARC/DKIM+# headers, the full MIME part tree and base64 body — feeding it into the model+# context slowed a voice turn to ~20 s and added no answer value (live bug+# 2026-07-01 "Was steht alles in meinen E-Mails drin?"). We project a read down+# to the fields that actually answer a mail question and cap the plain-text body.+_GMAIL_BODY_CHAR_CAP = 2000+++def _decode_b64url(data: str) -> str:+ try:+ return base64.urlsafe_b64decode(data.encode("ascii")).decode("utf-8", "replace")+ except Exception: # noqa: BLE001+ return ""+++def _strip_html(html: str) -> str:+ import re++ text = re.sub(r"<[^>]+>", " ", html)+ return re.sub(r"\s+", " ", text).strip()+++def _find_part_data(payload: dict[str, Any], mime: str) -> str | None:+ """Depth-first search for the first MIME part of ``mime`` that carries body+ data, returning the raw base64url string (or ``None``)."""+ if payload.get("mimeType") == mime:+ data = (payload.get("body") or {}).get("data")+ if data:+ return data+ for part in payload.get("parts") or []:+ found = _find_part_data(part, mime)+ if found:+ return found+ return None+++def _slim_gmail_message(raw: dict[str, Any]) -> dict[str, Any]:+ """Project a raw Gmail ``format=full`` message to sender/recipients/subject/+ date/label-state/snippet plus a decoded, length-capped plain-text body.+ Prefers a ``text/plain`` part; falls back to a stripped ``text/html`` part."""+ payload = raw.get("payload") or {}+ headers = {+ (h.get("name") or "").lower(): h.get("value", "")+ for h in (payload.get("headers") or [])+ }+ plain = _find_part_data(payload, "text/plain")+ if plain:+ body = _decode_b64url(plain)+ else:+ html = _find_part_data(payload, "text/html")+ body = _strip_html(_decode_b64url(html)) if html else ""+ if len(body) > _GMAIL_BODY_CHAR_CAP:+ body = body[:_GMAIL_BODY_CHAR_CAP] + "… [truncated]"+ return {+ "id": raw.get("id"),+ "threadId": raw.get("threadId"),+ "labelIds": raw.get("labelIds", []),+ "from": headers.get("from", ""),+ "to": headers.get("to", ""),+ "cc": headers.get("cc", ""),+ "subject": headers.get("subject", ""),+ "date": headers.get("date", ""),+ "snippet": raw.get("snippet", ""),+ "body": body,+ }+def _default_token_provider() -> str | None:from jarvis.marketplace.token_store import TokenStore@@ -231,4 +297,9 @@ class GmailRestTool:if isinstance(out, dict) and out.get("error"):return ToolResult(success=False, output=None, error=out["error"])+ # A read returns the whole raw message; slim it before it reaches the+ # brain's context (list_messages is already just IDs, send returns a tiny+ # ack — neither needs projecting).+ if action == "get_message" and isinstance(out, dict):+ out = _slim_gmail_message(out)return ToolResult(success=True, output=out)diff --git a/jarvis/skills/builtin/plugin-asana/SKILL.md b/jarvis/skills/builtin/plugin-asana/SKILL.mdindex d1405f84fd..721becc69d 100644--- a/jarvis/skills/builtin/plugin-asana/SKILL.md+++ b/jarvis/skills/builtin/plugin-asana/SKILL.md@@ -5,11 +5,11 @@ description: Manage the user's Asana tasks and projects.when_to_use: Use when the user mentions Asana or wants to view, create, assign, or close Asana tasks and projects.category: productivityplugin_id: asana-intent_verbs: [zeig, lies, erstell, zuweis, schließ, aktualisier] <!-- i18n-allow -->-intent_objects: [asana, asana-task, asana-aufgabe, asana-projekt, asana-team]+intent_verbs: [zeig, lies, erstell, zuweis, schließ, aktualisier] # i18n-allow+intent_objects: [asana, asana-task, asana-aufgabe, asana-projekt, asana-team] # i18n-allowtriggers:- type: voice- pattern: "(asana|asana-task|asana-projekt|in asana)"+ pattern: "(asana|asana-task|asana-projekt|in asana)" # i18n-allowrequires_tools: [asana]risk_policy:default_tier: monitordiff --git a/jarvis/skills/builtin/plugin-cloudflare/SKILL.md b/jarvis/skills/builtin/plugin-cloudflare/SKILL.mdindex baaa0dcfe2..6e6abf63e8 100644--- a/jarvis/skills/builtin/plugin-cloudflare/SKILL.md+++ b/jarvis/skills/builtin/plugin-cloudflare/SKILL.md@@ -5,11 +5,11 @@ description: Manage the user's Cloudflare DNS records, zones, and Workers.when_to_use: Use when the user mentions Cloudflare or wants to inspect or change DNS records, zones, or Workers.category: developerplugin_id: cloudflare-intent_verbs: [zeig, lies, erstell, konfigurier, aktualisier]-intent_objects: [cloudflare, cloudflare-dns, cloudflare-zone, cloudflare-worker, cloudflare-record]+intent_verbs: [zeig, lies, erstell, konfigurier, aktualisier] # i18n-allow+intent_objects: [cloudflare, cloudflare-dns, cloudflare-zone, cloudflare-worker, cloudflare-record] # i18n-allowtriggers:- type: voice- pattern: "(cloudflare|cloudflare-dns|cloudflare-zone|in cloudflare)"+ pattern: "(cloudflare|cloudflare-dns|cloudflare-zone|in cloudflare)" # i18n-allowrequires_tools: [cloudflare]risk_policy:default_tier: askdiff --git a/jarvis/skills/builtin/plugin-discord/SKILL.md b/jarvis/skills/builtin/plugin-discord/SKILL.mdindex 56dfb11bd6..5209f3cdee 100644--- a/jarvis/skills/builtin/plugin-discord/SKILL.md+++ b/jarvis/skills/builtin/plugin-discord/SKILL.md@@ -5,11 +5,11 @@ description: Read and post messages in the user's Discord server.when_to_use: Use when the user mentions Discord or wants to read or post messages in their Discord server.category: communicationplugin_id: discord-intent_verbs: [schick, sende, poste, zeig, lies, antworte]-intent_objects: [discord, discord-server, discord-channel, discord-kanal, discord-nachricht, guild] <!-- i18n-allow -->+intent_verbs: [schick, sende, poste, zeig, lies, antworte] # i18n-allow+intent_objects: [discord, discord-server, discord-channel, discord-kanal, discord-nachricht, guild] # i18n-allowtriggers:- type: voice- pattern: "(discord|discord-server|discord-channel|auf discord)"+ pattern: "(discord|discord-server|discord-channel|auf discord)" # i18n-allowrequires_tools: [discord]risk_policy:default_tier: askdiff --git a/jarvis/skills/builtin/plugin-github/SKILL.md b/jarvis/skills/builtin/plugin-github/SKILL.mdindex bede5af34c..888a61810c 100644--- a/jarvis/skills/builtin/plugin-github/SKILL.md+++ b/jarvis/skills/builtin/plugin-github/SKILL.md@@ -5,11 +5,11 @@ description: Work with the user's GitHub repositories, issues, and pull requestswhen_to_use: Use when the user mentions GitHub, a repo, an issue, or a pull request and wants to inspect or act on it.category: developerplugin_id: github-intent_verbs: [zeig, lies, erstell, öffne, schließ, merge, review, kommentier] <!-- i18n-allow -->-intent_objects: [github, github-issue, repo, repository, pull, pullrequest, pr, branch, commit, workflow]+intent_verbs: [zeig, lies, erstell, öffne, schließ, merge, review, kommentier] # i18n-allow+intent_objects: [github, github-issue, repo, repository, pull, pullrequest, pr, branch, commit, workflow] # i18n-allowtriggers:- type: voice- pattern: "(github|pull request|pull-request|\\bpr\\b|repo|repository)"+ pattern: "(github|pull request|pull-request|\\bpr\\b|repo|repository)" # i18n-allowrequires_tools: [github]risk_policy:default_tier: askdiff --git a/jarvis/skills/builtin/plugin-gmail/SKILL.md b/jarvis/skills/builtin/plugin-gmail/SKILL.mdindex d2092912fd..3fe74f58c2 100644--- a/jarvis/skills/builtin/plugin-gmail/SKILL.md+++ b/jarvis/skills/builtin/plugin-gmail/SKILL.md@@ -5,11 +5,11 @@ description: Read and send email from the user's connected Gmail inbox.when_to_use: Use when the user mentions Gmail, their inbox, or mail and wants to read, search, send, or answer email.category: communicationplugin_id: gmail-intent_verbs: [lies, lese, schick, sende, antworte, zeig, check]-intent_objects: [postfach, inbox, gmail, mail, email, e-mail, mails, nachrichten, posteingang]+intent_verbs: [lies, lese, schick, sende, antworte, zeig, check] # i18n-allow+intent_objects: [postfach, inbox, gmail, mail, email, e-mail, mails, nachrichten, posteingang] # i18n-allowtriggers:- type: voice- pattern: "(gmail|postfach|posteingang|meine? mails?|neue mails?)"+ pattern: "(gmail|postfach|posteingang|meine? mails?|neue mails?)" # i18n-allowrequires_tools: [gmail]risk_policy:default_tier: askdiff --git a/jarvis/skills/builtin/plugin-google_calendar/SKILL.md b/jarvis/skills/builtin/plugin-google_calendar/SKILL.mdindex 9a1ce5df03..1822723998 100644--- a/jarvis/skills/builtin/plugin-google_calendar/SKILL.md+++ b/jarvis/skills/builtin/plugin-google_calendar/SKILL.md@@ -5,11 +5,11 @@ description: Read and manage events in the user's Google Calendar.when_to_use: Use when the user mentions Google Calendar or wants to check, create, move, or delete calendar events or appointments.category: productivityplugin_id: google_calendar-intent_verbs: [zeig, lies, such, erstell, plan, verschieb, lösch] <!-- i18n-allow -->-intent_objects: [kalender, google-kalender, google-calendar, gcal, termin, termine, meeting, ereignis]+intent_verbs: [zeig, lies, such, erstell, plan, verschieb, lösch] # i18n-allow+intent_objects: [kalender, google-kalender, google-calendar, gcal, termin, termine, meeting, ereignis] # i18n-allowtriggers:- type: voice- pattern: "(google.?(kalender|calendar)|gcal|(in )?(meine[nm]? )?(kalender|termin|meeting))"+ pattern: "(google.?(kalender|calendar)|gcal|(in )?(meine[nm]? )?(kalender|termin|meeting))" # i18n-allowrequires_tools: [google_calendar]risk_policy:default_tier: monitordiff --git a/jarvis/skills/builtin/plugin-google_drive/SKILL.md b/jarvis/skills/builtin/plugin-google_drive/SKILL.mdindex 665c1d47c9..ddc681b97b 100644--- a/jarvis/skills/builtin/plugin-google_drive/SKILL.md+++ b/jarvis/skills/builtin/plugin-google_drive/SKILL.md@@ -5,11 +5,11 @@ description: Search, read, and manage files in the user's Google Drive.when_to_use: Use when the user mentions Google Drive or wants to search, read, share, or manage Drive files.category: productivityplugin_id: google_drive-intent_verbs: [zeig, lies, such, öffne, teil, lade] <!-- i18n-allow -->-intent_objects: [drive, google-drive, google-drive-datei, google-drive-ordner, gdrive]+intent_verbs: [zeig, lies, such, öffne, teil, lade] # i18n-allow+intent_objects: [drive, google-drive, google-drive-datei, google-drive-ordner, gdrive] # i18n-allowtriggers:- type: voice- pattern: "(google.?drive|gdrive|in (meinem )?drive)"+ pattern: "(google.?drive|gdrive|in (meinem )?drive)" # i18n-allowrequires_tools: [google_drive]risk_policy:default_tier: monitordiff --git a/jarvis/skills/builtin/plugin-linear/SKILL.md b/jarvis/skills/builtin/plugin-linear/SKILL.mdindex 81cd046772..24c491a15f 100644--- a/jarvis/skills/builtin/plugin-linear/SKILL.md+++ b/jarvis/skills/builtin/plugin-linear/SKILL.md@@ -5,11 +5,11 @@ description: Manage the user's Linear issues, projects, and cycles.when_to_use: Use when the user mentions Linear or wants to view, create, update, or close Linear issues and cycles.category: developerplugin_id: linear-intent_verbs: [zeig, lies, erstell, aktualisier, schließ, zuweis] <!-- i18n-allow -->-intent_objects: [linear, linear-issue, linear-ticket, linear-projekt, linear-cycle, linear-zyklus]+intent_verbs: [zeig, lies, erstell, aktualisier, schließ, zuweis] # i18n-allow+intent_objects: [linear, linear-issue, linear-ticket, linear-projekt, linear-cycle, linear-zyklus] # i18n-allowtriggers:- type: voice- pattern: "(linear|linear-issue|linear-ticket|in linear)"+ pattern: "(linear|linear-issue|linear-ticket|in linear)" # i18n-allowrequires_tools: [linear]risk_policy:default_tier: monitordiff --git a/jarvis/skills/builtin/plugin-notion/SKILL.md b/jarvis/skills/builtin/plugin-notion/SKILL.mdindex 4a8b168d9c..41401e4ff5 100644--- a/jarvis/skills/builtin/plugin-notion/SKILL.md+++ b/jarvis/skills/builtin/plugin-notion/SKILL.md@@ -5,11 +5,11 @@ description: Read and edit the user's Notion pages and databases.when_to_use: Use when the user mentions Notion or wants to read, search, or edit Notion pages and databases.category: productivityplugin_id: notion-intent_verbs: [zeig, lies, erstell, such, aktualisier, ergänz] <!-- i18n-allow -->-intent_objects: [notion, seite, seiten, page, datenbank, dokument]+intent_verbs: [zeig, lies, erstell, such, aktualisier, ergänz] # i18n-allow+intent_objects: [notion, seite, seiten, page, datenbank, dokument] # i18n-allowtriggers:- type: voice- pattern: "(notion|notion-seite|notion-datenbank)"+ pattern: "(notion|notion-seite|notion-datenbank)" # i18n-allowrequires_tools: [notion]risk_policy:default_tier: monitordiff --git a/jarvis/skills/builtin/plugin-slack/SKILL.md b/jarvis/skills/builtin/plugin-slack/SKILL.mdindex 5dbf2eaff7..e372f44581 100644--- a/jarvis/skills/builtin/plugin-slack/SKILL.md+++ b/jarvis/skills/builtin/plugin-slack/SKILL.md@@ -5,11 +5,11 @@ description: Read and post messages in the user's Slack workspace and channels.when_to_use: Use when the user mentions Slack or wants to read or post messages in their Slack workspace.category: communicationplugin_id: slack-intent_verbs: [schick, sende, poste, zeig, lies, antworte]-intent_objects: [slack, slack-channel, slack-kanal, slack-workspace, slack-nachricht] <!-- i18n-allow -->+intent_verbs: [schick, sende, poste, zeig, lies, antworte] # i18n-allow+intent_objects: [slack, slack-channel, slack-kanal, slack-workspace, slack-nachricht] # i18n-allowtriggers:- type: voice- pattern: "(slack|slack-channel|slack-kanal|auf slack)"+ pattern: "(slack|slack-channel|slack-kanal|auf slack)" # i18n-allowrequires_tools: [slack]risk_policy:default_tier: askdiff --git a/jarvis/skills/builtin/plugin-stripe/SKILL.md b/jarvis/skills/builtin/plugin-stripe/SKILL.mdindex 7cc115655a..f6350d08ff 100644--- a/jarvis/skills/builtin/plugin-stripe/SKILL.md+++ b/jarvis/skills/builtin/plugin-stripe/SKILL.md@@ -5,11 +5,11 @@ description: Look up Stripe customers, payments, invoices, and account balance.when_to_use: Use when the user mentions Stripe, payments, invoices, customers, or their account balance.category: developerplugin_id: stripe-intent_verbs: [zeig, lies, erstatt, prüf, such] <!-- i18n-allow -->-intent_objects: [stripe, zahlung, zahlungen, payment, payments, kunde, kunden, customer, customers, rechnung, rechnungen, invoice, invoices, abo, abonnement, subscription, guthaben, balance, charge, refund]+intent_verbs: [zeig, lies, erstatt, prüf, such] # i18n-allow+intent_objects: [stripe, zahlung, zahlungen, payment, payments, kunde, kunden, customer, customers, rechnung, rechnungen, invoice, invoices, abo, abonnement, subscription, guthaben, balance, charge, refund] # i18n-allowtriggers:- type: voice- pattern: "(stripe|zahlung|payment|rechnung|invoice|guthaben|kunde)"+ pattern: "(stripe|zahlung|payment|rechnung|invoice|guthaben|kunde)" # i18n-allowrequires_tools: [stripe]risk_policy:default_tier: askdiff --git a/jarvis/skills/builtin/plugin-supabase/SKILL.md b/jarvis/skills/builtin/plugin-supabase/SKILL.mdindex 965c04f966..0e1517191b 100644--- a/jarvis/skills/builtin/plugin-supabase/SKILL.md+++ b/jarvis/skills/builtin/plugin-supabase/SKILL.md@@ -5,11 +5,11 @@ description: Query and manage the user's Supabase database, tables, and projectswhen_to_use: Use when the user mentions Supabase or wants to query tables, run migrations, or inspect projects.category: developerplugin_id: supabase-intent_verbs: [zeig, lies, erstell, migrier, query, abfrag]-intent_objects: [supabase, supabase-datenbank, supabase-tabelle, supabase-projekt, supabase-migration]+intent_verbs: [zeig, lies, erstell, migrier, query, abfrag] # i18n-allow+intent_objects: [supabase, supabase-datenbank, supabase-tabelle, supabase-projekt, supabase-migration] # i18n-allowtriggers:- type: voice- pattern: "(supabase|supabase-datenbank|supabase-tabelle|in supabase)"+ pattern: "(supabase|supabase-datenbank|supabase-tabelle|in supabase)" # i18n-allowrequires_tools: [supabase]risk_policy:default_tier: askdiff --git a/jarvis/skills/builtin/plugin-vercel/SKILL.md b/jarvis/skills/builtin/plugin-vercel/SKILL.mdindex 6885e85059..82fbc5f0de 100644--- a/jarvis/skills/builtin/plugin-vercel/SKILL.md+++ b/jarvis/skills/builtin/plugin-vercel/SKILL.md@@ -5,11 +5,11 @@ description: Inspect the user's Vercel projects and deployments.when_to_use: Use when the user mentions Vercel or asks about deployment status, projects, or build results.category: developerplugin_id: vercel-intent_verbs: [zeig, lies, prüf, check] <!-- i18n-allow -->-intent_objects: [vercel, vercel-deployment, vercel-projekt, deployment, deployments]+intent_verbs: [zeig, lies, prüf, check] # i18n-allow+intent_objects: [vercel, vercel-deployment, vercel-projekt, deployment, deployments] # i18n-allowtriggers:- type: voice- pattern: "(vercel|vercel-deployment|deployment|auf vercel)"+ pattern: "(vercel|vercel-deployment|deployment|auf vercel)" # i18n-allowrequires_tools: [vercel]risk_policy:default_tier: monitordiff --git a/tests/unit/brain/test_tool_use_loop.py b/tests/unit/brain/test_tool_use_loop.pyindex 7979525ff6..8bd8996c7c 100644--- a/tests/unit/brain/test_tool_use_loop.py+++ b/tests/unit/brain/test_tool_use_loop.py@@ -5,7 +5,7 @@ from typing import Anyimport pytest-from jarvis.brain.tool_use_loop import ToolUseLoop+from jarvis.brain.tool_use_loop import _MAX_TOOL_RESULT_CHARS, ToolUseLoopfrom jarvis.core.protocols import BrainDelta, BrainRequest, ToolResult@@ -52,6 +52,55 @@ class _Brain:yield BrainDelta(finish_reason="stop")+class _HugeOutputTool:+ name = "gmail"+ schema: dict[str, Any] = {}+++class _ExecHuge:+ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:+ return ToolResult(success=True, output="X" * 50_000)+++class _ToolThenAnswerBrain:+ def __init__(self) -> None:+ self.requests: list[BrainRequest] = []++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.requests.append(req)+ if len(self.requests) == 1:+ yield BrainDelta(tool_call={"id": "c1", "name": "gmail", "input": {}})+ yield BrainDelta(finish_reason="tool_use")+ return+ yield BrainDelta(content="Zusammengefasst.")+ yield BrainDelta(finish_reason="stop")+++async def test_tool_result_is_capped_before_reaching_brain() -> None:+ """Systemic backstop (2026-07-01): no tool may flood the model context with+ an unbounded raw payload (a raw Gmail ``format=full`` message is ~23k chars).+ A ~50k-char tool output must be truncated — with a marker — before it is+ serialized into the tool-role message the brain sees on the next turn."""+ brain = _ToolThenAnswerBrain()+ loop = ToolUseLoop(+ brain,+ {"gmail": _HugeOutputTool()},+ _ExecHuge(), # type: ignore[arg-type]+ )++ result = await loop.run([], user_utterance="was steht in meinen mails")++ assert "Zusammengefasst" in result.text+ tool_msgs = [+ m for m in brain.requests[1].messages if getattr(m, "role", None) == "tool"+ ]+ assert tool_msgs, "expected a tool-role message in the 2nd request"+ inner = tool_msgs[-1].content[0]["content"]+ assert len(inner) <= _MAX_TOOL_RESULT_CHARS + 200+ assert "truncated" in inner++@pytest.mark.asyncioasync def test_how_to_question_blocks_side_effect_tool() -> None:brain = _Brain()diff --git a/tests/unit/plugins/tool/test_gmail_rest.py b/tests/unit/plugins/tool/test_gmail_rest.pyindex 521049562b..0a812c39ee 100644--- a/tests/unit/plugins/tool/test_gmail_rest.py+++ b/tests/unit/plugins/tool/test_gmail_rest.py@@ -185,3 +185,96 @@ def test_risk_tier_for_args_unknown_action_is_conservative():# An unrecognised action stays conservative (ask), never silently safe.tool = GmailRestTool(access_token_provider=lambda: "x")assert tool.risk_tier_for_args({"action": "purge_everything"}) == "ask"+++# ----------------------------------------------------------------------+# Read output must be SLIM, not raw MIME (live bug 2026-07-01 "Was steht+# alles in meinen E-Mails drin?"): get_message with format=full returns+# ~23k chars of raw headers (ARC-Seal, DKIM), full MIME tree and base64+# body per message. Feeding that into the model context slowed the turn to+# ~20 s and added no answer value. Project to sender/subject/date/snippet ++# a decoded, length-capped plain-text body.+# ----------------------------------------------------------------------+++async def test_get_message_returns_slim_projection_not_raw_mime():+ body_text = "Hallo Ruben, hier ist der Kern der Nachricht. " * 5+ raw_body_b64 = base64.urlsafe_b64encode(body_text.encode("utf-8")).decode("ascii")+ fat = {+ "id": "m1",+ "threadId": "t1",+ "labelIds": ["UNREAD", "INBOX"],+ "snippet": "Hallo Ruben, hier ist der Kern",+ "payload": {+ "mimeType": "multipart/alternative",+ "headers": [+ {"name": "From", "value": "Chef <[email protected]>"},+ {"name": "To", "value": "[email protected]"},+ {"name": "Subject", "value": "Quartalszahlen"},+ {"name": "Date", "value": "Wed, 01 Jul 2026 12:58:21 +0000"},+ {"name": "ARC-Seal", "value": "i=1; a=rsa-sha256; " + "A" * 4000},+ {"name": "DKIM-Signature", "value": "v=1; a=rsa-sha256; " + "B" * 4000},+ ],+ "parts": [+ {"mimeType": "text/plain", "body": {"data": raw_body_b64}},+ {"mimeType": "text/html", "body": {"data": raw_body_b64}},+ ],+ },+ }++ def handler(req: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=fat)++ tool = GmailRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ result = await tool.execute({"action": "get_message", "message_id": "m1"}, ctx=None)+ assert result.success is True+ out = result.output+ assert out["from"] == "Chef <[email protected]>"+ assert out["subject"] == "Quartalszahlen"+ assert out["date"].startswith("Wed, 01 Jul 2026")+ assert out["snippet"] == "Hallo Ruben, hier ist der Kern"+ assert "Kern der Nachricht" in out["body"]++ import json as _json++ serialized = _json.dumps(out)+ # The raw signature noise must be gone entirely.+ assert "ARC-Seal" not in serialized+ assert "DKIM-Signature" not in serialized+ assert "AAAA" not in serialized and "BBBB" not in serialized+ # And the projection is a fraction of the raw payload.+ assert len(serialized) < len(_json.dumps(fat)) // 2+++async def test_get_message_caps_a_long_body():+ long_body = "wort " * 2000 # ~10k chars decoded+ raw_body_b64 = base64.urlsafe_b64encode(long_body.encode("utf-8")).decode("ascii")+ fat = {+ "id": "m2",+ "threadId": "t2",+ "labelIds": ["INBOX"],+ "snippet": "x",+ "payload": {+ "mimeType": "text/plain",+ "headers": [{"name": "Subject", "value": "Long"}],+ "body": {"data": raw_body_b64},+ },+ }++ def handler(req: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=fat)++ tool = GmailRestTool(+ access_token_provider=lambda: "at_123",+ transport=httpx.MockTransport(handler),+ )+ result = await tool.execute({"action": "get_message", "message_id": "m2"}, ctx=None)+ assert result.success is True+ body = result.output["body"]+ assert len(body) <= 2100 # cap (2000) + short truncation marker+ assert "truncated" in body