Skip to content

feat: add bounded Hermes Gmail mailbox broker - #8

Merged
404Dealer merged 6 commits into
masterfrom
feat/hermes-mailbox-broker
Jul 11, 2026
Merged

404Dealer merged 6 commits into
masterfrom
feat/hermes-mailbox-broker

Conversation

@404Dealer

@404Dealer 404Dealer commented Jul 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add the credential-isolated Unix-socket Gmail Inbox broker and fixed mailbox CLI
  • add exact UIDVALIDITY/UID references, bounded list/read/verified mark-read operations
  • add Telegram-approved native IMAP MOVE to Gmail Trash with no delete/EXPUNGE fallback
  • harden broker concurrency, response limits, proposal replay, and production installation

Verification

Deployment

This PR is the first layer of the approved stack: broker → unsubscribe (#6) → multi-account profiles (#7).

Summary by CodeRabbit

  • New Features
    • Added mailbox access through the agent-gate-mailbox command.
    • Supports listing, reading, and marking Gmail messages as read.
    • Added approval-based proposals for moving selected messages to Trash.
    • Added previews, status reporting, and partial-operation handling for mailbox actions.
  • Safety
    • Enforces exact message references, bounded operations, and safe MOVE-only trash behavior.
    • Treats email content as untrusted and prevents direct sending or permanent deletion.
  • Documentation
    • Updated mailbox workflow guidance and installation instructions.

Copilot AI review requested due to automatic review settings July 11, 2026 04:05

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@404Dealer, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 50 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b5f6f67f-fd5a-42fb-aa98-69091bb1d069

📥 Commits

Reviewing files that changed from the base of the PR and between 6646fa3 and aeab42a.

📒 Files selected for processing (2)
  • src/mailbox-broker/gmail-inbox.ts
  • src/watcher.ts
📝 Walkthrough

Walkthrough

Adds a Gmail mailbox broker with Unix-socket access, mailbox CLI commands, canonical message references, approval-gated trash proposals, Gmail MOVE execution, pending-draft replay, and production installation/systemd configuration.

Changes

Mailbox broker and approval workflow

Layer / File(s) Summary
Mailbox contracts and draft types
package.json, src/mailbox-broker/protocol.ts, src/mailbox-broker/reference.ts, src/schema.ts
Defines canonical inbox references, validated mailbox requests and responses, and the mailbox-trash draft type.
Gmail inbox and trash operations
src/mailbox-broker/gmail-inbox.ts, src/mailbox-broker/gmail-trash.ts, tests/mailbox-trash-safety.test.ts
Adds bounded Gmail listing, reading, read marking, and MOVE-only trash preparation/execution with UID and UIDPLUS verification.
Broker transport, proposals, and CLI
src/mailbox-broker/server.ts, src/mailbox-broker/trash-proposal.ts, src/mailbox-client.ts, src/mailbox-broker/client.ts
Adds the Unix-socket broker, atomic trash proposal persistence, and the agent-gate-mailbox command-line client.
Approval execution and startup lifecycle
src/bot.ts, src/executor.ts, src/watcher.ts, src/index.ts, tests/mailbox-trash-safety.test.ts
Connects mailbox-trash snapshots to Telegram approvals, execution results, audit records, pending replay, and broker lifecycle management.
Production deployment and operator guidance
scripts/install-production.sh, skill/SKILL.md
Installs the mailbox client, configures groups and systemd settings, handles rollback state, and documents mailbox workflows and safety rules.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Agent as Hermes Agent
  participant CLI as agent-gate-mailbox
  participant Broker as MailboxBrokerServer
  participant Gmail as GmailMailboxTrashService
  participant Telegram as Telegram Approval Flow
  Agent->>CLI: Submit propose-trash request
  CLI->>Broker: Send validated references and context
  Broker->>Telegram: Persist pending mailbox-trash draft
  Telegram->>Gmail: Prepare snapshot for approval
  Gmail-->>Telegram: Return message preview snapshot
  Telegram-->>Agent: Present approval preview
  Agent->>Telegram: Approve proposal
  Telegram->>Gmail: Execute approved MOVE
  Gmail-->>Telegram: Return moved or move-partial result
  Telegram-->>Agent: Send execution notification
Loading

Possibly related PRs

  • 404Dealer/agent-gate#2: Shares the Telegram approval token and callback flow extended here for mailbox-trash drafts.
  • 404Dealer/agent-gate#4: Shares the executor and bot execution-result flow extended here with mailbox-trash outcomes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately reflects the main change: adding a bounded Hermes Gmail mailbox broker.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/hermes-mailbox-broker

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/mailbox-client.ts (2)

7-8: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated socket path and response size constants risk silent breakage.

SOCKET_PATH and MAX_RESPONSE_BYTES are hardcoded here but also defined in src/mailbox-broker/protocol.ts as MAILBOX_SOCKET_PATH and MAX_RESPONSE_BYTES. If the path changes in one location but not the other, the CLI will silently fail to connect.

Consider importing these from ./mailbox-broker/protocol.js to maintain a single source of truth.

♻️ Suggested fix
-import { createConnection } from 'node:net';
+import { createConnection } from 'node:net';
+import { MAILBOX_SOCKET_PATH, MAX_RESPONSE_BYTES } from './mailbox-broker/protocol.js';

Then replace usages:

-const SOCKET_PATH = '/run/agent-gate-mailbox/broker.sock';
-const MAX_RESPONSE_BYTES = 1024 * 1024;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/mailbox-client.ts` around lines 7 - 8, Remove the local SOCKET_PATH and
MAX_RESPONSE_BYTES declarations in mailbox-client.ts, import MAILBOX_SOCKET_PATH
and MAX_RESPONSE_BYTES from mailbox-broker/protocol.js, and update all
SOCKET_PATH references to MAILBOX_SOCKET_PATH.

34-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reference validation logic duplicates decodeInboxReference — divergence risk.

refIdentity reimplements the canonical reference validation from src/mailbox-broker/reference.ts. While currently equivalent, any future change to the reference format (e.g., new fields, different encoding) would need to be updated in both places. The CLI could accept refs the broker rejects or vice versa, producing confusing user errors.

Consider importing and reusing decodeInboxReference from ./mailbox-broker/reference.js, wrapping it to return null on error instead of throwing.

♻️ Suggested fix
+import { decodeInboxReference } from './mailbox-broker/reference.js';
+
 const refIdentity = (value: string): { uidValidity: string; uid: number } | null => {
-  if (!/^[A-Za-z0-9_-]{8,256}$/.test(value)) return null;
   try {
-    const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as Record<string, unknown>;
-    const keys = Object.keys(parsed).sort().join(',');
-    if (keys !== 'folder,uid,uidValidity,v' || parsed.v !== 1 || parsed.folder !== 'inbox' ||
-        typeof parsed.uidValidity !== 'string' || !/^[1-9][0-9]*$/.test(parsed.uidValidity) ||
-        typeof parsed.uid !== 'number' || !Number.isSafeInteger(parsed.uid) || parsed.uid < 1) return null;
-    const canonical = Buffer.from(JSON.stringify({
-      v: 1,
-      folder: 'inbox',
-      uidValidity: parsed.uidValidity,
-      uid: parsed.uid
-    }), 'utf8').toString('base64url');
-    return canonical === value ? { uidValidity: parsed.uidValidity, uid: parsed.uid } : null;
+    const ref = decodeInboxReference(value);
+    return { uidValidity: ref.uidValidity, uid: ref.uid };
   } catch {
     return null;
   }
 };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/mailbox-client.ts` around lines 34 - 52, Replace the duplicated
validation in refIdentity with decodeInboxReference imported from
./mailbox-broker/reference.js. Call the decoder with the provided value and
return its uidValidity/uid identity, catching decoder errors and returning null
so the existing caller behavior is preserved.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/mailbox-broker/gmail-inbox.ts`:
- Around line 202-229: Update the markRead method’s Promise return type to
include outcome as 'applied' | 'partial', matching the object returned by the
method; retain the existing outcome field and requested/verified properties.

In `@src/watcher.ts`:
- Around line 61-72: Update the startup error handling around DraftWatcher’s
ready/error promise so chokidar errors cannot synchronously throw through an
unhandled error event. Guard any this.emit('error', error) forwarding with an
appropriate listener check, or defer forwarding until after the watcher is
ready, while ensuring onStartupError still rejects start() and removes the
opposite listener.

---

Nitpick comments:
In `@src/mailbox-client.ts`:
- Around line 7-8: Remove the local SOCKET_PATH and MAX_RESPONSE_BYTES
declarations in mailbox-client.ts, import MAILBOX_SOCKET_PATH and
MAX_RESPONSE_BYTES from mailbox-broker/protocol.js, and update all SOCKET_PATH
references to MAILBOX_SOCKET_PATH.
- Around line 34-52: Replace the duplicated validation in refIdentity with
decodeInboxReference imported from ./mailbox-broker/reference.js. Call the
decoder with the provided value and return its uidValidity/uid identity,
catching decoder errors and returning null so the existing caller behavior is
preserved.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c4bb8de0-30b8-422f-a68c-bbd5b364b43b

📥 Commits

Reviewing files that changed from the base of the PR and between ab263a6 and 6646fa3.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (17)
  • package.json
  • scripts/install-production.sh
  • skill/SKILL.md
  • src/bot.ts
  • src/executor.ts
  • src/index.ts
  • src/mailbox-broker/client.ts
  • src/mailbox-broker/gmail-inbox.ts
  • src/mailbox-broker/gmail-trash.ts
  • src/mailbox-broker/protocol.ts
  • src/mailbox-broker/reference.ts
  • src/mailbox-broker/server.ts
  • src/mailbox-broker/trash-proposal.ts
  • src/mailbox-client.ts
  • src/schema.ts
  • src/watcher.ts
  • tests/mailbox-trash-safety.test.ts

Comment thread src/mailbox-broker/gmail-inbox.ts Resolved
Comment thread src/watcher.ts Resolved
@404Dealer
404Dealer merged commit 82d6384 into master Jul 11, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants