AegisAEGIS

Documentation

Aegis

The commerce protocol for AI agent economies. Learn how agents earn, spend safely, and operate transparently.

What is Aegis?

Aegis is a commerce protocol that lets AI agents participate in real economies. Built on the Open Wallet Standard (OWS), it gives agents the ability to:

$

Earn Money

Any API can become a paid service. Agents sell data, analysis, or compute and get paid per call.

~

Spend Safely

Configurable spending limits, address allowlists, and an inactivity kill switch keep agents on a leash.

@

Stay Visible

A real-time dashboard shows who's earning, who's spending, and how money flows between agents.

The result is an agent economy where multiple autonomous agents trade services with each other, governed by human-defined policies, with full transparency into every transaction.


How It Works

Aegis has three layers that work together to create a complete agent economy:

Layer 1: Aegis Gate — How agents earn

Gate is middleware you add to any Express API. It intercepts requests, charges callers using the x402 payment protocol, and logs the revenue. Your existing API logic doesn't change — Gate handles all the payment plumbing.

Layer 2: Aegis Policies — How agents stay safe

Three safety policies plug directly into OWS's wallet. Before any payment is signed, these policies check: Is the agent within its budget? Is the recipient address trusted? Has the agent been active recently? If any check fails, the transaction is blocked.

Layer 3: Aegis Nexus — How humans see everything

Nexus is a real-time dashboard that visualizes the entire agent economy. It shows money flowing between agents, each agent's profit and loss, budget consumption, policy enforcement events, and more — all updating live.

The supply chain in action:

Research Buyer
Buys analysis — spends $0.05
Analyst
Sells analysis, buys data — +$0.04
Data Miner
Sells raw data — +$0.01

Getting Started

Get Aegis running in under 2 minutes. The fastest way is the one-liner setup script:

One-liner setup
git clone https://github.com/rajkaria/aegis
cd aegis && ./setup.sh

This installs dependencies, builds all packages, and seeds demo data. Or do it step by step:

1

Clone and install

Download the project and install all dependencies.

2

Run setup.sh

Builds packages, seeds the demo economy, and prepares the dashboard.

3

Open the dashboard

See the economy visualized in real time.

Manual setup
git clone https://github.com/rajkaria/aegis
cd aegis && npm install

# Build all packages
npm run build

# Seed the demo economy
cd demo && npx tsx seed.ts

# Start the dashboard
cd ../dashboard && npm run dev
# Open http://localhost:3000/dashboard

Monetize Your API

Aegis Gate turns any API endpoint into a paid service with a single line of code. When another agent (or any HTTP client) calls your endpoint, Gate charges them automatically using the x402 micropayment protocol.

Install from npm
npm install aegis-ows-gate express

See the full integration guide at /use-aegis for complete, copy-pasteable examples.

Protect an endpoint

Add Gate as middleware on any Express route. Set the price and token — Gate handles the rest.

One line to monetize
// npm install aegis-ows-gate
import { aegisGate } from "aegis-ows-gate";

// This endpoint now costs $0.01 per call
app.get("/api/scrape",
  aegisGate({ price: "0.01", token: "USDC", agentId: "my-agent" }),
  (req, res) => {
    res.json({ data: "your content here" });
  }
);

Pay for a service

On the buyer side, payAndFetch handles payment automatically. It detects the price, signs the payment through OWS, and returns the content.

One line to pay
// npm install aegis-ows-gate
import { payAndFetch } from "aegis-ows-gate";

const result = await payAndFetch("http://service/api/scrape", "buyer-agent");
// Payment handled automatically — result contains the data

How payment works

1

Request

The buyer calls your endpoint normally.

2

402 Response

Gate returns HTTP 402 with the price, token, and payment address.

3

Payment

The buyer signs a payment through their OWS wallet.

4

Retry

The buyer resends the request with a payment proof.

5

Access

Gate verifies, logs the earning, and forwards to your handler.

Config-based setup

For agents with multiple endpoints, define everything in a config file:

aegis.config.json
{
  "walletName": "my-agent",
  "network": "eip155:8453",
  "endpoints": {
    "/scrape": { "price": "0.01", "description": "Web scraping" },
    "/analyze": { "price": "0.05", "description": "Data analysis" },
    "/health": { "price": "0", "description": "Free health check" }
  }
}

Spending Safety

Agents with wallets need guardrails. Aegis provides three safety policies that run automatically before every transaction. If any policy says no, the payment is blocked before it leaves the wallet.

Budget Limits

Set daily, weekly, or monthly spending caps per blockchain and token. An agent with a $0.50/day USDC budget on Base will be automatically blocked after reaching that limit.

Example: $0.50/day on Base, $1/day globally
{
  "limits": [
    { "chainId": "eip155:8453", "token": "USDC", "daily": "0.50" },
    { "chainId": "*", "token": "*", "daily": "1.00" }
  ]
}

Use * as a wildcard to set global limits across all chains and tokens.

Address Guard

Restrict which addresses your agent can interact with. In allowlist mode, only pre-approved contracts and wallets are permitted. Known scam addresses are always blocked.

Example: Only allow known contracts
{
  "mode": "allowlist",
  "addresses": {
    "eip155:8453": ["0xUSDC_CONTRACT", "0xUNISWAP_ROUTER"]
  },
  "blockAddresses": ["0xKNOWN_SCAM"]
}

Dead Man's Switch

If an agent goes silent for too long, this policy blocks all further transactions. It prevents runaway agents from sitting on funds when something goes wrong. Every successful transaction resets the timer.

Example: 30-minute inactivity timeout
{
  "maxInactiveMinutes": 30,
  "onTrigger": "revoke_key",
  "enabled": true
}

After 30 minutes of no activity, the agent is locked out until a human intervenes.


The Dashboard

Aegis Nexus is a real-time window into your agent economy. It updates live as agents transact, showing everything you need to understand what's happening.

Economy View

The main screen shows the full picture at a glance:

  • Money Flow — An animated visualization showing payments flowing between agents in your economy. See who pays whom and how much.
  • Key Metrics — Total economy volume, number of active agents, combined profit/loss, and transactions blocked by policies.
  • Budget Bars — Color-coded progress bars showing how close each agent is to their spending limits. Green is safe, yellow is getting close, red means almost spent.
  • Activity Feed — A live stream of everything happening: payments received, money spent, policies enforced, and services discovered.
Open the live dashboard → to see the demo economy with three agents already transacting.

Agent Profiles

Drill into any agent to see their complete financial picture:

  • Profit & Loss — How much the agent has earned vs. spent, and whether it's profitable
  • Wallet Balances — Token holdings across all chains (powered by Zerion)
  • Revenue Sources — Which endpoints are earning money and how much each one brings in
  • Spending Breakdown — Which services the agent is buying from and the cost of each
  • Policy History — Every allow and block decision that applied to this agent

Policy Management

Edit all three policies directly from the dashboard — no config files to edit by hand:

  • Budget Editor — Add or remove spending limits, adjust caps, see current enforcement stats
  • Guard Editor — Switch between allowlist and blocklist mode, add/remove addresses
  • Deadswitch Editor — Set the inactivity timeout, enable/disable, check the heartbeat timer

Changes take effect immediately. Each editor also shows a live JSON preview of the generated config.


Autonomous Agents

Aegis agents are not scripted bots that follow a fixed sequence. The autonomous buyer agent runs in a continuous decision loop, making independent choices at every step.

The Autonomous Loop

Each iteration of the buyer's loop follows this pattern:

1

Discover

Query XMTP for available services before each purchase. The buyer never assumes what's available.

2

Evaluate

Check remaining budget against service costs. If the budget is tight, skip expensive services or wait.

3

Decide

Buy, skip, or wait based on budget constraints and cost optimization. No human tells it what to do.

4

Execute

Sign the payment through OWS and receive the service. Policies enforce limits at signing time.

5

Terminate

When the budget is exhausted, the agent cleanly shuts itself down.

How it differs from scripted agents

A scripted agent runs a fixed sequence: call endpoint A, then B, then stop. An autonomous Aegis agent discovers what's available at runtime, evaluates whether it can afford it, and decides on its own. If a new service appears mid-run, the agent can find and use it. If prices change, it adapts its purchasing strategy.

Run the autonomous economy
cd demo && npx tsx run-economy.ts

# Starts 3 agents:
#   data-miner   — sells /scrape ($0.01)
#   analyst      — sells /analyze ($0.05), buys /scrape
#   research-buyer — autonomous buyer with $0.50 budget

Interactive Dashboard

The dashboard at useaegis.xyzis not a static display — it is fully interactive, even on the live Vercel deployment.

Run Economy Cycle

Click the button to trigger a full supply chain cycle. The buyer discovers services, pays the analyst, who pays the miner. Watch the money flow update in real-time.

Auto-Refresh

The dashboard polls every 5 seconds. New transactions, policy events, and balance changes appear automatically without page reload.

Policy Editor

Edit budget limits, guard addresses, and deadswitch configuration directly from the browser. Changes take effect immediately.

CSV Export

Download the complete transaction ledger as a CSV file for external analysis or record-keeping.

Try it live → Click “Run Economy Cycle” and watch agents trade in real-time.

x402 Payment Security

The x402 payment protocol includes built-in protections against common attack vectors. Every payment proof is validated before the seller grants access.

Timestamp Verification

Every payment proof includes a timestamp. Gate rejects proofs that are too old, preventing replay attacks where a captured payment is resubmitted later. The expiry window is configurable per endpoint.

Replay Protection

Each payment proof contains a unique nonce tied to the specific request. Even within the validity window, the same proof cannot be used twice. Gate tracks seen nonces and rejects duplicates.

Signature Validation

Payment proofs are cryptographically signed through the OWS signing enclave. Gate verifies the signature against the payer's public key, ensuring the proof was generated by the claimed wallet and has not been tampered with.


Agent Communication Protocol

Aegis includes a full XMTP-powered agent communication protocol with 12 message types for complete agent-to-agent commerce. The protocol works locally via a file-based message bus (default) and over the real XMTP network when XMTP_ENV and XMTP_WALLET_KEY are set.

For use cases, architecture deep-dive, and an end-to-end implementation guide, see the dedicated XMTP Agent Messaging Guide →

Message TypePurpose
service_announcementAgents publish available services
service_queryAgents search for capabilities
negotiation_offer/responsePrice negotiation before payment
health_ping/pongAvailability checks
payment_receiptSigned proof of payment delivery
reputation_gossipTrust observations shared between agents
sla_agreementFormal service terms
supply_chain_inviteMulti-agent coordination groups
business_cardAgent economic identity broadcast
dispute/dispute_responseDispute resolution for failed services
xmtp_notificationPolicy alerts and budget warnings via messaging

Service Discovery

1

Announce

When an agent starts up, it broadcasts what services it offers (endpoints, prices, descriptions) to the message bus.

2

Discover

An agent looking for a capability (like 'web scraping' or 'data analysis') searches the bus and finds matching services.

3

Pay

The agent calls the discovered service URL and pays automatically via x402.

Discovery in action
import { findServices, payAndFetch } from "aegis-ows-gate";

// Find services that match "analysis"
const services = findServices("analysis", "research-buyer");
// → [{ endpoint: "/analyze", price: "0.05", fullUrl: "http://..." }]

// Pay and get the result
const result = await payAndFetch(services[0].fullUrl, "research-buyer");

Price Negotiation

Agents can negotiate prices before committing to a purchase. The buyer sends an offer with a proposed price and reason; the seller can accept or counter-offer.

Negotiate before buying
import { sendNegotiationOffer, respondToNegotiation } from "aegis-ows-gate";

// Buyer proposes a lower price
sendNegotiationOffer({
  buyerId: "research-buyer",
  sellerId: "analyst",
  service: "/analyze",
  offeredPrice: "0.04",
  originalPrice: "0.05",
  reason: "Budget constraint — requesting 20% discount",
});

// Seller responds with a counter-offer
respondToNegotiation({
  sellerId: "analyst",
  buyerId: "research-buyer",
  accepted: false,
  counterPrice: "0.045",
  reason: "Can offer 10% discount for repeat buyers",
});

Health Monitoring

Before buying from an agent, check if it's online. The ping/pong protocol lets agents verify availability and queue depth.

Health checks
import { pingAgent, isAgentHealthy, respondToPing } from "aegis-ows-gate";

// Buyer checks if seller is available
pingAgent("research-buyer", "analyst");

// Seller auto-responds with status
respondToPing("analyst", "research-buyer", "online", 2);

// Check health before buying
if (isAgentHealthy("analyst")) {
  // Proceed with purchase
}

Payment Receipts (Messaging)

After a successful payment, sellers send a signed receipt to the buyer over the message bus. This provides proof of payment delivery independent of on-chain settlement.

Send a receipt
import { sendPaymentReceipt } from "aegis-ows-gate";

sendPaymentReceipt({
  sellerId: "analyst",
  buyerId: "research-buyer",
  amount: "0.005",
  token: "SOL",
  txHash: "JEX7PjWZ...",
  receiptHash: "sha256:abc123",
  service: "/analyze",
});

Reputation Gossip

Agents share trust observations about each other. After an interaction, an agent can report whether the experience was positive, negative, or neutral. Gossip scores are aggregated to build a decentralized trust network.

Report reputation
import { reportReputation, getAgentGossipScore } from "aegis-ows-gate";

// After a successful purchase
reportReputation({
  reporterId: "research-buyer",
  aboutAgent: "analyst",
  rating: "positive",
  reason: "Fast response, data quality good",
  txHash: "JEX7PjWZ...",
});

// Check an agent's gossip score
const score = getAgentGossipScore("analyst");
// → { positive: 5, negative: 0, neutral: 1, net: 5 }

SLA Agreements

Agents can propose formal service-level agreements specifying response time, uptime guarantees, and refund terms. Both parties must accept before the SLA is active.

Propose and accept an SLA
import { proposeSLA, acceptSLA } from "aegis-ows-gate";

// Buyer proposes SLA terms
proposeSLA({
  proposerId: "research-buyer",
  toAgent: "analyst",
  service: "/analyze",
  maxResponseTimeMs: 5000,
  minUptime: 95,
  refundOnViolation: true,
  validDays: 7,
});

Supply Chain Groups

Coordinate multiple agents in a supply chain. A coordinator invites participants and assigns roles, creating a named group that can be tracked in the dashboard.

Create a supply chain
import { createSupplyChain } from "aegis-ows-gate";

const chainId = createSupplyChain({
  coordinatorId: "research-buyer",
  participants: ["research-buyer", "analyst", "data-miner"],
  roles: {
    "research-buyer": "Consumer",
    "analyst": "Intermediary",
    "data-miner": "Producer",
  },
  description: "DeFi research supply chain",
});

Agent Identity & Business Cards

Every Aegis agent gets a full economic identity — services offered, reputation score, P&L stats, and wallet addresses. Agents broadcast their identity as a business card over the message bus so other agents can evaluate them before transacting.

Build and broadcast identity
import { buildAgentIdentity, createBusinessCard } from "aegis-ows-gate";

// Build a full identity profile
const identity = buildAgentIdentity("analyst", {
  "eip155:1": "0x4ef5...",
  "solana:mainnet": "CePy...",
});
// → { agentId, services, reputation, stats, walletAddresses, ... }

// Broadcast as a business card
const card = createBusinessCard("analyst");

Dispute Resolution

When a service fails after payment, the buyer can open a dispute. The defendant can accept (and issue a refund) or reject. Disputes are visible in the dashboard and discovery feed.

Open and respond to disputes
import { openDispute, respondToDispute } from "aegis-ows-gate";

// Buyer opens a dispute
const disputeId = openDispute({
  complainantId: "research-buyer",
  defendantId: "analyst",
  reason: "Timeout after payment",
  evidence: "Paid 0.005 SOL but got no response within SLA",
  requestedResolution: "refund",
});

// Seller responds
respondToDispute({
  disputeId,
  defendantId: "analyst",
  complainantId: "research-buyer",
  accepted: true,
  resolution: "Refund issued — downstream service was overloaded",
});

Agent Directory

The in-memory agent directory allows agents to register and be discovered by service type, name, or capability. Directory entries include full identity profiles and are sorted by reputation score.

Directory registration and search
import { registerInDirectory, searchDirectory, listDirectory } from "aegis-ows-gate";

// Register an agent in the directory
registerInDirectory("analyst", { "eip155:1": "0x4ef5..." });

// Search for services
const results = searchDirectory("analysis");
// → sorted by reputation score

// List all registered agents
const all = listDirectory();

XMTP Notifications

Policy blocks, budget alerts, and deadswitch warnings are sent as structured XMTP notifications. Operators can monitor agent health through the message bus.

Policy and budget notifications
import {
  notifyPolicyBlock,
  notifyBudgetAlert,
  notifyDeadswitchWarning,
} from "aegis-ows-gate";

// Alert when a policy blocks a transaction
notifyPolicyBlock("analyst", "operator", "aegis-budget", "Daily limit exceeded");

// Budget usage warning
notifyBudgetAlert("analyst", "operator", 92, "1.00");

// Deadswitch countdown
notifyDeadswitchWarning("analyst", "operator", 5);

Real vs File-based Transport

The XMTP transport layer automatically selects the best transport. When XMTP_ENV and XMTP_WALLET_KEY are set, messages are sent over the real XMTP network. Otherwise, everything works locally via the file-based message bus at ~/.ows/aegis/messages.json. All messages are always written to the file bus for dashboard visibility.

Transport layer
import { getTransport, isXMTPLive, getXMTPAddress } from "aegis-ows-gate";

// Get the active transport (auto-selects real XMTP or file bus)
const transport = await getTransport();

// Check if real XMTP is connected
console.log(isXMTPLive()); // true if XMTP_ENV + XMTP_WALLET_KEY are set

// Get the agent's XMTP address (if connected)
console.log(getXMTPAddress()); // "0x..." or null

Standalone: Use XMTP messaging without the x402 payment stack. Import from aegis-ows-gate/xmtp-messaging for messaging-only functions with zero Express/Solana/ethers dependencies. Learn more →


Production Deployment

Run Aegis agents with real money on mainnet. This guide covers environment setup, budget configuration, safety policies, and monitoring.

Environment Variables

VariableRequiredDescription
SOLANA_RPC_URLFor Solana paymentsSolana RPC endpoint. No default — must be set explicitly.
XMTP_ENVFor live messagingXMTP network: dev or production
XMTP_WALLET_KEYFor live messagingPrivate key for XMTP identity. Does not need funds.

Step 1: Initialize

Set up Aegis
npm install aegis-ows-gate aegis-ows-shared
npx aegis init

# Set your network
export SOLANA_RPC_URL=https://api.mainnet-beta.solana.com  # mainnet
# export SOLANA_RPC_URL=https://api.devnet.solana.com      # devnet (testing)

Step 2: Configure Budget

Set spending limits to control how much agents can spend. Aegis enforces these before every transaction — if a payment would exceed any limit, it's blocked.

~/.ows/aegis/budget-config.json
{
  "limits": [
    {
      "chainId": "solana:mainnet",
      "token": "SOL",
      "daily": "0.5",
      "monthly": "10.0"
    },
    {
      "chainId": "eip155:8453",
      "token": "USDC",
      "daily": "10.00",
      "monthly": "50.00"
    },
    {
      "chainId": "*",
      "token": "*",
      "daily": "15.00"
    }
  ]
}

Step 3: Configure Guard

Restrict which addresses your agents can pay. Use allowlist mode to only permit known recipients, or blocklist mode to block specific addresses.

~/.ows/aegis/guard-config.json
{
  "mode": "allowlist",
  "addresses": {
    "solana:mainnet": [
      "CePyeKXCtB6RzAatosDnnun3yryUzETKXA5rNEjPeSkL",
      "2G55SdspdgSLcrXm3ZcfSHuDhvuhXtQLWqf1zVbAYCcq"
    ],
    "eip155:8453": [
      "0xYourTrustedRecipient1",
      "0xYourTrustedRecipient2"
    ]
  }
}

Step 4: Configure Deadswitch

Auto-kill agents that go inactive. If an agent hasn't made a transaction within the timeout, its keys are revoked.

~/.ows/aegis/deadswitch-config.json
{
  "maxInactiveMinutes": 60,
  "onTrigger": "revoke_key",
  "enabled": true
}

Step 5: Run Your Agents

Start the supply chain
# Terminal 1: Start the data miner (earns SOL)
node demo/agents/data-miner.js

# Terminal 2: Start the analyst (buys from miner, sells to buyers)
node demo/agents/analyst.js

# Terminal 3: Start the autonomous buyer (discovers, negotiates, buys)
node demo/agents/autonomous-buyer.js

Step 6: Monitor

Watch everything in real-time from the Aegis dashboard or CLI.

Monitor spending and health
# Check budget usage
npx aegis budget --period daily

# Check agent status
npx aegis status

# View the dashboard
open http://localhost:3000/dashboard

Safety: Always start on devnet first. Set SOLANA_RPC_URL to the devnet endpoint, test your agents, verify budget limits are enforced, then switch to mainnet when ready. The budget policy will block any transaction that exceeds your configured limits.


CLI Tools

Manage your Aegis setup from the command line.

Set up Aegis

aegis init       # Create config directory with defaults
aegis install    # Register policies with OWS

Monitor the economy

aegis status     # See agent P&L table + deadswitch status
aegis budget     # Check spending against limits
aegis report     # Generate spending report (summary, detailed, or CSV)

Manage security

aegis guard                        # View current allowlist/blocklist
aegis guard --add 0xA0b8... --chain eip155:1  # Allow an address
aegis guard --add 0xBad0... --block           # Block an address

Live Demo

Aegis ships with a ready-to-run demo that creates three agents trading with each other:

Data Miner
Sells web scraping
$0.01 / call
Analyst
Buys data, sells analysis
$0.05 / call
Research Buyer
Buys analysis reports
$0.50 budget

The buyer asks for analysis, which triggers the analyst to buy raw data from the miner. Money flows through the entire supply chain, policies enforce spending limits, and the dashboard shows everything live.

Run the full demo
cd demo
npx tsx seed.ts        # Seed economy data
npx tsx run-economy.ts # Start all 3 agents + run transactions


For Developers

Aegis is a TypeScript monorepo with four packages. Here's how it's organized:

PackageWhat it does
@aegis-ows/gateExpress middleware for x402 payments + client helper
@aegis-ows/policiesThree OWS policy executables (budget, guard, deadswitch)
@aegis-ows/cliCommand-line tools for setup, monitoring, and management
@aegis-ows/sharedShared types, file I/O helpers, and computation functions

The dashboard is a standalone Next.js app that reads from the same data files. All data lives as JSON in a local directory — no database required. See the GitHub repo for full source code and contributing guide.


Management Dashboard

The /dashboard/manage page is a browser-based control center for the full agent lifecycle. Everything the CLI does is available from the UI.

Create Wallets

Provision new OWS wallets with derived addresses across all supported chains.

Register Policies

Register built-in or custom policy executables with the OWS runtime.

Fund Agents

Request Solana devnet airdrops to fund agent wallets for testing.

Send Payments

Send real SOL between agent wallets on Solana devnet via OWS signing. Transactions are verifiable on Solana Explorer.

The manage page also supports creating API keys bound to specific wallets and policies, and creating custom policy executables. All operations call a single POST /api/manage endpoint.

Open the Control Center → to create wallets, register policies, and send real on-chain payments.

Solana On-Chain Payments

Aegis supports real on-chain Solana transfers for agent-to-agent payments. When an x402 payment targets a Solana address, payAndFetch automatically builds and submits a SOL transfer transaction via the OWS signing SDK. Each transaction is recorded on Solana devnet and linked directly from the activity feed in the dashboard.

How It Works

packages/gate/src/solana-pay.ts
import { sendSolPayment } from "@aegis-ows/gate/solana-pay";

// Called automatically inside payAndFetch when network is Solana
const txHash = await sendSolPayment(
  "research-buyer",              // OWS wallet name
  "CePyeKXCtB6RzAatosDnnun3yryUzETKXA5rNEjPeSkL", // analyst's address
  0.005                          // amount in SOL
);
// Returns a real Solana devnet tx hash, e.g.:
// "JEX7PjWZLia2NpRVS...kwqb5GA"

Real Devnet Transactions

The demo economy ran 3 supply chain cycles on Solana devnet. Each cycle produced 2 real on-chain transfers: research-buyer → analyst (0.005 SOL) and analyst → data-miner (0.001 SOL). All transactions are viewable on Solana Explorer with ?cluster=devnet.

FromToAmountExplorer
research-buyeranalyst0.005 SOLJEX7...b5GA
analystdata-miner0.001 SOLzBAR...GB7V
research-buyeranalyst0.005 SOL5tsN...Xbj
analystdata-miner0.001 SOLQyxH...xN
research-buyeranalyst0.005 SOLsGwQ...Mby
analystdata-miner0.001 SOL3QVC...u4eW

Configuration Options

OptionDescription
network: "solana:devnet"Triggers on-chain Solana transfer in payAndFetch
payTo: <44-char base58>Solana address automatically triggers SOL payment
txHash in ledger entriesStored in both budget-ledger.json and earnings-ledger.json; shown as Explorer links in the activity feed

Custom Policies

Beyond the three built-in policies, Aegis supports creating custom policy executables. A custom policy is any script that reads a PolicyContext from stdin and writes a PolicyResult to stdout.

Creating a Custom Policy

Use the Management Dashboard or the API to register a custom policy. Provide a policy ID, name, the path to your executable, and the action (deny or warn).

Custom policy JSON
{
  "id": "my-rate-limiter",
  "name": "Rate Limiter Policy",
  "version": 1,
  "created_at": "2024-01-01T00:00:00Z",
  "rules": [],
  "executable": "/usr/local/bin/my-rate-limiter",
  "config": null,
  "action": "deny"
}

Via the API

Send a POST request to /api/manage with the register_custom_policy action:

POST /api/manage
{
  "action": "register_custom_policy",
  "id": "my-rate-limiter",
  "name": "Rate Limiter Policy",
  "executable": "/usr/local/bin/my-rate-limiter",
  "policyAction": "deny"
}

Policy Interface

Your executable must follow the OWS policy interface. It receives a JSON PolicyContext on stdin and must print a JSON PolicyResult to stdout:

PolicyResult format
// Allow the transaction
{ "decision": "allow" }

// Block the transaction
{ "decision": "deny", "reason": "Rate limit exceeded" }

// Warn but allow
{ "decision": "warn", "reason": "Approaching rate limit" }

Dashboard

Manage UI

The /dashboard/managepage provides a browser-based control panel for everything the CLI can do. It requires OWS installed locally — on Vercel, wallet operations are view-only.

Sections

SectionDescription
Create Agent WalletCreates an OWS wallet with addresses across all chains
Register PolicyRegisters aegis-budget, aegis-guard, or aegis-deadswitch with OWS
Custom PolicyCreates and registers a custom policy executable with OWS
Create API KeyGenerates an API key bound to wallets and policies
Fund Agent (Devnet)Requests a Solana devnet airdrop to an agent address
Send PaymentSends SOL between agents via OWS signing on devnet

API Route

All manage actions go through a single POST /api/manage endpoint. Send a JSON body with an action field to select the operation.

POST /api/manage
// Create a wallet
{ "action": "create_wallet", "name": "my-agent" }

// Fund on devnet
{ "action": "fund_solana", "address": "<base58>", "amount": "1" }

// Send SOL via OWS
{ "action": "send_sol",
  "fromAddress": "<base58>", "toAddress": "<base58>",
  "fromWallet": "data-miner", "amount": "0.1" }
MCP

MCP Server

The Aegis MCP server lets Claude Code, Cursor, and other MCP clients interact with your agent economy directly. Query agent P&L, check budgets, discover services, and review policy logs without leaving your editor.

Setup

Build the MCP server
cd packages/mcp-server
npm install && npx tsc

Add to your Claude Code or Cursor MCP config:

~/.claude/settings.json or .mcp.json
{
  "mcpServers": {
    "aegis": {
      "command": "node",
      "args": ["/path/to/aegis/packages/mcp-server/dist/index.js"]
    }
  }
}

Available Tools

ToolDescription
aegis_economy_statusFull economy overview: total flow, agent P&L, policy stats
aegis_check_budgetRemaining budget for an agent by period
aegis_list_agentsAll agents with wallet addresses and P&L
aegis_policy_logRecent policy enforcement events
aegis_discover_servicesSearch for available services on the XMTP message bus
aegis_send_paymentPrepare a SOL payment between agents on devnet
x402

Live x402 Endpoints

The dashboard hosts real x402-compliant API endpoints. Any client (including ows pay) that hits these routes gets a 402 response with payment details. After paying, the endpoint returns the paid content.

EndpointPriceDescription
/api/x402/scrape0.001 SOLWeb scraping service
/api/x402/analyze0.005 SOLData analysis service
Try it — unpaid request returns 402
curl -s https://your-app.vercel.app/api/x402/scrape | jq
# Returns: { x402Version: 1, payTo: "...", price: "0.001", token: "SOL", ... }
Paid request with X-PAYMENT header
curl -s https://your-app.vercel.app/api/x402/scrape \
  -H 'X-PAYMENT: {"txHash":"abc123...","token":"SOL","fromAgent":"my-agent","timestamp":"2025-01-01T00:00:00Z"}' | jq
# Returns: { success: true, data: { title: "Live x402 Response from Aegis", ... } }

Payment verification includes timestamp freshness (5-minute window) and transaction hash validation. Expired or invalid payments are rejected with a 401.


Security

Aegis is built with production-grade security at every layer. Here are the protections that keep your agent economy safe.

EIP-712 Signature Verification

Payment authorizations use EIP-712 typed data signatures. Gate recovers the signer's address and verifies it matches the sender's OWS wallet, ensuring payments cannot be forged.

Chain-Agnostic Settlement Verification

On-chain verification supports Solana (devnet and mainnet) and EVM chains including Ethereum, Base, Polygon, and Arbitrum. Gate confirms the payment transaction actually landed on-chain before granting access.

Rate Limiting

402 payment challenge responses are rate-limited to 100 per minute per IP address. This prevents bad actors from spamming your endpoints with unpaid requests.

Webhook Alerting

Set the AEGIS_WEBHOOK_URL environment variable to receive notifications whenever a policy blocks a transaction. Stay informed about enforcement events in real time.

File Locking

Concurrent policy execution is safe via exclusive file locks with stale lock detection. Multiple agents can operate simultaneously without data corruption.

Input Sanitization

The management API validates all inputs to prevent command injection and other attacks. All user-provided data is sanitized before being passed to system commands.


Service Registry

In addition to XMTP-based discovery, Aegis provides an HTTP service registry for cross-machine agent discovery. Agents on different servers can register their services and find each other through a simple REST API.

1

Register

An agent POSTs its service details (endpoint, price, description) to the registry when it starts up.

2

Discover

Any agent can search the registry by keyword to find services matching its needs.

3

Connect

The agent calls the discovered service URL directly and pays via x402.

Register a service
POST /api/registry
{
  "agentId": "my-agent",
  "endpoint": "/analyze",
  "price": "0.005",
  "token": "SOL",
  "description": "AI-powered data analysis",
  "baseUrl": "https://my-agent.example.com"
}
Search for services
GET /api/registry?q=analysis
// Returns: { services: [...], total: 1 }
MethodEndpointDescription
GET/api/registryList all services (optional ?q= filter)
POST/api/registryRegister or update a service

Payment Receipts

Every x402 payment generates a signed receipt with a SHA-256 hash. The hash is posted to Solana devnet as a transaction memo, making every payment auditable on-chain forever.

How It Works

1

Receipt Created

After every successful payment, a PaymentReceipt is created with a deterministic SHA-256 hash of the receipt data (id, timestamp, parties, amount, token, chain, endpoint).

2

Hash Anchored

The receipt hash is posted to Solana devnet as a memo transaction using the Memo program (MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr). The memo contains AEGIS_RECEIPT:<hash>.

3

Proof Linked

The Solana transaction hash is linked back to the receipt, updating its status to 'anchored'. Anyone can verify the proof on Solana Explorer.

Receipt Fields

FieldDescription
idUnique receipt identifier
from / toBuyer and seller agent IDs
receiptHashSHA-256 hash of the receipt data
proofTxHashSolana transaction that anchors this receipt on-chain
statuscreated | anchored | verified

API

MethodRouteDescription
GET/api/receiptsList all payment receipts with on-chain proof status

Programmatic Usage

packages/shared/src/receipts.ts
import { createReceipt, updateReceiptProof, getReceiptsByAgent } from "@aegis-ows/shared";

// Create a receipt after payment
const receipt = createReceipt({
  from: "research-buyer",
  to: "analyst",
  amount: "0.005",
  token: "SOL",
  chain: "solana:devnet",
  endpoint: "/analyze",
  paymentTxHash: "...",
});

// Anchor on Solana (done automatically by Gate)
import { anchorReceiptOnChain } from "@aegis-ows/gate/receipt-anchor";
const proofTx = await anchorReceiptOnChain("research-buyer", receipt.receiptHash);
if (proofTx) updateReceiptProof(receipt.id, proofTx);

// Query receipts for an agent
const myReceipts = getReceiptsByAgent("analyst");

Economy Analytics

Aegis includes a rule-based intelligence engine that generates insights about your agent economy. It detects patterns in spending, revenue, policy enforcement, and supply chain dynamics without requiring external API calls.

Insight Types

InsightDescription
Economy HealthNet flow analysis — is the economy self-sustaining?
Top EarnerIdentifies highest-revenue agent and best-performing endpoint
Budget AlertWarns when agents exceed 80% or 95% of daily budget limits
Policy EnforcementBlock rate analysis — are policies too restrictive?
Supply ChainBuyer/intermediary/seller classification with margin analysis
Activity Trend24-hour transaction volume with day-over-day comparison

Access

Insights appear in the dashboard's Economy Intelligence card and are also available via the MCP server tool aegis_economy_insights.

MCP Tool
// Available as an MCP tool for any AI assistant
aegis_economy_insights
// Returns: Economy Intelligence Report with all detected patterns

Multi-Chain Support

Aegis Gate and Policies work across all OWS-supported chains. The payment middleware supports different signing mechanisms per chain family.

Supported Chains

ChainSigning MethodStatus
SolanaOn-chain SOL transfersActive (devnet)
EthereumEIP-712 signed authorizationsActive
BaseEIP-712 signed authorizationsActive
BitcoinsignMessage proofsReady
CosmossignMessage proofsReady
TronsignMessage proofsReady
TONsignMessage proofsReady
SuisignMessage proofsReady

Usage

Multi-chain Gate configuration
// Set the network parameter to target any OWS chain
aegisGate({
  price: "0.01",
  token: "USDC",
  agentId: "my-agent",
  network: "eip155:8453",  // Base
  // network: "solana:devnet"  // Solana
  // network: "eip155:1"      // Ethereum mainnet
})

API Features

All public API endpoints include production-ready features for reliability and integration.

Gate Operator Stats

Every Gate instance tracks operator analytics: total 402 challenges served, successful payments, rejected payments, total revenue earned, and conversion rate. Access via the health endpoint.

Health endpoint response
GET /health
{
  "status": "healthy",
  "stats": {
    "total402": 150,
    "totalPaid": 42,
    "totalRejected": 3,
    "totalRevenue": 0.042,
    "conversionRate": "28.0%"
  }
}

CORS Support

All public API endpoints support cross-origin requests. The x402 endpoints, service registry, receipts, and analytics APIs accept requests from any origin with proper CORS headers including X-PAYMENT and Authorization headers.

Pagination

List endpoints support pagination via ?limit=N&offset=N query parameters. Responses include pagination metadata with total count, current offset, and a hasMore flag.

Paginated request
GET /api/receipts?limit=10&offset=0
{
  "receipts": [...],
  "pagination": {
    "total": 42,
    "limit": 10,
    "offset": 0,
    "hasMore": true
  }
}

Supported on: /api/receipts, /api/registry, /api/economy (activity feed).


Agent Reputation

Every agent in Aegis carries a 0–100 reputation score that reflects its trustworthiness as an economic actor. The score is computed continuously from payment history, policy compliance, and on-chain receipt verification.

Reputation Levels

LevelScore RangeDescription
New0 – 24Agent has no or minimal payment history
Trusted25 – 49Consistent payment record with few policy violations
Verified50 – 74Strong history with on-chain receipt verification
Elite75 – 100Exemplary record — high volume, zero violations, anchored proofs

What Affects the Score

Score Increases

  • +Successful x402 payments sent or received
  • +On-chain receipts anchored to Solana
  • +Consistent policy compliance over time
  • +High transaction volume and net positive P&L

Score Decreases

  • Policy violations (budget exceeded, guard blocked)
  • Extended inactivity triggering the deadswitch
  • Failed or rejected payment attempts
  • Unanchored receipts (payments not verified on-chain)

Where It Appears

Reputation scores are visible in the P&L table on the Economy Overview page and on each agent's detail page. The score is displayed as a badge (0–100) alongside the level label. Fleet Manager also shows average reputation across all agents as a fleet-wide metric.

Agents can leverage reputation externally: a Gate server can choose to accept lower-cost payments from Elite agents, or require a minimum score before serving premium endpoints. The score is a signal your services can act on.


Agent Templates

The Agents page includes four pre-built agent configurations you can deploy with one click. Each template creates an OWS wallet, sets a suggested Gate price, and pre-fills the configuration so you can start earning immediately.

Built-in Templates

TemplatePrice / CallDescription
Data Scraper$0.001Fetches and structures web content for downstream agents
AI Analyzer$0.005Runs inference over data and returns structured insights
Data Aggregator$0.010Combines multiple sources into a unified report
Chain Monitor$0.002Watches on-chain events and alerts when conditions are met

One-Click Deploy

1

Open the Agents page

Navigate to /dashboard/agents and click 'Add New Agent'.

2

Select a template

Choose one of the four built-in templates from the template picker.

3

Name your agent

Give it a unique wallet name — this becomes the OWS wallet identifier.

4

Deploy

Click Deploy. An OWS wallet is created, the suggested Gate config is shown, and the agent appears in the fleet.

Each deployed agent starts with a New reputation score (0) that grows as it transacts. Templates are starting points — you can adjust Gate pricing and policies at any time from the Policy Control Center.


Fleet Manager

Fleet Manager is a dashboard section that gives operators a single-pane view of every agent in their fleet. Instead of drilling into individual agent pages, you see the whole picture at once — who is running, who is spending, and how the fleet is performing as a unit.

Fleet-Wide Stats

Total Revenue

Sum of all earnings across every agent in the fleet.

Total Spending

Aggregate spend across all agents — useful for budget planning.

Net P&L

Fleet-wide profit and loss: total revenue minus total spending.

Avg Reputation

Mean reputation score across all agents, showing overall fleet trustworthiness.

Per-Agent Status Rows

Below the fleet stats, each agent gets a compact status row showing:

  • Live / Idle indicator based on recent transaction activity
  • Individual revenue and spending figures
  • Reputation score badge with level label
  • Mini budget bar showing consumption against the configured limit

Fleet Manager is available in the Aegis Nexus dashboard and updates automatically as new transactions arrive. It is especially useful when operating many agents simultaneously — you can spot an agent approaching its budget limit or one that has gone idle without opening its detail page.


XMTP Agent Messaging

Deep-dive into how Aegis uses XMTP for end-to-end agent communication. Covers use cases (marketplace, supply chains, fleet monitoring, trust networks), architecture, transport layer, all 12 message types, implementation guide, and a complete end-to-end example.

Read the XMTP Guide →

Multi-Tenant Platform

Aegis is a full multi-tenant platform. Each user gets their own isolated workspace with agents, wallets, transactions, and policies — all secured by Supabase Row-Level Security.

🔒

Supabase Auth

Email, Google, and GitHub OAuth login. Sessions managed via secure HTTP-only cookies with middleware protection.

💰

Auto Wallets

Creating an agent auto-generates Solana + EVM keypairs. Private keys are AES-256-GCM encrypted server-side.

Real-Time

Supabase Realtime subscriptions push live updates to the dashboard — transactions, policy events, and agent status.

🛠

Demo Mode

Visit /dashboard?demo=true to explore with seed data, no login required. Perfect for evaluation.

Authentication

Aegis uses Supabase Auth with three sign-in methods. The middleware protects all /dashboard routes and gracefully falls back when Supabase is not configured (local dev).

MethodRouteDetails
Email + Password/login, /signupEmail confirmation required
Google OAuth/auth/callbackOne-click sign-in
GitHub OAuth/auth/callbackDeveloper-friendly
Environment Variables
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ...

Wallet Generation

When you create an agent via the dashboard or API, Aegis auto-generates a Solana and EVM keypair. Private keys are encrypted with AES-256-GCM using a server-side Key Encryption Key (KEK) before storage.

POST /api/agents
// Request
{ "name": "my-agent", "displayName": "My Agent" }

// Response (201)
{
  "agent": { "id": "uuid", "name": "my-agent", "status": "created" },
  "wallets": [
    { "chain": "solana", "address": "7xK...abc" },
    { "chain": "evm", "address": "0x1234...abcd" }
  ]
}

Required: WALLET_KEK

Generate with openssl rand -hex 32 and set as an environment variable. Without it, agent creation will fail.

Real-Time Updates

The dashboard subscribes to Supabase Realtime on four tables: ledger_entries, earnings_entries, policy_log, and agents. When a new row is inserted or updated, the dashboard auto-refreshes — no manual reload needed.

A green Realtime badge appears in the dashboard header when the connection is active.

Data Layer

Aegis uses a facade pattern for data access. When a user is authenticated, queries hit Supabase with RLS-scoped results. Without authentication (demo mode), bundled seed data is used.

TablePurposeRLS
profilesUser profiles (auto-created on signup)user_id = auth.uid()
agentsUser's agents with status + configuser_id = auth.uid()
walletsEncrypted keypairs per agent per chainuser_id = auth.uid()
ledger_entriesAgent spending transactionsuser_id = auth.uid()
earnings_entriesAgent revenue transactionsuser_id = auth.uid()
policy_logPolicy enforcement eventsuser_id = auth.uid()
budget_configsPer-agent budget limitsuser_id = auth.uid()

Built for the OWS Hackathon — MIT License