MDX Limo
Troy — Autonomous Entrepreneur Agent

Troy — Autonomous Entrepreneur Agent

Mission: Troy is an AI agent whose sole purpose is to figure out how to make money on the internet and maximize profit — operating as a solo entrepreneur who builds, launches, markets, and iterates on products, with hard guardrails and human oversight on money and irreversible actions.

Design stance: Not overbuilt. One agent, one loop, a small set of well-designed tools, and platform-enforced limits. Anthropic's canonical guidance is to start with the simplest thing that works and add complexity only when evals show it failing (Building Effective Agents). Anthropic's Project Vend — the closest real experiment to Troy (Claude running an actual shop) — showed that procedural scaffolding and hard external constraints matter more than raw model capability: phase 1 lost money (hallucinated payment accounts, gave discounts to everyone, sold below cost); phase 2 became profitable after adding a CRM, cost-visible ledger, payment-link tooling, and forced checklists (Project Vend 1, Project Vend 2). Troy's architecture is built around those lessons.


1. Architecture Overview

1┌─────────────────────────────────────────┐ 2 Wake signals │ TROY (Cloudflare Agents SDK / DO) │ 3 ─ schedule/cron ───▶ │ • Heartbeat loop (schedule/alarms) │ 4 ─ email webhook ───▶ │ • State + SQLite memory (1 GB) │ 5 ─ Stripe webhook ──▶ │ • Ledger, journal, task queue │ 6 ─ human (chat/WS) ─▶ │ • MCP client → external tool servers │ 7 └───────┬─────────────┬───────────────────┘ 8 │ │ 9 ┌──────────────┴──┐ ┌──────┴───────────────────┐ 10 │ Guardrail layer │ │ Cloudflare Workflows │ 11 │ (spend caps, │ │ (multi-step jobs, human │ 12 │ approval tiers,│ │ approval gates) │ 13 │ kill switch) │ └──────┬───────────────────┘ 14 └─────────────────┘ │ 15 ┌──────────┬──────────┬───────────┬───┴──────┬──────────┬─────────┬─────────┐ 16 ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ 17 GitHub Vercel Supabase Stripe Postiz AgentMail Browser/ fal.ai 18 (MCP) (REST + (MCP) (restricted (REST+MCP) (API+MCP) Search (media, 19 domains) keys) on VPS (CF) API key)

Runtime: Cloudflare Agents SDK (developers.cloudflare.com/agents). Troy is a single Agent class backed by a Durable Object: globally unique identity, single-threaded execution (thread-safe state), embedded SQLite (up to 1 GB), WebSocket + HTTP + email entry points, and — the economic core — hibernation: Troy costs ~nothing while dormant and wakes on schedules, webhooks, email, or human contact (Agents API, long-running agents, DO pricing).

Key platform pieces Troy uses:

CapabilityCloudflare primitiveWhy
Heartbeat / wake-upsthis.schedule() cron + scheduleEvery() (DO alarms)Self-waking with no inbound traffic (scheduling)
Working memorythis.state (small) + this.sql SQLite (queryable)Survives hibernation/restarts (state)
Crash-safe in-agent workFibers (runFiber/startFiber + ctx.stash)Checkpointed execution with recovery (durable execution)
Long multi-step jobs + approvalsWorkflows (step.do, step.sleep, waitForApproval())Durable pipelines that wait indefinitely for human sign-off without keeping Troy active (Workflows, HITL)
External toolsBuilt-in MCP client: this.addMcpServer(name, url, {transport}) — OAuth handled automatically, tokens persisted in SQLite, getAITools() bridges into the AI SDKOne standard connection for GitHub/Supabase/Stripe/Postiz/AgentMail (MCP client API)
Code workspaceSandbox (@cloudflare/sandbox) — real Linux containers, filesystem, shell, git, package installs, preview URLs, persistent across turnsWhere Troy writes/tests his products and his own code changes (Sandbox, agent tool)
Web browsingBrowser Rendering (Puppeteer/Playwright/Stagehand + REST quick actions)See §4.2 (Browser Rendering)
LLM proxyAI Gateway — caching, retries, model fallbacks, cost/token analyticsFree observability + resilience on every model call (AI Gateway)
Long-term artifacts / knowledgeR2 (skills, artifacts), Vectorize (semantic memory, later)Docs' recommended division of labor (memory concepts)
TracingWorkers Observability traces (OpenTelemetry GenAI spans)Audit every tool call (tracing)

Config notes: nodejs_compat flag, DO binding + new_sqlite_classes migration, secrets via wrangler secret put, Workers Paid plan ($5/mo — required for Sandbox containers; DOs otherwise work on free) (configuration, limits).


2. The Brain — Model Layer and Loop

  • Model: Claude (Anthropic API) called through AI Gateway for caching, fallback, and per-call cost tracking. Use adaptive thinking with the effort ladder as the intelligence/cost lever; freeze the system-prompt prefix for prompt caching (~0.1× input price on cache reads) (prompt caching).
  • Loop: the AI SDK ToolLoopAgent inside Troy's Agent class — provider-agnostic TypeScript, built-in stop conditions (step caps as a runaway guard), prepareStep hooks for gating. Cloudflare's docs bless this exact pairing, and getAITools() converts connected MCP servers straight into AI SDK tools (using AI models).
  • Two-tier work model: Troy's DO loop is the executive (cheap, always-on, decides and dispatches). Heavy building work — coding a product, refactoring his own repo — runs as jobs in the Sandbox container, optionally driven by the Claude Agent SDK (the full Claude Code harness as a library: file tools, subagents, auto-compaction). The executive stays small; the workshop gets a real computer.
  • Tool-overload control: don't load 50 MCP tool schemas into every prompt. Register few, consolidated, workflow-shaped tools (Writing Tools for Agents); for multi-tool data flows use the code-execution pattern — Anthropic measured a 98.7% token reduction presenting MCP as a code API (Code Execution with MCP); Cloudflare ships this natively as Code Mode (experimental — adopt once stable; it also supports requiresApproval: true on connector methods).
  • Background/batch: route non-urgent bulk work (nightly analytics summaries, content drafts) through the Batch API at 50% price (batch processing).

3. Memory

Layered, per Anthropic's context-engineering guidance (Effective Context Engineering) and the Agents SDK memory model (conversation state & memory):

  1. this.state (small, synced): current venture, mode, budget status, active task pointers.
  2. SQLite (this.sql) — the ledger layer, exact facts only: ventures, transactions (every dollar in/out — Project Vend's core fix), customers, decisions (append-only journal: what/why/outcome), metrics, approvals, tasks. Money data lives in SQL, never in prose notes.
  3. Files in R2 — working notes and lessons: Markdown notes, venture briefs, post-mortems, drafts. This mirrors Anthropic's memory-tool pattern (file-based memory measured at +39% on agentic tasks with 84% less token burn) (memory tool, context management). Never store credentials in memory files.
  4. Compaction: the SDK's built-in macro-compaction (compactAfter) + freezeSystemPrompt() to preserve prompt caching; sub-agent/Sandbox jobs return short summaries, not transcripts.
  5. Vectorize (deferred): add semantic recall only when the notes corpus actually outgrows keyword/FTS search. Not in v1.

4. The Tool Belt

Cross-cutting auth pattern (every vendor converges on it): remote MCP over streamable HTTP with non-interactive token auth for the agent loop, REST/SDK fallback for gaps; least-privilege scoped credentials; all secrets in Workers Secrets, never in Troy's context.

4.1 GitHub — code, self-improvement, products

  • Path: official remote MCP server https://api.githubcopilot.com/mcp/ with a fine-grained PAT scoped to Troy's repos (Authorization: Bearer); graduate to a GitHub App (bot identity, installation tokens, higher rate limits) once running (github-mcp-server, remote server, App auth).
  • Scoping: per-toolset endpoints (/mcp/x/{toolset}) and /readonly variants — mount repos, pull_requests, issues, actions only.
  • Fallback: Octokit (fetch-based, Workers-compatible) for bulk/blob operations.

4.2 Web access — search, scrape, browse

Browser-use is Python-only and doesn't fit the TypeScript/Workers stack; Cloudflare's native stack covers all three layers:

  • Search: Brave Search API — plain REST, $5 free credit/month (~1,000 queries) covers a solo agent.
  • Fetch/scrape: plain fetch() for static pages (free); Browser Rendering quick actions REST endpoints (/markdown, /scrape, /json) for LLM-ready extraction (Browser Rendering).
  • Full automation: Playwright — or Stagehand for AI-resilient selectors (act/extract/observe) — on Cloudflare Browser sessions ($0.09/hr past 10 included hours; 10 free min/day on free plan) (limits, pricing). Live View lets you take over for logins/CAPTCHAs. Escalation path if needed later: Browserbase (same Stagehand code, adds stealth/captcha) (browserbase.com/pricing).

4.3 Vercel — websites, deploys, analytics

  • Path: REST API via @vercel/sdk (fetch-based, Workers-compatible) with an access token — this is primary because Vercel's MCP server (mcp.vercel.com) is OAuth-only and restricted to approved clients (Claude, Cursor, etc.), so a custom headless agent can't connect directly (Vercel MCP, REST API).
  • Covers: project create, deployments (POST /v13/deployments — file-tree deploys, no Git required), env vars, domains/DNS, Web Analytics reads, runtime logs. Use the MCP server from your Claude Code sessions when supervising Troy's projects.

Domains — free first, registrar later:

  • v1: generated .vercel.app URLs. Every deployment automatically gets <project>-<scope>.vercel.app plus per-branch/per-commit URLs — no API call, no cost (generated URLs). Custom unclaimed <name>.vercel.app subdomains attach via the same POST /v10/projects/{id}/domains endpoint (first-come, first-served).
  • Later: real domains via the Vercel Registrar API (registrar guide, buy-a-domain). One typed buy_domain tool wrapping the documented flow: GET .../availability (bulk ≤50) → GET .../price?years=NGET .../contact-info/schema (TLD-specific extras) → POST /v1/registrar/domains/{domain}/buy with expectedPrice (order rejected on price drift) → poll GET /v1/registrar/orders/{orderId} (draft|purchasing|completed|failed) → attach to project (Vercel-bought domains auto-verify, nameservers pre-configured). DNS CRUD via /v2/domains/{domain}/records.
  • Guardrail notes: purchases charge the team card immediately and are non-refundable, and the REST buy endpoint has no idempotency key (that's an MCP-layer feature) — so the tool must poll the orderId on retry, never re-POST, and every purchase stays approve-before with the quoted price in the approval request. Availability checks are rate-limited at 60/min, price at 100/min (limits).

4.4 Supabase — Troy's product database

  • Path: official remote MCP https://mcp.supabase.com/mcp with a PAT, hard-scoped in the URL: ?project_ref=<troys-project>&features=database,debugging,development,functions (Supabase MCP, tool list).
  • Tools: execute SQL, migrations, edge function deploys, logs, security/performance advisors, TS type generation. supabase-js in product code for the data plane.
  • Heed their published prompt-injection warning: data returned from the DB can carry injected instructions — one dedicated project for Troy (which you're creating), never a production DB shared with anything else.

4.5 Social media — Postiz (self-hosted)

  • Choice: Postiz (AGPL-3.0). It beats Mixpost decisively for an agent: full public API free on self-hosted (posting, scheduling, media, analytics) and a built-in MCP server (/mcp endpoints, 9 tools incl. schedulePostTool) — Mixpost paywalls both API and MCP behind a $299 Pro tier (Postiz API, Postiz MCP, Mixpost pricing).
  • Coverage: X, LinkedIn, Instagram, TikTok, YouTube, Reddit, Threads, Bluesky, Mastodon, Discord + more. Postiz holds all platform OAuth tokens; Troy holds one API key.
  • Deploy: Docker Compose on a ~$6/mo VPS. Use the REST API for analytics reads (not exposed via MCP). Rate limit: 90 posts/hour self-hosted.
  • Why an aggregator: one credential store and one API instead of per-platform OAuth apps and pricing (X API alone is now pay-per-use, $0.015/post for new developers) (X API pricing).

4.6 Email — AgentMail

  • Path: AgentMail Node SDK + REST with an inbox-scoped API key (am_ prefix — blast-radius control). One call creates Troy's inbox (troy@agentmail.to or a custom domain later).
  • Inbound: AgentMail webhooks → a Worker route → Troy's DO — the natural fit on Cloudflare (10 event types: received/bounced/complained/etc.) (webhooks). Hosted MCP also exists (https://mcp.agentmail.to/mcp, x-api-key header, 24 tools) (MCP).
  • Use cases: signups for services Troy needs, customer support, outreach (CAN-SPAM compliant), receipts. Drafts API supports human-review-before-send for outreach. Free tier: 3 inboxes / 3,000 emails/mo (pricing).
  • Note: Cloudflare has native email channels (onEmail, sendEmail) — keep as a fallback; AgentMail is purpose-built for agent inboxes and stays.

4.7 Stripe — revenue

  • Path: remote MCP https://mcp.stripe.com with a restricted API key as bearer token — Stripe explicitly documents this for autonomous agents and "strongly recommends" restricted keys (Stripe MCP, restricted keys). Alternative in-process: the toolkit packages now consolidated at github.com/stripe/ai with an explicit per-action permission map.
  • Covers: payment links, products/prices, customers, invoices, subscriptions, refunds, balance/payouts, plus docs search. Payment links are Troy's default monetization primitive (Vend phase 2's fix for hallucinated payment details). Token-metered billing available if Troy sells AI products (token billing).
  • Key discipline: start in sandbox mode; the live restricted key excludes payouts, account changes, and anything not on the allowlist. Refunds above a threshold require approval (§6).

4.8 Media generation — fal.ai primary, Workers AI free tier

Marketing without visuals underperforms everywhere Troy operates (social, landing pages, OG images, ads later).

  • Primary: fal.ai. The only platform that covers both frontier image and video behind one API key: FLUX Pro/Kontext, Recraft V3 (best for text-in-image/OG assets), Seedream for images; Veo 3.1, Kling 2.5, Wan 2.5 for video — with published per-output prices (~0.020.04/image;0.02–0.04/image; 0.05–0.40/s video) (pricing). Its queue + signed-webhook flow is purpose-built for Workers: fal.queue.submit(..., { webhookUrl }) from Troy's DO, result POSTs back to a Worker route, asset lands in R2 (queue, webhooks). Fetch-based TS client runs on Workers; hosted MCP at mcp.fal.ai/mcp authenticates with the same API key — genuinely headless (fal MCP).
  • Free/cheap tier: Workers AI via the native ai binding — flux-1-schnell / flux-2 for high-volume, low-stakes images (drafts, thumbnails) inside the 10k free neurons/day; escalate to fal for hero assets. No video models on Workers AI (models, pricing).
  • Future add-on: HeyGen for avatar/talking-head marketing videos. Integrate via REST, not its MCP (the MCP is OAuth-only and draws on consumer-plan credits — wrong shape for a headless agent): POST /v2/video/generate with X-Api-Key, async completion via webhook events (avatar_video.success) — the same webhook pattern as fal, so it drops in as one more thin tool. Pay-as-you-go API wallet from 5, 5, ~1/min standard avatar video (API pricing, webhooks).
  • Evaluated and skipped: Higgsfield — 30+ models via MCP incl. Soul (consistent characters) and Cinema Studio, but the MCP is account-OAuth with no API keys, billing is subscription credits, and there's no TS SDK; its distinctive models are largely reachable through fal anyway. Reconsider only if consistent-character brand mascots become core. Replicate overlaps fal's catalog (and outputs expire after 1 hour) — but it was acquired by Cloudflare, so re-evaluate in ~6 months for native Workers bindings (Replicate docs).
  • Guardrails: media spend flows through the ledger like everything else — per-output prices make it predictable; video generation above a per-job cost threshold is notify-after.

5. Skills and Self-Improvement

Skills — Troy's growable playbook layer. Adopt the open Agent Skills standard (SKILL.md folders, YAML frontmatter, progressive disclosure — ~30–50 tokens per skill at rest, full body loaded only when relevant) (Anthropic on Agent Skills). Implementation in a custom agent needs only: skills stored in the repo (synced to R2), frontmatter injected into Troy's system prompt at start, file-read + sandbox-exec tools to pull bodies and run bundled scripts. The Agents SDK's session "skills" providers (R2/D1, load_context) map onto this directly (memory concepts).

Starter skills: validate-opportunity, launch-checklist, write-landing-page, pricing-playbook, content-calendar, weekly-review, deploy-to-vercel, customer-support.

Self-improvement ladder (cheapest/safest first):

  1. Memory + skill edits (day one): Troy updates his own notes, post-mortems, and skills as he learns — most of the compounding benefit, near-zero risk.
  2. PR-gated code changes (phase 4): Troy edits his own harness only via branch → PR in his GitHub repo; an eval gate (regression suite of representative tasks) must pass, and an independent read-only reviewer agent critiques the diff; the running production Troy only executes merged code (agent-PR review). Human review required for anything touching money paths, permissions, or guardrails.
  3. Never: live-editing the running agent; modifying guardrail/limit code (it lives outside the directory Troy may touch).

6. Guardrails and Governance

Non-negotiable, enforced outside the model — Vend's core lesson is that the model will agree to bad deals; the platform must refuse.

  1. Spend ledger with hard caps. Every money-moving tool calls a ledger check before executing: per-transaction, daily, and monthly caps. Cap reached → Troy pauses and notifies you. (Modeled on Anthropic's session budgets: hard caps resumable only by a human (sessions).)
  2. Four-tier action classification:
    • Auto-allow: reads, drafts, analytics, memory writes, sandbox work.
    • Notify-after: publishing posts, deploys, small spends (< $X), sending routine email.
    • Approve-before: payments/refunds above threshold, buying domains, price changes, new subscriptions/services, outreach campaigns, merging self-modification PRs. Implemented as Workflow waitForApproval() gates — durable, wait indefinitely at zero cost, approve/reject from a simple dashboard or email reply (HITL patterns).
    • Forbidden (no tool exists): new payment rails, contracts/legal commitments, hiring, touching guardrail code, credentials in memory.
  3. Least-privilege credentials everywhere (§4): fine-grained GitHub PAT, Stripe restricted key, Supabase project-scoped PAT, AgentMail inbox-scoped key — injected as Workers Secrets at the tool layer so raw keys never enter model context. Treat any key the model can see as compromised under prompt injection.
  4. Kill switch + audit. A paused flag checked every loop iteration (flip via dashboard/API), credential revocation as the hard stop, and append-only logging of every tool call with reasoning (SQL decisions table + Workers traces).
  5. Money actions are dedicated typed tools, never generic shell/fetch — a create_payment_link tool can be gated and audited; bash -c curl cannot (Writing Tools for Agents).
  6. Platform ToS compliance: original scheduled content is fine; no keyword-triggered auto-replies, follow/unfollow scripts, or fixed-interval bot patterns (X revokes write access for these); respect Reddit/HN self-promotion norms; CAN-SPAM for email; label automation where required (X automation rules). Human-approve outbound social for the first weeks, then relax to notify-after.
  7. Legal/identity clarity: Troy operates under your Stripe org and your accounts; you are the accountable merchant of record. Vend phase 2's residual failures (near-illegal contracts, social manipulation) are exactly what tiers 2 and the forbidden list exist to catch.

7. Business Operating System — how Troy actually makes money

The open-ended entrepreneur layer is the agent loop; the repeatable inner activities are workflows (per Building Effective Agents: agents for open-ended decisions, workflows for known paths).

The venture loop:

1SCOUT → VALIDATE → BUILD → LAUNCH → GROW → MEASURE → (double-down | iterate | kill)
  • Scout: web research (search + browse) for niches, pains, trends; log candidate opportunities with revenue model, effort estimate, and confidence to SQL.
  • Validate cheaply: landing page + waitlist (Vercel deploy + AgentMail signups + a Postiz teaser) before building anything. Kill criteria defined in advance — written to the venture record.
  • Build: Sandbox workspace → GitHub repo → Vercel deploy → Supabase backend → Stripe payment link. Bias to small digital products: micro-SaaS, tools, templates, content products, APIs (Stripe token-billing if AI-powered).
  • Grow: content calendar via Postiz, SEO pages, launch posts (Product Hunt/Reddit per skill playbooks), email list.
  • Measure: Vercel Analytics + Stripe revenue + Postiz engagement rolled into SQL metrics nightly.

Operating cadence (via this.schedule() cron):

  • Daily heartbeat: process inbox, check metrics/revenue vs. ledger, execute scheduled content, advance the top task queue, write journal entry.
  • Weekly review: P&L per venture from the ledger, kill/persist decisions against pre-registered criteria, update skills with lessons, propose next week's plan → sent to you (notify or approve depending on scope).
  • Monthly: strategy memo + self-improvement proposals.

North-star metric: net profit (revenue − API costs − infra − tool subscriptions), computed from the ledger, not self-reported.


8. Build Plan

Phase 0 — Foundation (repo + rails): Scaffold from cloudflare/agents-starter; wrangler config (DO binding, SQLite migration, nodejs_compat); secrets; SQL schema (ledger, ventures, decisions, tasks, approvals); guardrail core (spend caps, action tiers, pause flag) — built and tested before any tool can spend a cent; minimal dashboard (state view, approval queue, kill switch); observability traces on.

Phase 1 — A brain that wakes up: AI SDK loop through AI Gateway → Claude; daily heartbeat schedule; memory (state/SQL/R2 notes + compaction); skills loader with 3–4 starter skills; approval Workflow wired to dashboard + email. Exit test: Troy runs a week of heartbeats, researches (web search/fetch), journals, and requests one approval correctly.

Phase 2 — Hands (build & ship): GitHub MCP (fine-grained PAT); Sandbox container workspace; Vercel REST deploys; Supabase MCP (scoped). Exit test: Troy ships a working demo site end-to-end — repo → build in sandbox → deploy → DB — on a free .vercel.app URL.

Phase 3 — Distribution & revenue: Postiz on VPS + platform accounts connected; AgentMail inbox + webhook route; Stripe sandbox → restricted live key; Stripe/AgentMail webhooks into Troy; fal.ai key + webhook route for marketing assets (Workers AI binding for cheap drafts). Exit test: first real payment link sold and reconciled in the ledger.

Phase 4 — Compounding: Eval suite (representative tasks, run in CI); PR-gated self-modification + independent reviewer agent; Code Mode adoption for multi-tool flows; Vectorize memory if notes outgrow FTS; buy_domain tool on the Vercel Registrar API (approve-before — trigger: a venture with real revenue that warrants brand credibility); HeyGen REST integration for avatar videos (trigger: video content demonstrably converting); relax approval tiers where the track record supports it.


9. Cost Envelope (steady state, pre-revenue)

Item~Cost/mo
Cloudflare Workers Paid (DO, Workflows, Sandbox base)$5 + usage
VPS for Postiz~$6
AgentMail0(freetier)0 (free tier) → 20
Brave Search$0 (free credit)
Browser Rendering~$0–5 (10 hrs incl.)
fal.ai media generation~$5–20 usage (per-output pricing; Workers AI covers drafts free)
Claude API (dominant, controllable)budget-capped by you, e.g. $50–200
Domains (Phase 4+, approve-before, non-refundable) / HeyGen (future, from $5) / miscvariable

The model spend is the real dial; prompt caching, compaction, effort laddering, and Batch API keep it down. Everything else is ~$15/mo.


10. Source Index

Cloudflare: Agents platform · Agents API · State · Scheduling · Fibers · Workflows · MCP client · HITL · Memory · Sandbox · Browser Rendering · AI Gateway · Code Mode · Limits · DO pricing

Anthropic: Building Effective Agents · Writing Tools for Agents · Agent Skills / spec · Code Execution with MCP · Context Engineering · Memory tool · Project Vend 1 / 2 · Claude Agent SDK

Integrations: GitHub MCP server · Vercel MCP / REST API / Registrar API / buy-a-domain / generated URLs · Supabase MCP · Stripe MCP / stripe/ai / agentic commerce · AgentMail docs · Postiz / API / MCP · fal.ai docs / pricing / queue / MCP · Workers AI models · HeyGen MCP / API pricing · Higgsfield MCP (evaluated, skipped) · Stagehand · Brave Search API · AI SDK agents

Troy — Autonomous Entrepreneur Agent | MDX Limo