> ## Documentation Index
> Fetch the complete documentation index at: https://ouroborai.xyz/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> How ouroborai processes requests from intent to execution

ouroborai is structured as a Bun + TypeScript monorepo where a Hono API server
orchestrates a Claude-backed agent runner, protocol-specific adapters, and
ERC-4337 smart account infrastructure. This page explains the data flow,
component responsibilities, and design patterns that hold the system together.

## High-Level Data Flow

```
User (Web / Telegram / CLI / MCP)
  |
  |  POST /agent/prompt { prompt, threadId? }
  v
Hono API Server
  |
  |  x402 payment verification ($0.01 USDC)
  |  Nonce uniqueness check (Redis / in-memory)
  v
Agent Runner
  |
  |  Skill detection --> Claude tool-call loop
  |  Thread context loaded from ThreadStore
  v
Protocol Adapters
  |
  |  UniswapV3 | GmxV2 | AaveV3 | RWA | TimeBoost
  |  Build + simulate transactions
  v
ZeroDev Kernel (ERC-4337)
  |
  |  Session key authorization
  |  UserOperation bundling
  v
Arbitrum One / Robinhood Chain (46630)
```

## Request Lifecycle

Every prompt follows this sequence:

<Steps>
  <Step title="Payment gate">
    The `x402` middleware extracts the `X-PAYMENT` header, verifies the USDC
    signature, and checks that the nonce has not been used before (stored in
    Redis with a 24-hour TTL, or in an in-memory set for local development).
  </Step>

  <Step title="Job creation">
    The API creates an async job in the **job queue** and returns a `jobId` +
    `threadId` immediately. The caller polls `GET /agent/job/:id` for results.
  </Step>

  <Step title="Skill detection">
    The agent runner scans the prompt against registered skill definitions.
    Each skill declares a set of trigger keywords and maps to one or more
    adapter tools. Matching skills are loaded into the Claude system prompt as
    available tools.
  </Step>

  <Step title="Claude agent loop">
    Claude receives the prompt, the thread history (if `threadId` was
    provided), and the matched tool definitions. It reasons about the intent
    and emits a sequence of tool calls. The runner executes each tool call
    against the corresponding adapter and feeds results back to Claude until
    the agent produces a final text response.
  </Step>

  <Step title="Adapter execution">
    Each tool call dispatches to a protocol adapter. The adapter builds a
    transaction (or read call), simulates it against the current chain state,
    and either returns data (quotes, balances, health factors) or submits the
    transaction through the smart account.
  </Step>

  <Step title="Response">
    The final agent response and any transaction hashes are written to the
    thread and stored on the job. The client retrieves the completed job with
    the full conversation and execution results.
  </Step>
</Steps>

## Adapter Pattern

Protocol integrations follow a uniform adapter interface. Each adapter
exposes a set of **tools** -- typed functions the agent can call -- and handles
all protocol-specific encoding, simulation, and error handling internally.

| Adapter     | Protocol      | Tools                                          |
| ----------- | ------------- | ---------------------------------------------- |
| `UniswapV3` | Uniswap V3    | `swap`, `quote`, `positions`, `pool_info`      |
| `GmxV2`     | GMX V2        | `open_position`, `close_position`, `positions` |
| `AaveV3`    | Aave V3       | `supply`, `borrow`, `repay`, `health_factor`   |
| `RWA`       | Robinhood RWA | `rwa_scan`, `rwa_quote`, `rwa_trade`           |
| `TimeBoost` | Arbitrum      | `bid_express_lane`, `estimate_mev`             |

Adding a new protocol means implementing the adapter interface and
registering its tools with the skill system. See the
[Add a Protocol](/docs/guides/add-a-protocol) guide.

## Skill System

Skills are the bridge between natural language and adapter tools. Each skill
is defined in a `SKILL.md` markdown file with this structure:

```markdown theme={"theme":{"light":"dracula","dark":"dracula"}}
# Skill: spot-trading

## Triggers
swap, trade, exchange, buy, sell, convert

## Description
Execute token swaps on Uniswap V3 with automatic route optimization.

## Tools
- swap: Execute a token swap
- quote: Get a price quote without executing
```

When a prompt matches a skill's trigger keywords, the runner loads that
skill's tools into the Claude context. Multiple skills can activate for a
single prompt (e.g. "Swap USDC for ARB and supply ARB to Aave" activates
both `spot-trading` and `lending`).

<Info>
  Skills are discovered at startup by scanning the `packages/adapters/src/`
  directory for `SKILL.md` files. No registration code is required.
</Info>

## State Management

The platform uses a **factory pattern** for all stateful services. Each
service has two implementations -- one backed by Redis for production, one
using in-memory data structures for local development -- selected
automatically based on whether `REDIS_URL` is configured.

| Service           | Purpose                              | Redis Key Pattern             |
| ----------------- | ------------------------------------ | ----------------------------- |
| **Job Queue**     | Async job creation, polling, results | `arb:job:{jobId}`             |
| **Thread Store**  | Conversation history per session     | `arb:thread:{threadId}`       |
| **Nonce Tracker** | x402 payment replay protection       | `arb:nonce:{nonce}` (24h TTL) |

Threads are recovered automatically when a `threadId` is passed with a
prompt. The web terminal persists the active `threadId` in `sessionStorage`
so refreshing the browser resumes the same conversation.

## Workspace Structure

The monorepo is organized into **packages** (shared libraries) and **apps**
(deployable services):

```
agent/
  packages/
    sdk/            # Chain config, types, contract addresses
    adapters/       # UniswapV3, GmxV2, AaveV3, RWA, TimeBoost adapters
    timeboost/      # Express lane bidder, MEV estimation
    smart-account/  # ZeroDev Kernel wrapper, session key management
  apps/
    api/            # Hono API server (agent runner, x402 middleware)
    web/            # Next.js 15 web terminal
    telegram/       # Grammy Telegram bot
    mcp-server/     # 15-tool MCP server for Claude Code
  contracts/
    agent-registry/       # On-chain agent registry (Stylus/Rust)
    route-optimizer/      # Multi-DEX route comparison (Stylus/Rust)
    liquidation-monitor/  # Multi-protocol health scanner (Stylus/Rust)
    timeboost-vault/      # Bid funding + resale vault (Stylus/Rust)
```

Build order matters because of workspace dependencies:

1. `packages/sdk` -- no internal dependencies, built first
2. `packages/adapters`, `packages/timeboost`, `packages/smart-account` --
   depend on `sdk`
3. `apps/*` -- depend on one or more packages

<Note>
  External packages `@zerodev/*`, `permissionless`, and `tslib` must be
  marked as externals in the Bun build configuration to avoid bundling issues.
</Note>

## Smart Account Integration

All on-chain transactions are executed through a **ZeroDev Kernel** smart
account (ERC-4337). This provides three key capabilities:

**Session keys** -- The agent operates with a scoped session key that has
limited permissions (specific token allowances, time bounds, spending caps).
The user's root private key never touches the agent runtime.

**UserOperation bundling** -- Multiple actions within a single prompt (e.g.
approve + swap + supply) are bundled into a single UserOperation, saving gas
and ensuring atomicity.

**Spending limits** -- Each session key is configured with per-token and
aggregate spending limits. The smart account contract enforces these limits
on-chain, so even a compromised session key cannot drain the wallet.

```
User Wallet (EOA)
  |
  |  Delegates session key with limits
  v
ZeroDev Kernel (Smart Account)
  |
  |  Validates session key permissions
  |  Bundles UserOperations
  v
Bundler --> Arbitrum One
```

## Stylus Contracts

Performance-critical on-chain logic is implemented in **Stylus** -- Rust
compiled to WASM and executed natively on the Arbitrum VM. These contracts
use dynamic registries (indexed mappings with soft-delete) so new protocols
and DEXes can be added without redeployment.

| Contract              | Purpose                                   | Tests |
| --------------------- | ----------------------------------------- | ----- |
| `agent-registry`      | On-chain agent registry with capabilities | 7     |
| `route-optimizer`     | Multi-DEX route comparison and selection  | 38    |
| `liquidation-monitor` | Multi-protocol health factor scanning     | 43    |
| `timeboost-vault`     | Express lane bid funding and resale       | 27    |

See the [Contracts](/docs/contracts/overview) section for detailed documentation.

## What's Next

<CardGroup cols={2}>
  <Card title="x402 Payments" icon="credit-card" href="/docs/agent-api/x402-payments">
    How the micropayment protocol gates API access.
  </Card>

  <Card title="Skills & Tools" icon="puzzle-piece" href="/docs/agent-api/skills">
    Deep dive into skill detection and tool registration.
  </Card>

  <Card title="MCP Server" icon="server" href="/docs/agent-api/mcp-server">
    Use the 15-tool MCP server from Claude Code or any MCP client.
  </Card>

  <Card title="Contract Methods" icon="file-code" href="/docs/reference/contract-methods">
    Full reference for all Stylus contract interfaces.
  </Card>
</CardGroup>
