Skip to content

feat(ui): Node-free email-agent sidecar with user/dev modes - #1884

Merged
itomek-amd merged 23 commits into
amd:mainfrom
kovtcharov:claudia/task-d9a0b79e
Jun 30, 2026
Merged

itomek-amd merged 23 commits into
amd:mainfrom
kovtcharov:claudia/task-d9a0b79e

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Before: the Agent UI could only run the email agent in-process, importing the heavy
email deps into core — the exact Node-free objection that closed epic #1767. After:
the Python backend runs the email agent as an out-of-process sidecar it fetches
(verified), spawns, health-checks, proxies to, and tree-kills directly — no Node.js,
no npm on the runtime path. User mode runs the published frozen binary (SHA-256
verified against binaries.lock.json); dev mode runs the same REST contract from
local source with hot reload, so prompt/tool edits show up live without a
freeze → publish loop.

This is additive and gated behind GAIA_EMAIL_AGENT_MODE (user default /
dev): the existing in-process path is untouched until the supersede decision
(#1767) lands, so nothing breaks today. Routes that don't exist yet (inbox pre-scan,
search #1781, archive/quarantine #1779, calendar #1780) are gated in the proxy with a
loud, issue-named error — never silently faked.

Implements the approved design in docs/plans/email-sidecar-agent-ui.md (#1882);
step-by-step plan + hardening addendum in
docs/plans/email-sidecar-agent-ui-implementation.md.

Depends on #1882 (the design doc). This branch builds on those plan commits;
they'll resolve once #1882 merges.

What's complete (this PR)

A bulletproof, fully-tested standalone sidecar capability ready to wire:

  • Verified fetch — SHA-256 gate (tamper → refuse), ~/.gaia/agents/email/ cache,
    placeholder-refuse, atomic write.
  • Lifecycle — ephemeral port (never 4001), spawn (user binary / dev
    uvicorn server:app --app-dir …), health-poll with service-identity check,
    process-group tree-kill, atexit orphan reaping, port-race retry, concurrency
    lock (one sidecar under concurrent first-use), /version contract handshake.
  • Proxy — forwards triage/draft/send/health/version unchanged; preserves the
    sidecar's actionable error detail via SidecarHTTPError; gates the not-yet-built
    routes.
  • No pipe deadlock — sidecar output goes to a pruned per-port log file, not an
    undrained PIPE.
  • Integration seam — EmailSidecarManager.proxy() + context-manager lifecycle.

One design correction (verified live)

The design's uvicorn packaging.server:app does not resolve — the email package's
packaging/ dir collides with the PyPI packaging library, and adding
packaging/__init__.py would shadow packaging.version for every dependency. Dev
mode instead loads the file as the top-level module server via
uvicorn server:app --app-dir hub/agents/python/email/packaging.

Test plan

  • python -m pytest tests/unit/test_email_sidecar_*.py — 58 tests, incl. live
    dev-mode spawn/health/tree-kill
    and a live real-LLM triage round-trip
    through the manager-owned proxy against the frozen contract (skips cleanly
    without the email wheel / Lemonade).
  • python -m pytest tests/unit/agents/email/test_connector_routes.py — no
    regression from the new module-level app.
  • python util/lint.py --all — passes.
  • Manual dev mode: uv pip install -e hub/agents/python/email then
    GAIA_EMAIL_AGENT_MODE=dev gaia chat --ui.

Gated / deferred (by design)

Plan for triaging personal Gmail through the Agent UI with two
interchangeable sidecar backends behind one fixed REST seam: a frozen
npm binary for users and a hot-reloading uvicorn-from-source server for
developers. Both run the same agent code against the same local Google
grant, so personal email works identically in each and improving the
agent is a one-file edit with no freeze/publish/patch loop.
The first draft assumed the renderer calls a fixed /v1/email REST URL and
that an Electron-main sidecar manager would host it. Code review found the
UI surfaces email through the chat agent loop + SSE cards (the frontend has
no email REST client), and the agent already runs in-process in the Python
backend reading ~/.gaia/connectors/grants.json.

Reframe: the seam is the chat agent's email-tool layer and the host is the
Python UI backend (no Node backend needed). Both modes proxy over the same
HTTP path to a sidecar on :8131 — frozen binary for users, uvicorn --reload
from source for devs — keeping process isolation identical across modes and
preserving the existing SSE card pipeline.
Fold in the two product requirements and resolve every open item from the
architecture review:

- Dogfooding: user mode runs the exact Hub-published frozen binary (pinned via
  binaries.lock.json), so the Agent UI validates the shipped product. This is the
  rationale the sidecar earns over an editable in-process install.
- Lightweight UI: the sidecar is lazy-fetched on first email use, one platform
  binary only; core ships no email deps.
- Resolve open questions: use a proxy AGENT reusing agent_type=email machinery;
  remove the redundant in-process /v1/email mount (amd#1768) so the UI has one backend.
- Review fixes: own the dev-mode enabler (module-level app = build_app()), reuse the
  npm fetch SHA/lock integrity check instead of porting it to Python, ephemeral
  per-instance port (no fixed-8131 multi-instance clash), single-writer grant model
  (OAuth stays on backend; sidecar reads only), exact current-contract table.
- Sequence behind the in-flight REST build-out (pre-scan + amd#1779/amd#1780/amd#1781) and
  flag the amd#1767 in-process decision must be superseded with @itomek sign-off.
…jection)

itomek closed amd#1767/amd#1785 because mixing an npm package requiring Node.js into the
Python-backed Agent UI is too dirty. Remove that entirely: the Python backend fetches
the binary itself (verified SHA-256 download, no npx), spawns it, and proxies over
HTTP. No Node runtime, no npm package in the UI's path. The npm package remains the
external Node-integrator channel only.
Dev mode loads packaging/server.py as the top-level module 'server' via
'uvicorn server:app --app-dir <email>/packaging' so the package's packaging/
dir does not collide with the PyPI packaging library.
Adds the GAIA_EMAIL_AGENT_MODE dev/user doc, a live proxy<->sidecar round-trip
test, and clears pylint/flake8/mypy findings on the new sidecar package.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes labels Jun 27, 2026
…ionable errors, version handshake

Critical runtime fixes from an adversarial review of the sidecar:
- Redirect sidecar stdout/stderr to a per-port log file instead of an undrained
  PIPE, which would deadlock the child once the ~64KB OS buffer filled (uvicorn
  logs a line per request). Early-exit + health-timeout now report the log tail.
- Register an atexit reaper in start() so a backend crash/exit no longer leaks a
  detached sidecar holding its port and a loaded LLM; unregister on shutdown.
- Proxy preserves the sidecar's actionable error detail (e.g. 502 'local LLM
  triage failed') via SidecarHTTPError instead of flattening it into a generic
  HTTPError.
- Add a /version contract handshake after health: capture apiVersion/agentVersion
  and fail loudly on a MAJOR mismatch when an expected version is supplied
  (no email-wheel import in core).
- start() retries only the fast early-exit failure (lost ephemeral-port race ->
  uvicorn bind failure) with a fresh port; a genuine health timeout fails loudly
  once (no latency multiplication).
- Freeze main() reuses the module-level app instead of building a second one.
- Document that the sync manager/proxy must run off the async event loop, plus
  the sidecar log location, version handshake, and atexit reaping in the guide.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Update — hardening pass (adversarial self-review + code-reviewer)

Reviewed the sidecar lifecycle for runtime bugs and fixed the critical ones:

  • No pipe-buffer deadlock. The sidecar's stdout/stderr now go to a per-port
    log file (~/.gaia/agents/email/logs/sidecar-<port>.log), not an undrained
    PIPE that would hang the child once the ~64KB OS buffer filled (uvicorn logs a
    line per request). Failures report the log tail.
  • No orphaned sidecars. An atexit reaper tree-kills the sidecar if the
    backend exits without a clean shutdown, so it never leaks its port or a loaded
    LLM.
  • Actionable errors survive the proxy. A sidecar 502 local LLM triage failed
    (Lemonade down), 403 send-gate, etc. now surface verbatim via
    SidecarHTTPError instead of being flattened into a generic HTTPError.
  • Contract handshake. The backend reads /version on start, records
    apiVersion/agentVersion, and fails loudly on a MAJOR mismatch when a host
    pins an expected version (no email-wheel import in core).
  • Port-race resilience. start() retries only the fast early-exit failure
    (lost ephemeral-port race) with a fresh port; a genuine health timeout fails
    loudly once.
  • Single app build in the freeze entrypoint; async-safety documented (the
    sync manager/proxy must run off the UI event loop via a worker thread).

Tests: 50 sidecar unit tests (incl. live dev-mode spawn/health/tree-kill and a
live proxy round-trip) + 9 existing email connector-route tests, all green;
util/lint.py --all passes.

- Serialize start()/shutdown() with a reentrant lock so a concurrent lazy
  'first email use' from two UI worker threads spawns exactly one sidecar.
- Health probe now requires service=='gaia-agent-email', so a foreign process
  that grabbed the ephemeral port is rejected instead of mistaken for the sidecar.
- A pinned expected_api_version with a missing/empty apiVersion in /version now
  fails loudly instead of silently skipping the contract gate.
…rip test

- EmailSidecarManager.proxy() returns an EmailSidecarProxy bound to the running
  sidecar's port (the manager owns the port; the proxy is the request surface);
  raises if not started.
- Context-manager protocol guarantees shutdown: 'with EmailSidecarManager() as m'.
- Add an end-to-end live test: real dev sidecar + manager proxy + the frozen
  triage contract round-trips a real LLM triage (or surfaces the actionable 502
  when Lemonade is down) — proving the call is valid, not just mocked.
…addendum

- Export SidecarHTTPError + VersionMismatchError from the package.
- Prune per-port sidecar logs to the newest few so ephemeral-port log files
  don't accumulate without bound across restarts.
- Record the hardening addendum in the implementation plan.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Update 2 — hardening milestones M3–M5 (continued critique).

  • Concurrency + identity: start()/shutdown() serialized by a reentrant lock
    (one sidecar under concurrent lazy first-use); health now requires
    service=="gaia-agent-email" so a foreign process on the ephemeral port is
    rejected; a pinned version with a missing apiVersion fails loudly.
  • Integration seam: EmailSidecarManager.proxy() returns a port-bound proxy and
    the manager is a context manager (with EmailSidecarManager() as m:) guaranteeing
    shutdown. Added a live real-LLM triage round-trip test through the manager+proxy
    against the frozen contract.
  • Polish: per-port sidecar logs pruned to the newest few; SidecarHTTPError /
    VersionMismatchError exported; plan addendum recorded.

58 sidecar unit tests green (incl. the two live tests), util/lint.py --all passes.
The one failing test_schema_version_unchanged_by_multi_inbox is pre-existing on
main (contract bumped to 2.1; that test still pins 2.0) and outside this PR's scope.

…is set

Wires the sidecar live into the UI backend (design decision 4 — the single
/v1/email surface). When GAIA_EMAIL_AGENT_MODE is set, the server mounts a proxy
router that lazily spawns the sidecar on the first /v1/email request, forwards
triage/draft/send/health/version, preserves the sidecar's status + actionable
error detail, and tree-kills it on lifespan shutdown — instead of importing the
email wheel in-process. Unset keeps the in-process mount, so default installs work
before the frozen binary is published (no breaking change).

Security: only triage/draft/send/health/version are proxied; the sidecar's
connector OAuth write routes are never exposed to the UI, keeping all grant writes
on the backend's single-writer path.

Verified end-to-end with a live test: UI server route -> EmailSidecarManager ->
real dev sidecar -> response, with lifespan tree-kill.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Update 3 — the sidecar is now live in the backend (M6).

GAIA_EMAIL_AGENT_MODE no longer just selects the spawn mode — when set, the UI
backend now serves /v1/email/* from the sidecar (design decision 4: the single
/v1/email surface). The server mounts a proxy router that lazily spawns the sidecar
on the first request, forwards triage/draft/send/health/version with the sidecar's
status + actionable detail intact, and tree-kills it on lifespan shutdown — instead of
importing the email wheel in-process. Unset keeps the in-process mount, so default
installs are unaffected until the frozen binary is published.

Security: only the five contract endpoints are proxied; the sidecar's connector OAuth
write routes are never exposed to the UI (grant writes stay single-writer on the
backend).

Verified end-to-end live: UI route → EmailSidecarManager → real dev sidecar →
response, with lifespan tree-kill. 68 sidecar unit tests green; util/lint.py --all
passes.

Remaining (distinct, larger piece): the chat inbox pre-scan card still runs
in-process because it needs an inbox-scan REST route the sidecar does not expose yet
(#1781 & friends), plus a chat-agent→proxy-agent swap that touches the agent loop +
SSE. That's sequenced behind those routes and is the natural next epic.

@github-actions github-actions Bot added the agent::email Email agent changes label Jun 30, 2026
Tomasz Iniewicz added 3 commits June 30, 2026 10:44
A raw requests.ConnectionError escaping _forward became an unhandled 500.
Add a final RequestException catch that raises HTTPException(503) with an
actionable "email sidecar unreachable: <reason>" detail, and a unit test
that proves the 503 + detail string.
app.routes._IncludedRouter objects lack a .path attribute on the installed
Starlette version, breaking two tests. Replace route-list introspection with
TestClient HTTP probes (status != 404 proves the route is mounted) so the
assertions are version-independent.
…except

- server.py: pass expected_api_version="2" to EmailSidecarManager so a
  breaking sidecar contract upgrade fails loudly instead of drifting silently.
- proxy.py: default timeout drops from 900s to 300s, overridable via
  GAIA_EMAIL_SIDECAR_TIMEOUT env var; add unit tests for both paths.
- manager.py: remove dead try/except around atexit.unregister (never raises);
  add TOCTOU-safety comment in router._get_proxy explaining the RLock.
@itomek

itomek commented Jun 30, 2026

Copy link
Copy Markdown
Collaborator

Picking this up to get it across the line (Kalin's out today) — validated end-to-end on AMD hardware and hardened for review. Still draft; the supersede/merge call stays with maintainers.

The sidecar works: I ran the dev mode path on real AMD hardware against a live local LLM and it triaged a real email through the out-of-process sidecar, with correct spawn → health → tree-kill lifecycle and a loud failure on every error path. I also folded in 6 small fixes from an adversarial review (one real correctness gap, the rest hardening + two test-robustness fixes), so the suite is fully green.

Test plan — all verified ✅

  • pytest tests/unit/test_email_sidecar_*.py → 71 passed (the 2 previously-failing route-mount tests are fixed — they broke on newer Starlette's _IncludedRouter; now use TestClient probes)
  • pytest tests/unit/agents/email/test_connector_routes.py → 9 passed
  • python util/lint.py --all → pass
  • Manual dev mode → PASS on AMD hardware (evidence below)
🔬 Real-world evidence — dev mode on an AMD Radeon box + Lemonade (Gemma-4-E4B-it-GGUF)

UI backend (GAIA_EMAIL_AGENT_MODE=dev, python -m gaia.ui.server) → out-of-process sidecar (uvicorn on an ephemeral port) → local LLM → structured result.

GET  /v1/email/health   → 200 {"status":"ok","service":"gaia-agent-email"}
GET  /v1/email/version  → 200 {"apiVersion":"2.1","agentVersion":"0.3.0"}

POST /v1/email/triage (an URGENT budget-approval email) → 200:

{"schema_version":"2.1","request_kind":"single","result":{
  "category":"URGENT","is_spam":false,"is_phishing":false,
  "summary":"Alice must approve the attached Q3 budget proposal by end of day today …",
  "action_items":[{"description":"Please review the attached spreadsheet and reply with your approval …"}],
  "suggested_action":"reply",
  "usage":{"prompt_tokens":1228,"completion_tokens":736,"tokens_per_second":126.96}}}

Round-trip latency 11.75s (cold — includes a one-time model context reload).

Lifecycle: the sidecar ran in its own process group, logged to ~/.gaia/agents/email/logs/sidecar-<port>.log; after the backend received SIGTERM, no orphaned sidecar remained (tree-kill works).

Fail-loud (no silent fallback):

  • User mode (binary not yet published, [packaging] Fully-automated R2 publish + thin npm package #1648) → 503 with the actionable "PENDING-1648 … run dev mode / publish the agent" message, on both /health and /triage.
  • Sidecar kill -9'd mid-session → the next request auto-respawned it (200). No hang, no silent wrong answer.
🔧 Fixes added on top of the original branch (commits c0893f6, 951d79c, d937446)

From an adversarial code + architecture review (which found no Critical issues against the original design — the lifecycle, concurrency-safe lazy start, and tree-kill all check out):

  • Correctness: _forward now catches requests.RequestException → a loud 503 "email sidecar unreachable" instead of a generic 500 when the sidecar dies mid-request (the one real gap — the lazy-start path was already covered).
  • Hardening: activated the contract version gate (EmailSidecarManager(expected_api_version="2")) so a breaking sidecar major fails loudly; removed a dead except Exception: pass around atexit.unregister (no-silent-fallback compliance); added a TOCTOU-safety note on the lock-free is_running pre-check.
  • Scalability: proxy timeout 900s → 300s, GAIA_EMAIL_SIDECAR_TIMEOUT-configurable (a 15-min blocking localhost call risked threadpool exhaustion).
  • Tests: the 2 route-mount tests made Starlette-version-robust (TestClient probes), plus new tests for the 503 path and the timeout env.

The real-world golden path above was captured on the base commit; these changes are error-path / config / test only and leave the success path unchanged — re-validated by the full suite (80 passed) including the live dev-mode spawn/health/tree-kill test, and lint.

Scope — what's intentionally NOT here (the parked epic #1896, v0.23.0)

This PR is the additive, env-gated foundation — it does not complete the user-facing "email in Agent UI" feature. Still ahead in #1896: the frozen-binary publish (#1648, which unblocks user mode), the richer REST routes (#1778–#1781 → pre-scan / archive / calendar / search), the chat-agent→proxy swap, removing the in-process mount, and dogfood (#1653). Default installs (flag unset) keep the in-process mount and are unaffected.

@itomek itomek self-assigned this Jun 30, 2026
@itomek
itomek marked this pull request as ready for review June 30, 2026 15:00
@itomek
itomek requested a review from kovtcharov-amd as a code owner June 30, 2026 15:00
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: ✅ Approve (with minor suggestions)

This adds a Node-free, out-of-process email-agent sidecar the Python UI backend fetches (SHA-256 verified), spawns, health-checks, proxies to, and tree-kills — gated behind GAIA_EMAIL_AGENT_MODE so the default in-process path is untouched. The work is additive, fails loudly everywhere, and is unusually well-tested (unit + live dev-mode spawn/health/tree-kill + a full server→sidecar round-trip).

The bottom line: this is ready to merge. I found no correctness or security blockers — the SHA-256 gate, service-identity health check, version handshake, process-group tree-kill, atexit reaping, and concurrency lock are all sound, and I verified the host's expected_api_version="2" correctly matches the sidecar's SCHEMA_VERSION="2.1" on a MAJOR comparison. Only a few low-priority polish items below.

One thing to confirm before merge: with the flag set, the /v1/email REST surface swaps entirely to the sidecar (the two backends are mutually exclusive in server.py) — the PR's "in-process mount kept" note refers to the default flag-unset path and the separate agent_type=email chat sessions, which are indeed untouched. Worth a sentence in the description so a reviewer doesn't read it as a contradiction.

🔍 Technical details

🟢 Minor

A new requests.Session is created per request (router.py:_get_proxy → manager.proxy() → EmailSidecarProxy(base_url) with no session). Every triage/draft/send/health/version call builds a fresh Session and TCP connection that is never pooled/reused. Low impact, but the manager could memoize a proxy (invalidated on restart, since the ephemeral port changes) to reuse the connection. Comment-only — caching across restarts needs care, so no blind suggestion here.

fetch_binary buffers the whole binary in memory (fetch.py:773 session.get(...) without stream=True, then data = resp.content, verify_sha256(data), tmp.write_bytes(data)). Frozen PyInstaller binaries are tens-to-hundreds of MB; this holds the full payload in RAM for the duration. Fine for a one-time fetch, but streaming-to-temp with an incremental hash would cap memory. Minor.

health_timeout default of 30s may be tight for a cold dev-mode boot (manager.py:107). Dev mode spawns uvicorn --reload which imports the heavy email wheel (RAG/Lemonade/connectors) before /health answers; the live tests bump this to 45–60s precisely because of that. User-mode frozen binaries boot faster, so this only bites dev mode on a cold machine, and it surfaces loudly via HealthTimeoutError with the log tail — so it's a tuning nit, not a bug.

Note (no action needed)

packaging/server.py:build_app() mounts connector_router (the /v1/email/connectors/* write routes) on the sidecar, which now also binds a localhost ephemeral port. The UI router correctly does not proxy those routes (explicit allowlist of 5 endpoints, verified by test_connector_routes_not_exposed and the server-wiring test), so they're unreachable through the backend. A local process could still hit them directly on the ephemeral port, but that's the pre-existing localhost trust model (build_app mounted them before this PR) — flagging only for awareness, not as a change-request.

Strengths

  • Fail-loud discipline is consistent with CLAUDE.md: no user→dev or sidecar→in-process fallback, placeholder/PENDING SHAs refuse loudly, IntegrityError has no "use it anyway" path, and every error names what failed + what to do + where to look (log tail surfaced on spawn failure).
  • Boundary translation is done right — SidecarHTTPError preserves the sidecar's own status code and actionable detail (e.g. 502 local LLM triage failed) instead of flattening to a generic error, and router._forward maps RequestException → loud 503.
  • Lifecycle hardening is thorough: service-identity check (not just status==ok) so a foreign process on the recycled ephemeral port can't be mistaken for the sidecar; process-group tree-kill for the --reload/PyInstaller child; atexit reaper for crash exits; RLock so concurrent first-use spawns exactly one sidecar; port-race retry that does not retry a genuine hang.
  • Test coverage is excellent — atomic-write-on-tamper, cache-hit-skips-network, placeholder-refuse, version MAJOR-mismatch, connection-error→503, the security allowlist, and a real live round-trip that skips cleanly without the wheel/Lemonade.
  • The packaging.server:app → server:app --app-dir correction is real and well-documented (avoids shadowing the PyPI packaging lib); docs, code comment, and manager test all agree.

@github-actions github-actions Bot added the dependencies Dependency updates label Jun 30, 2026
@itomek

itomek commented Jun 30, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the thorough review — agreed it's ready. Quick triage on the minor suggestions; all are non-blocking follow-ups rather than changes for this PR:

  • Per-request requests.Session — fair. Memoizing a proxy per running sidecar (invalidated on the ephemeral-port change at restart) is a clean follow-up; left out here to keep the restart / port-race logic simple. Noted as polish.
  • fetch_binary buffers in memory — only exercised in user mode, which is still gated on the frozen-binary publish ([packaging] Fully-automated R2 publish + thin npm package #1648). Streaming-to-temp with an incremental hash belongs with that work, when real SHAs land and the path is actually exercised.
  • health_timeout 30s for cold dev boot — health_timeout is already a constructor arg (the live tests pass 45–60s), so it's tunable per call. Left at 30s since it surfaces loudly (HealthTimeoutError + log tail) rather than silently; happy to bump the dev default if cold-boot timeouts show up in practice.
  • "in-process mount kept" wording — good catch; you read it right. Flag set → the sidecar serves /v1/email/* entirely (the two backends are mutually exclusive in server.py); flag unset → the in-process mount, and the separate agent_type=email chat sessions are untouched either way. (Also covered in the validation comment above.)

After merging main, registering the new gaia.ui.email_sidecar package in setup.py cleared a packaging-integrity failure — all unit / quality / build checks pass. The 3 remaining red checks (API / RAG-integration / Lemonade-embeddings on the stx runners) are a runner Lemonade-startup infra issue, not this PR: verified on a Strix Halo box with Lemonade up, those suites pass (embeddings 6/6, RAG 5/5) and the test_api failures are pre-existing on main. Tracked separately. The broader user-facing rollout — user-mode binary (#1648), the richer routes (#1778–#1781), mount removal — remains the parked #1896 epic.

@itomek-amd
itomek-amd merged commit 50c17de into amd:main Jun 30, 2026
52 of 61 checks passed
@itomek itomek mentioned this pull request Jun 30, 2026
8 of 9 tasks
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jul 2, 2026
…cess /v1/email) (amd#1910)

## Why this matters

Before this PR the Agent UI's email surface was split and the heavy
email agent ran inside the UI process: the `/v1/email/*` REST routes
were served by an **in-process mount of the email wheel by default**
(only by the sidecar when `GAIA_EMAIL_AGENT_MODE` was set), and the
in-app email chat agent (`agent_type=email`) loaded live Gmail/Outlook
backends, an action DB, and a memory store **into the UI backend**.
After this PR the out-of-process **sidecar is the sole, default backend
for both surfaces**. The core UI backend no longer imports the email
wheel — it stays lightweight, crash-isolated, and **dogfoods the exact
schema-2.1 product third-party integrators consume**.

This is the deferred cutover from epic amd#1767, on the foundations from
amd#1884 and the now-complete REST 2.1 contract from amd#1883 (design: amd#1882).

### What changed (three threads a reviewer should evaluate
independently)

- **Proxy ungated → full contract.** `EmailSidecarProxy` now forwards
the full schema-2.1 surface (prescan, search, archive/unarchive,
quarantine/unquarantine, confirm, batch triage, calendar
view/preview/create/respond) returning the sidecar's envelopes
unchanged. The UI router exposes the full contract, so removing the
in-process mount does **not** shrink the external `/v1/email` surface.
- **Sidecar is the sole + default `/v1/email` surface.** The in-process
`gaia_agent_email.api_routes` mount is removed from the UI server; unset
`GAIA_EMAIL_AGENT_MODE` now defaults to **user mode** (frozen binary,
lazy-fetched + SHA-verified). No in-process fallback — a
missing/unpublished binary fails loudly with a remedy. (The separate
`gaia api` / `openai_server` mount is intentionally out of scope.)
- **`agent_type=email` flipped to the sidecar.** New `EmailProxyAgent`
keeps the local-LLM tool loop in the UI backend, but every tool is a
thin HTTP call to the sidecar. `pre_scan_inbox` returns the
**identical** `email_pre_scan` envelope so the triage card renders
unchanged. Its tool surface is the subset the REST contract serves today
(inbox pre-scan, search, calendar view, archive + undo); the unmapped
in-process tools
(labels/stars/move/trash/delete/summarize/profile/preferences/forward/send)
are not exposed in chat until their REST routes land — the agent product
still implements them, they're just not reachable over the contract yet.

## Test plan

- [x] `python -m pytest tests/unit/test_email_sidecar_*.py` — 91 pass
(proxy, router, server-wiring, manager, fetch, platform, devmode-app,
**new** proxy-agent).
- [x] `python util/lint.py --black --isort --flake8` — all pass.
- [x] Chat-path regression: `pytest
tests/unit/test_session_mail_provider.py tests/unit/test_agents_split.py
tests/unit/test_chat_preflight.py tests/unit/chat/ui/test_server.py` —
141 pass.
- [x] **End-to-end card property (no Gmail):** the proxy agent's real
`pre_scan_inbox` output, fed through the real `SSEOutputHandler`,
injects an `email_pre_scan` render payload (test
`test_pre_scan_envelope_triggers_real_sse_card_injection`).
- [x] **Live dev-mode round-trip:** spawned the dev sidecar
(`apiVersion=2.1 agentVersion=0.3.0`), drove the proxy agent's real
`pre_scan_inbox`/`search_messages` tools against live `/prescan` and
`/search`; with no mailbox connected they fail loudly with the sidecar's
verbatim "No mailbox connected…" detail (full chain: proxy agent →
shared manager → sidecar → REST → fail-loud passthrough). Clean
tree-kill on shutdown.
- [x] `create_app()` with `GAIA_EMAIL_AGENT_MODE` unset → manager mode
`user`, full contract routes mounted, no in-process mount.

To exercise locally with a connected Gmail:
```bash
uv pip install -e hub/agents/python/email
GAIA_EMAIL_AGENT_MODE=dev gaia chat --ui   # email session → "what's in my inbox" → pre-scan card via the sidecar
```

### Notes for the reviewer
- **Eval:** no `gaia eval agent` run — the change touches neither the
in-core ChatAgent prompts nor the wheel's `EmailTriageAgent`; the eval
harness targets the wheel agent (unchanged), and there is no eval path
for the new `EmailProxyAgent`. Its behavior is covered by the
integration + live tests above.
- **Reduced chat tool surface** is a deliberate, maintainer-approved
product decision (sidecar-mapped tools only) — backwards compat for
*other* Agent-UI agents (chat/code/browser/…) is untouched.
- **Follow-up:** the registry gate still requires the email wheel for
the `email` id to resolve, so a no-wheel install can use the REST
surface but not the chat agent. Decoupling that (registering proxy-agent
metadata without the wheel) is a separate change.
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Aug 17, 2026
Release notes had grown into long blocks of prose with a marketing-toned
paragraph on top. They now generate as short bullets grouped by section,
with a word cap on the narrative part. Nothing informational is lost —
every PR link, contributor credit, and changelog entry is preserved; the
prose around them is cut.

Two generators write `docs/releases/<tag>.mdx` and they had drifted
apart. The `gaia-release` skill told the model GAIA's notes "read dry"
and to make them "engaging"; the `release-notes` job in `claude.yml`
asked for "comprehensive" notes with an `## Overview` paragraph and
emoji headings. Fixing one alone would have been overwritten by the
other on the next tag, so both now share one spec.

Closes amd#2961

## What it looks like now

Regenerated from the last two releases — same facts, same PR numbers,
new template. Narrative words (the capped part, excluding
bug-fix/contributor/changelog lists):

| Release | Published | Regenerated | Cap |
|---|---|---|---|
| v0.22.0 (minor) | 1705 | **538** | 600 |
| v0.23.0 (minor) | 1119 | **280** | 600 |

<details>
<summary>Example 1 — v0.23.0 regenerated</summary>

```markdown
---
title: "v0.23.0"
description: "Install and run agents from the terminal, add capabilities as skills, and connect a Microsoft account without a secret."
---

# GAIA v0.23.0 Release Notes

Agents are now installable from the terminal, and the confirmation gate that pauses an agent before a consequential action works everywhere, not just in the Agent UI.

## Breaking Changes

- **`GAIA_MICROSOFT_TENANT` is gone** — the Microsoft connector split into Personal and Work/School, each with its own tenant. Drop the variable and pick the matching connector. (PR [amd#2729](amd#2729))

## What's New

- **Install and run agents from the terminal** — `gaia hub list`, `gaia hub install <agent> --trust`, `gaia hub uninstall <agent>`. `--trust` is required for an unverified agent. (PRs [amd#2484](amd#2484), [amd#2530](amd#2530), [amd#2708](amd#2708))
- **Every agent asks before it acts** — the confirmation gate for sending mail, writing files, and running commands now fires from the terminal, the local API, and MCP tool calls, not only the Agent UI. Set `GAIA_AUTO_APPROVE_TOOLS=1` to opt out. (PRs [amd#2475](amd#2475), [amd#2544](amd#2544), [amd#2846](amd#2846), [amd#2854](amd#2854))
- **Safer by default** — the MCP bridge binds to localhost and enforces `--auth-token`; the local API refuses credentialed cross-origin requests from non-allow-listed sites; MCP servers launch without a shell; agents cannot write to `~/.gaia` or pass crafted SQL to the database agent. (PRs [amd#2246](amd#2246), [amd#2238](amd#2238), [amd#2344](amd#2344), [amd#2844](amd#2844), [amd#2847](amd#2847), [amd#2860](amd#2860))
- **Add capabilities as skills** — `gaia skill create|import|list|info` gives an agent a new capability from a folder and a manifest. Skills are signed with trust tiers, audited before publish, and opt-in. (PRs [amd#2669](amd#2669), [amd#2692](amd#2692), [amd#2702](amd#2702), [amd#2693](amd#2693))
- **Connect a Microsoft account without a secret** — Personal and Work/School are separate connectors with device-code sign-in. (PRs [amd#2718](amd#2718), [amd#2364](amd#2364))
- **Lemonade Server 11.5.0.**

## Bug Fixes

- **Triage paginates large inboxes and reports truncation** (PR [amd#2646](amd#2646)) — mail past a hidden limit is no longer dropped without saying so.
- **Thread messages come back sorted and numbered** (PR [amd#2570](amd#2570)) — "reply to 3" hits the message shown at position 3.
- **The inbox pre-scan reports uncertainty as uncertainty** (PR [amd#2587](amd#2587)).
- **An email conversation survives its turns** (PR [amd#2837](amd#2837)) — a follow-up keeps session context.
- **A bare reconnect keeps existing grants** (PR [amd#2733](amd#2733)).
- **Restore from Trash anytime** (PR [amd#2542](amd#2542)) — no time window on undo.
- **Sender priority no longer overrides content classification** (PR [amd#2774](amd#2774)).
- **The agent survives an OpenMP double-init** (PR [amd#2508](amd#2508)).
- **Large tool results truncate to valid JSON** (PR [amd#2645](amd#2645)).
- **A missing model surfaces as a real 404** (PR [amd#2245](amd#2245)).
- **GPU is detected on all platforms and `default_device` is honoured** (PR [amd#2244](amd#2244)).
- **A sidecar that is alive but not serving is detected** (PR [amd#2707](amd#2707)).
- **The model-slot lease is held across inference** (PR [amd#2394](amd#2394)) — a second agent can't evict the model mid-generation.
- **A browser that never launched is surfaced** (PR [amd#2507](amd#2507)).
- **Stop aborts in-flight streaming** (PR [amd#2166](amd#2166)).

## Known Issues

- **The email agent is beta and CLI-first** — treat its output as a draft to review.
- **A full inbox triage can time out on larger mailboxes.**
- **Email autonomy is experimental** and not wired up in the packaged sidecar.

## Contributors

- [@handle](https://github.com/handle) — <contribution> (PR [#NNN](https://github.com/amd/gaia/pull/NNN))
  <!-- generated from the commit log; v0.23.0's list is unchanged from the published notes -->


## Full Changelog

**N commits** since v0.22.0:

- `<sha>` — <subject>

Full Changelog: [v0.22.0...v0.23.0](amd/gaia@v0.22.0...v0.23.0)
```
</details>

<details>
<summary>Example 2 — v0.22.0 regenerated (the largest recent
release)</summary>

```markdown
---
title: "v0.22.0"
description: "The email agent tracks follow-ups and action items, drafts in your voice, and runs as its own process. Plus a cron scheduler and Word document support in RAG."
---

# GAIA v0.22.0 Release Notes

A large release built around the email agent, which now tracks what you're waiting on instead of forgetting it after triage.

## Breaking Changes

- **Triage returns a reply scaffold, not an empty draft** — `POST /v1/email/triage` and `/triage/batch` now return a `DraftScaffold` without `body`. Code reading `result.draft.body` gets a missing key instead of `""`; use `POST /v1/email/draft` for composed prose. (PR [amd#1984](amd#1984))
- **RoutingAgent and DocumentQAAgent moved to standalone packages** — install `gaia-agent-routing` and `gaia-agent-docqa`. The old imports fail; there is no deprecation shim. (PR [amd#1455](amd#1455))

## What's New

- **An inbox agent that keeps track** — `gaia email` scans Sent folders across every connected mailbox and flags threads still waiting on a reply past a window you set (default 3 days). Detection only; it never nudges anyone for you. (PRs [amd#1922](amd#1922), [amd#1917](amd#1917), [amd#1919](amd#1919), [amd#1918](amd#1918))
- **Drafts in your own voice** — the agent derives greeting, sign-off, length, and formality from your Sent history and composes against that. Only the derived characteristics are stored, never old mail content. (PR [amd#1925](amd#1925))
- **Attachments work end to end** — triage surfaces each attachment's name, type, and size, and drafting and sending accept real attachments as Gmail multipart MIME or Outlook Graph attachments. (PRs [amd#1921](amd#1921), [amd#1883](amd#1883))
- **Email runs as its own process in the Agent UI (beta)** — install it from the Agent Hub panel and the UI talks to it over HTTP, instead of loading the email stack into the UI process. (PRs [amd#1884](amd#1884), [amd#1910](amd#1910), [amd#2100](amd#2100), [amd#2101](amd#2101), [amd#2105](amd#2105))
- **Run prompts on a cron from the terminal** — `gaia schedule add --name digest --cron "0 9 * * *" --prompt "summarize my inbox" --sink stdout`, then `gaia schedule daemon`. Schedules live in a hand-editable `~/.gaia/schedules.toml`; sinks are `stdout`, `file:<path>`, `notification`, or `telegram`. (PR [amd#1371](amd#1371))
- **Agents learn from work they repeat** — after enough successes on the same shape of goal, an agent distills the tool sequence into a reusable procedure and recalls it next time. Runs inside the existing memory pass; nothing to install. (PR [amd#1794](amd#1794))
- **Pick your model once** — `gaia config set default_model <id>` persists across `gaia chat`, `gaia llm`, and `gaia prompt`. An explicit `--model` still wins for a one-off. (PR [amd#1863](amd#1863))
- **RAG reads Word documents** — `.docx` files index like PDF and PPTX, including table cells, nested tables, content controls, hyperlinks, and textboxes, so filled-in form values get indexed. (PR [amd#1866](amd#1866))
- **A new default embedder** — the previous default cannot be loaded by current llama.cpp builds, which broke indexing, code search, and memory embedding on an up-to-date Lemonade. The default is now EmbeddingGemma 300M at the same 768 dimensions. (PRs [amd#1952](amd#1952), [amd#1761](amd#1761), [amd#1748](amd#1748))
- **The Agent Hub shows what an agent is worth** — an agent's page now carries its eval scorecard with a score badge and a code-derived capability matrix. (PRs [amd#1985](amd#1985), [amd#2020](amd#2020), [amd#2066](amd#2066))
- **Lemonade Server 10.10.0** — adds an audio-generation endpoint, lets Windows reuse system ROCm, and inhibits suspend during inference. Two upstream breaking changes are Linux-specific. (PR [amd#1969](amd#1969))

## Bug Fixes

- **`gaia init` said a working Lemonade wasn't installed** (PR [amd#1940](amd#1940)) — modern Lemonade (10.7+) dropped the `lemonade-server` CLI that GAIA probed for.
- **Installing the email agent from the Hub failed on every platform** (PR [amd#2086](amd#2086)).
- **Bulk triage broke on any real inbox** (PR [amd#2088](amd#2088)) — 60 emails overflowed the 16K context window; the result envelope is now condensed.
- **RAG silently indexed nothing** (PR [amd#1979](amd#1979)) — a failed `sentence-transformers` import made every indexing call a no-op.
- **Email bodies were truncated at 4,000 characters with no override** (PR [amd#2036](amd#2036)) — MFA codes and precise replies lost content past the cutoff.
- **Long threads overflowed the model's context** (PR [amd#2076](amd#2076)).
- **A disabled device was treated as usable** (PR [amd#2081](amd#2081)) — a device reporting `available: false`, such as an unpowered NPU, was misread as ready.
- **A newly connected mailbox was skipped** (PR [amd#1808](amd#1808)) — mailboxes connected mid-session were not picked up.
- **JSON with a `}` inside a string was dropped** (PR [amd#1824](amd#1824)).
- **Outlook users were told to reconnect Google** (PR [amd#1757](amd#1757)) — `AGENT_NOT_GRANTED` named the wrong provider.
- **The Agent UI hard-crashed on a recoverable GPU crash** (PR [amd#1799](amd#1799)) — it now falls back to software rendering.
- **A user-edited memory could be silently downgraded and then wiped** (PR [amd#1958](amd#1958)).
- **The builder agent ignored an agent name you had already given** (PR [amd#1981](amd#1981)).
- **The landing and hub pages scrolled sideways on phones** (PR [amd#1959](amd#1959)).

## Known Issues

- **Inbox pre-scan needs a single mailbox for now** — with both Gmail and Outlook connected, an Agent UI pre-scan errors. Disconnect one in Settings → Connectors; triage itself still spans every mailbox. ([amd#2127](amd#2127))
- **Spam detection under-flags over the REST API** — `/v1/email/triage` uses a narrow sender check rather than the model's reading. The agent's own inbox scanning is unaffected. ([amd#2124](amd#2124))
- **The email agent is beta** — treat its output as a draft to review. It never sends without your confirmation.

## Contributors

- [@alexey-tyurin](https://github.com/alexey-tyurin) — skill auto-synthesis / procedural memory (PR [amd#1794](amd#1794))
- [@TravisHaa](https://github.com/TravisHaa) — the `gaia schedule` CLI and cron-based dispatch (PR [amd#1371](amd#1371))
- [@Rohithmatham12](https://github.com/Rohithmatham12) — refresh resolved email backends before multi-mailbox triage (PR [amd#1808](amd#1808))
- [@Osamaali313](https://github.com/Osamaali313) — fix `extract_json_from_text` dropping JSON containing `}` (PR [amd#1824](amd#1824))
- [@eeee2345](https://github.com/eeee2345) — offline model-endpoint guard-proxy integration guide (PR [amd#1809](amd#1809))
- [@somo9909](https://github.com/somo9909) — prerequisites section for the memory guide (PR [amd#1665](amd#1665))

## Full Changelog

**N commits** since v0.21.2:

- `<sha>` — <subject>

Full Changelog: [v0.21.2...v0.22.0](amd/gaia@v0.21.2...v0.22.0)
```
</details>

<details>
<summary>What changed in the templates</summary>

- The narrative overview paragraph and the `**Why upgrade:**` block are
gone — the latter restated `What's New` verbatim.
- `What's New` entries are bullets, not `###` prose blocks.
- Tone guidance is no longer restated in the skill; it points at
CLAUDE.md § How You Communicate.
- The skill's embedded example now shows the old prose block as **bad**
and the bullet form as **good**.
- Emoji removed from the CI prompt (it asked for 🚀 / 🎯 / 🐛 headings
against the skill's own no-emoji rule).
- Both generators now emit the same sections in the same order, so the
file's shape no longer depends on which one ran.
- The cap excludes `Bug Fixes` / `Known Issues` / `Contributors` / `Full
Changelog`. Those are reference lists sized by how many fixes shipped —
capping them would hide work. This was caught by regenerating v0.22.0,
which overflowed a whole-file cap purely on its 14 bug-fix bullets.

**Follow-up, not in this PR:** the cap lives in prompt text, so it is
advisory. Making it a hard check in `util/validate_release_notes.py`
would enforce it in CI.
</details>

## Test plan

- [ ] `python util/validate_release_notes.py <regenerated sample> --tag
v0.23.0` exits 0 — passes unmodified, no validator changes in this PR
- [ ] `awk '/^## (Bug Fixes|Known Issues|Contributors|Full
Changelog)/{exit} {print}' <file> | wc -w` is under 350 (patch) / 600
(minor-major)
- [ ] `.github/workflows/claude.yml` parses as valid YAML and its
release-notes prompt contains no emoji
- [ ] `.claude/skills/gaia-release/SKILL.md` is under 500 lines (498)
- [ ] Both generators list the same sections in the same order
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::email Email agent changes dependencies Dependency updates documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants