Skip to content

Repository files navigation

⚡ MicroManus

Deep Research. On Autopilot.

Next.js 16 TailwindCSS v4 Supabase Stripe

An autonomous AI research agent that queries search engines, scrapes content, synthesizes findings, and compiles elegant PDF reports. Fully decentralized billing: bring your own API key.

Explore FeaturesSystem ArchitectureGetting StartedFuture Scope


📖 Overview

MicroManus is a self-hosted, tenant-isolated AI agent application designed to execute comprehensive deep research queries. Users define the query budget, and the system coordinates an autonomous ReAct (Reasoning and Action) loop—executing Brave web searches, scraping raw DOM text, synthesizing data across cycles, and compiling a structured executive PDF summary.

Unlike traditional platforms, MicroManus operates on a Bring Your Own Key (BYOK) model. API credentials (like OpenRouter or OpenAI keys) are stored securely under encryption, and running costs are calculated in real-time down to cache hits and token margins.


🛠️ Architecture

The flowchart below demonstrates the path of a research thread, showing how the frontend, ReAct agent loop, scraper, and PDF renderer communicate:

graph TD
    User["User Query in app/page.tsx"] --> Auth{"Auth Verification (Supabase Auth)"}
    Auth -- Success --> CreditCheck{"Credit Check (profiles.credits > 0)"}
    CreditCheck -- Insufficient --> Stop["Error: Insufficient Credits"]
    CreditCheck -- Active --> KeyRetrieve["Retrieve Encrypted API Key"]
    KeyRetrieve --> Decrypt["AES-256-GCM Decryption (lib/crypto.ts)"]
    Decrypt --> LLMInit["Initialize Agent System Prompt"]
    
    subgraph AgentLoop ["Autonomous ReAct Loop (app/api/chat/route.ts) - Max 10 Turns"]
        LLMInit --> Planning["Plan Search Strategy"]
        Planning --> Act{"Choose Action?"}
        
        Act -- web_search --> BraveSearch["Brave Search (lib/search.ts)"]
        BraveSearch --> ResultFeed["Filter Web Results & Citations"]
        ResultFeed --> Planning
        
        Act -- fetch_page --> Scraping["Web Scraper (lib/scraper.ts)"]
        Scraping --> CleanDOM["Strip script/style/nav tags"]
        CleanDOM --> ParsedText["Deliver text chunk (Max 5k chars)"]
        ParsedText --> Planning
    end
    
    Act -- generate_pdf --> PDFKit["PDF Document Compiler (lib/pdf.ts)"]
    PDFKit --> AFMRedirect["FS Patch redirects .afm lookups"]
    AFMRedirect --> RobotoLoad["Load custom Roboto TTF fonts"]
    RobotoLoad --> PdfUpload["Upload PDF to Supabase storage bucket"]
    PdfUpload --> SaveArtifact["Save public URL in public.chats"]
    SaveArtifact --> FinalStream["SSE Streams PDF URL to UI"]
    
    AgentLoop -.-> TokenTrack["Track Input, Output & Cache Tokens"]
    TokenTrack -.-> CalcCost["Calculate Model Cost (lib/models.ts)"]
    CalcCost -.-> UpdateCredits["Deduct USD cost from profiles.credits"]
Loading

✨ Features

  • 🕵️ Autonomous ReAct Agent: Performs iterative planning, search query generation, web page scraping, and citation building.
  • 🔑 Bring Your Own Key (BYOK): Connects to OpenRouter or native providers. Keys are fully encrypted on-disk and in-database with AES-256-GCM.
  • 🕷️ Optimized DOM Scraper: Parses websites cleanly by discarding scripts, navigation panels, styles, and footers, saving LLM input tokens.
  • 💳 Precise Cost & Token Billing: Features a built-in catalog estimator tracking input, output, and prompt-cached tokens. Profiles are debited in real-time.
  • 📃 Robust PDF report compiles: Overrides PDFKit defaults with a custom filesystem patch, avoiding Turbopack build/runtime AFM failures by compiling clean Roboto-based PDFs.
  • 🎨 Minimalist Design & UX: Next.js 16 client styled with Tailwind CSS 4 featuring an interactive dashboard layout, credit billing triggers, and smooth status feeds.

⚙️ Configuration & Security Internals

🗄️ Database Tables (Supabase Postgres)

The tables declared in schema.sql drive tenant isolation:

  • profiles: Holds the user display metadata, status, and credits balance.
  • api_keys: Encrypted API keys keyed to owner user_id with an is_default flag.
  • chats: Tracks session titles, model ID, running status, total USD token costs, and artifact links.
  • messages: Multi-turn history logs containing system templates, tool execution payloads, and client prompts.
  • coupons: Supports promotional credits campaigns (e.g. redeeming SID_DRDROID).
🔒 Key Encryption Standard

User credentials are secure. In lib/crypto.ts, keys are protected via:

  1. Cipher: aes-256-gcm.
  2. Master Key: A unique, server-side secret (KEY_SECRET) configured in environment properties.
  3. Random IVs (initialization vectors) are generated for every key row.
  4. Encrypted payloads are formatted as iv:authTag:ciphertext before landing in Postgres. Decryption only occurs transiently during API cycles.
🛠️ Turbopack font override patch

Under Next.js 16/Turbopack, dynamic module lookups can fail for non-javascript assets. In lib/pdf.ts, we address PDFKit AFM crashes by:

  1. Overriding Node's fs.readFileSync globally.
  2. Intercepting queries for .afm layout metrics and routing them to a local cache of Roboto TTF files.
  3. Programmatically aliasing core fonts (Helvetica, Helvetica-Bold) to these Roboto variants, ensuring cross-platform compliance without reliance on host system fonts.

🚀 Getting Started

Follow these steps to deploy and run MicroManus locally:

1. Install Project Dependencies

Clone the repository and install npm packages:

git clone https://github.com/devcool20/micromanus.git
cd micro-manus
npm install

2. Configure Environment Files

Copy .env.example to .env.local:

cp .env.example .env.local

Fill in the necessary values:

  • NEXT_PUBLIC_SUPABASE_URL & NEXT_PUBLIC_SUPABASE_ANON_KEY: Credentials from your Supabase Project settings.
  • SUPABASE_SERVICE_ROLE_KEY: Service Key used by billing logic.
  • KEY_SECRET: A secure 64-character hexadecimal key (e.g. generated via openssl rand -hex 32).
  • BRAVE_API_KEY: API key for web search (Optional; mock mode activates if left blank).
  • NEXT_PUBLIC_STRIPE_PK & STRIPE_SECRET_KEY: Stripe API keys for credits topups.

3. Initialize Database Tables

Execute the query instructions inside schema.sql in your Supabase SQL Editor. This will register schema structures, Row Level Security (RLS) policies, and trigger hooks binding new auth signups to profiles database entries.

4. Boot Dev Server

Start the local server instance:

npm run dev

Access the dashboard at http://localhost:3000.

5. Start Stripe Webhook Listener (Optional)

To test credit transactions, spin up the Stripe CLI forwarding tool:

stripe listen --forward-to localhost:3000/api/billing/webhook

Save the returned signing secret as STRIPE_WEBHOOK_SECRET in .env.local.


🔮 Future Scope & Roadmap

We are continuously planning enhancements. The next stages of MicroManus include:

  • Multi-Agent Consensus Loops: Enable the coordinator to spawn individual sub-agents (e.g. Finance Agent, Engineering Agent, Risk Auditor) to cross-reference facts before finalizing a report.
  • Native Local Vector RAG: Let users upload PDFs, slide decks, or text documents into a chat session, allowing the agent to research local knowledge bases alongside the web.
  • Alternative Search API Connectors: Introduce Google Search API, SearXNG, and Tavily search support to supplement Brave Search.
  • Split-Screen Interactive Editor: Provide a Markdown preview panel alongside the generated PDF report, allowing immediate manual tweaks and customization before export compilation.
  • Automated cron report audits: Schedule recurrent research jobs (e.g. daily competitor tracking) that generate and email reports to teams.

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages