Samson Sunny built a development agent that treats an Outlook inbox as a task queue. You send an email with a feature request. The agent polls the inbox, generates code using opencode, runs the Xcode build, pushes to main, and replies with the commit hash and build status. No dashboard, no webhook server, no custom UI. Just email threading and launchd polling.
This is not a toy. It is a working pattern for asynchronous agent execution that sidesteps traditional queue infrastructure by repurposing email as trigger, state store, and audit log. The implementation exposes real trade-offs: polling latency versus webhook complexity, email threading as idempotency key, and the security boundary of a single-user inbox.
Architecture: Email as Orchestration Primitive
The agent runs as a launchd job on macOS, polling every 60 seconds. Each cycle:
- Fetch unread messages via Microsoft Graph API
- Parse subject line for task intent (e.g.,
[dev] Fix Today badge count) - Verify clean checkout (refuses to run on dirty working tree)
- Invoke opencode to generate code changes
- Run Xcode build to verify compilation
- Commit and push to main branch
- Reply to original email with commit hash, build status, and agent summary
The inbox becomes a durable queue. Each email is a work item. The reply thread is the execution trace. Marking a message as read is the acknowledgment.
Component Breakdown
| Component | Role | Failure Mode |
|---|---|---|
| Microsoft Graph API | Inbox polling, reply threading | Rate limit (429), token expiry, network partition |
| launchd | Periodic execution scheduler | Missed interval if system sleeps, no retry on crash |
| opencode | Code generation from natural language | Hallucinated imports, syntax errors, incomplete logic |
| Xcode build | Verification gate | Compile error blocks push, no rollback on runtime failure |
| Git push | State persistence | Merge conflict if concurrent push, no distributed lock |
Polling vs. Webhooks: Latency and Recovery Trade-Offs
The agent uses 60-second polling instead of Microsoft Graph webhooks. This is a deliberate choice.
Polling advantages:
- No public endpoint to secure
- No TLS certificate management
- No webhook verification handshake
- Simpler failure recovery (just wait for next poll)
Polling costs:
- 60-second minimum latency
- Wasted API calls when inbox is empty
- No sub-minute response time
For a single-user development agent, the latency is acceptable. The developer sends a request, switches context, and checks email later. The 60-second delay is less disruptive than managing a webhook server that needs to stay reachable.
Webhook-based systems fail differently. If the webhook endpoint is down when the email arrives, you need a retry queue. If the endpoint is slow, you need timeout handling. If the endpoint is compromised, you need request signing. Polling trades latency for operational simplicity.
State Management: Email Threading as Idempotency Key
Each email thread is a single execution context. The agent replies to the original message, creating a conversation thread that captures:
- Initial request (subject and body)
- Execution timestamp
- Commit hash
- Build result
- Agent-generated summary
If the agent crashes mid-execution, the next poll cycle sees the same unread message and retries. This is safe because the agent checks for a clean working tree before starting. If the previous run partially completed and left uncommitted changes, the agent refuses to proceed.
The email thread becomes the audit log. You can search for [dev] Fix Today badge count and see every attempt, every failure, and the final successful commit. No separate logging infrastructure required.
Error Handling: What Happens When the Build Fails
If the Xcode build fails, the agent:
- Does not push to main
- Replies to the email with build errors
- Marks the message as read (to avoid infinite retry)
- Leaves the working tree dirty (for manual inspection)
This is a human-in-the-loop design. The agent does not attempt automatic remediation. It surfaces the failure and waits for the developer to intervene.
The alternative (automatic retry with modified prompts) creates a different risk: the agent might push broken code after exhausting retries, or it might loop indefinitely on a task that requires human judgment.
Security Boundary: Single-User Inbox as Access Control
The agent trusts every email in the inbox. There is no authentication beyond “this message arrived in my Outlook account.” This works because:
- The inbox is single-user
- Microsoft handles authentication (OAuth 2.0)
- The agent runs on a developer workstation, not a shared server
If you wanted multi-user support, you would need:
- Per-sender authorization (which users can trigger builds?)
- Rate limiting (how many requests per user per hour?)
- Approval workflow (should some requests require manual confirmation?)
The single-user model avoids these problems. The inbox is already a trusted channel. If someone compromises your email, they can trigger arbitrary code execution, but they already have access to your email, calendar, and contacts. The agent does not expand the attack surface.
Code: Polling Loop and Reply Threading
Here is the core polling logic (simplified from the original Swift implementation):
func pollInbox() async throws {
let messages = try await graphClient.fetchUnreadMessages(folder: "Inbox")
for message in messages where message.subject.hasPrefix("[dev]") {
do {
// Verify clean checkout
guard try gitStatus().isEmpty else {
try await reply(to: message, body: "Error: Dirty working tree")
try await markAsRead(message)
continue
}
// Generate code
let request = message.body
let changes = try await opencode.generate(prompt: request)
// Build and verify
try await applyChanges(changes)
let buildResult = try await xcodeBuild()
guard buildResult.success else {
try await reply(to: message, body: "Build failed:\n\(buildResult.errors)")
try await markAsRead(message)
continue
}
// Commit and push
let commitHash = try await gitCommit(message: message.subject)
try await gitPush()
// Reply with success
let summary = """
Request: \(message.subject)
Commit: \(commitHash)
Build: passed
"""
try await reply(to: message, body: summary)
try await markAsRead(message)
} catch {
try await reply(to: message, body: "Error: \(error.localizedDescription)")
try await markAsRead(message)
}
}
}
The reply threading uses Microsoft Graph’s createReply endpoint, which preserves the conversation ID. This ensures all execution history stays attached to the original request.
Observability: What You See and What You Miss
The email thread gives you:
- Request timestamp
- Completion timestamp
- Commit hash (linkable to GitHub)
- Build status
- Agent-generated summary
You do not get:
- Real-time progress updates
- Intermediate build logs
- Resource usage (CPU, memory, disk)
- Retry attempts (if the agent crashes before replying)
For a single-user agent, this is enough. You can click the commit hash to see the diff. You can check the build logs in Xcode. You can search your inbox for failed builds.
For a team agent, you would want structured logging (JSON lines to a file or log aggregator), metrics (execution time, success rate), and alerting (Slack notification on repeated failures).
When Email-as-Queue Works
This pattern fits when:
- Single user or small team. No need for multi-tenancy or complex authorization.
- Asynchronous work. You do not need sub-second response times.
- Human oversight. You want to review results before they go live.
- Audit trail matters. Email threading gives you provenance for free.
- No infrastructure budget. You already have email. You do not want to run a queue service.
It does not fit when:
- High throughput. Polling every 60 seconds limits you to one task per minute per inbox.
- Distributed execution. Email does not give you distributed locking or leader election.
- Strict ordering. Email delivery order is not guaranteed.
- Real-time feedback. You need progress bars or streaming logs.
Technical Verdict
Email-as-queue is a legitimate orchestration primitive for low-volume, single-user agent workflows. It gives you durability, audit trails, and human-in-the-loop observability without running a queue service. The polling model trades latency for operational simplicity, which is the right trade-off when you are building for yourself.
The pattern breaks down at scale. If you need multi-user support, you will add authorization logic. If you need high throughput, you will switch to webhooks or a real queue. If you need distributed execution, you will need a coordination service.
But for a solo developer who wants an agent that takes instructions from email and replies with commit hashes, this is a clean, maintainable design. The inbox is already a trusted channel. The email thread is already an audit log. The reply is already a notification. You are just connecting the pieces.
Use this when you want agent automation without agent infrastructure. Avoid it when you need real-time feedback, high throughput, or multi-user coordination.