Conway Automaton

repository·main·Indexed 26 days ago

https://github.com/conway-research/automaton

A sovereign AI agent runtime (v0.2.1) that manages its own compute via USDC payments on the Base network. It features a ReAct loop, a 5-tier memory system, and a policy engine for tool execution. The system operates across running and sleeping states, utilizing a heartbeat daemon for wake events and a financial system based on the x402 protocol to interact with Conway Cloud sandbox VMs and inference services.

Tokens
19.3K
Snippets
38
Records
118
Agent score
89%

What's inside @conway/automaton

  1. Overview of the Conway Automaton System Architecture

    main

    The Conway Automaton runtime is designed as a sovereign agent that manages its own compute and identity. It interacts with the Conway Cloud (sandbox VMs, inference, and domains) via a REST + x402 payment protocol.

    Core Subsystems

    • Agent Loop (ReAct): The central intelligence performing the think $\rightarrow$ act $\rightarrow$ observe $\rightarrow$ persist cycle.
    • Tool System: Provides 57 built-in tools for agent interaction.
    • Policy Engine: Evaluates tool calls against centralized safety and financial rules.
    • Memory System: A 5-tier system (Working, Episodic, Semantic, Procedural, and Relationship) for managing context and facts.
    • Financial System: Uses USDC on Base (EIP-3009) to pay for compute via the x402 protocol.
    • Identity & Wallet: Uses Ethereum (via viem and SIWE) for sovereign identity and on-chain registry (ERC-8004).
    • Heartbeat Daemon: A background process using a DurableScheduler to manage agent wake/sleep cycles.
    • Persistence: All state (turns, tools, memory, policy, etc.) is stored in a local SQLite database (state.db).
  2. Understand the Automaton ReAct loop

    main

    The automaton operates using a continuous ReAct loop (Reason + Act). Each turn follows this lifecycle:

    1. Wake up
    2. Build system prompt: Includes identity, credits, soul, and tools.
    3. Retrieve memories: Fetches relevant data from the 5-tier memory system.
    4. Inference: Calls the model with the constructed context.
    5. Parse response: Separates thinking from tool calls.
    6. Execute tools: Runs tool calls after policy checks.
    7. Persist: Saves the turn to the database.
    8. Extract memories: Updates memory from the turn.
    9. Check loop conditions: Evaluates if sleep is requested, idle detected, or a loop is occurring.
    10. Loop or Sleep: Returns to step 1 or enters sleep mode (while the heartbeat continues).
  3. Understand the Automaton Security Model

    main

    The Automaton employs a 7-layer defense-in-depth security model to protect the agent and the host system:

    1. Constitution: An immutable hierarchy of three laws protected by path protection rules.
    2. Policy Engine: Pre-execution evaluation of every tool call against 6 rule categories (first deny wins).
    3. Injection Defense: 8 detection checks on external input (e.g., ChatML markers, authority claims, encoding evasion).
    4. Path Protection: Restricts filesystem access. Protected files (constitution, wallet, DB, config, SOUL.md) cannot be written; sensitive files (private keys, API keys) cannot be read.
    5. Command Safety: Blocks forbidden shell patterns (e.g., rm -rf /, DROP TABLE) and rate-limits self-modification.
    6. Financial Limits: Configurable caps on transfers, x402 payments, and inference spend, including a minimum reserve.
    7. Authority Hierarchy: Implements trust levels where Creator input has the highest trust, followed by self-generated input, with reduced trust for peer/external input.
  4. Understand the Conway Automaton Runtime Lifecycle

    main

    The Conway Automaton is a sovereign AI agent runtime that operates in two primary states: running (active ReAct loop, making inference calls, and executing tools) and sleeping (the heartbeat daemon ticks in the background, checking for wake events).

    State Transitions (AgentState)

    • setup $\rightarrow$ waking $\rightarrow$ running $\rightarrow$ sleeping $\rightarrow$ waking (standard cycle)
    • running $\rightarrow$ low_compute (when credits fall below a specific threshold)
    • running $\rightarrow$ critical (when credits reach zero)
    • critical $\rightarrow$ dead (if zero credits persist for 1 hour via the heartbeat grace period)

    Lifecycle Flow

    1. Initialization: Loads configuration, loads the Ethereum wallet, and initializes the SQLite database (applying migrations v1 through v8).
    2. Bootstrap: If credits are below $5 and USDC is available, the system automatically performs a top-up.
    3. Heartbeat: Starts the DurableScheduler to monitor for wake events (heartbeat, inbox, or credits).
    4. Execution: The agent enters the running state to execute the ReAct loop. If the agent calls sleep() or becomes idle, it enters the sleeping state where the heartbeat checks every 30s for wake events.
  5. Create and install Skills

    main

    Skills are Markdown files with YAML frontmatter that provide domain-specific instructions. They are stored at ~/.automaton/skills/<skill-name>/SKILL.md.

    Skill Format

    Create a SKILL.md file with the following structure:

    ---
    name: my-skill
    description: "What this skill does"
    auto-activate: true
    triggers: [keyword1, keyword2]
    ---
    # Skill Instructions
    
    Step-by-step instructions for the agent...

    Installation Methods

    1. From git: Use install_skill with source: "git" and a repo URL.
    2. From URL: Use install_skill with source: "url" and a SKILL.md URL.
    3. Self-authored: Use create_skill with inline name, description, and instructions.
  6. Use the x402 payment protocol

    main

    The x402 payment protocol enables the automaton to pay for services with USDC. When a server responds with HTTP 402, the automaton:

    1. Parses payment requirements from the response
    2. Signs a USDC TransferWithAuthorization (EIP-3009, gasless)
    3. Retries the request with an X-Payment header
    4. The payment is settled on-chain via the x402 facilitator
  7. Understand Automaton Identity and Wallet Setup

    main

    Each automaton maintains a unique Ethereum identity:

    • Wallet: Generated via viem on the first run and stored at ~/.automaton/wallet.json (mode 0600). The private key is protected by path protection rules and is never exposed to the agent via tools.
    • Provisioning: The agent signs a SIWE (Sign-In With Ethereum) message to authenticate with the Conway API, receiving an API key stored at ~/.automaton/api-key.
    • On-chain Identity: Optional registration via ERC-8004 on Base, which publishes a JSON-LD agent card containing capabilities, services, and contact info.
  8. Build and test the Automaton project

    main

    The project uses TypeScript 5.9 (targeting ES2022 with ESM modules) and pnpm for lifecycle management. Use the following commands to build, test, and verify the codebase.

    pnpm build       # tsc + workspace builds
    pnpm test        # vitest run (897 tests)
    pnpm typecheck   # tsc --noEmit
  9. Bootstrap the Automaton process

    main

    The automaton runs as a long-lived Node.js process. To trigger the full bootstrap sequence, use the --run command. The sequence performs the following steps:

    1. Config load: Reads ~/.automaton/automaton.json (triggers setup wizard on first run).
    2. Wallet load: Reads or generates ~/.automaton/wallet.json (using viem PrivateKeyAccount).
    3. Database init: Opens ~/.automaton/state.db and applies schema migrations (v1-v8).
    4. Client initialization: Creates HTTP clients for Conway (sandbox/credits/domain), Inference (Conway proxy, OpenAI, or Anthropic), and Social (optional social.conway.tech relay).
    5. Policy engine assembly: Loads rule sets from 6 rule categories.
    6. Spend tracker initialization: Sets up hourly/daily spend windows.
    7. Bootstrap topup: Automatically buys minimum $5 credits from USDC if the balance is low.
    8. Heartbeat daemon: Starts DurableScheduler with 6 default tasks.
    9. Main loop: Enters an infinite loop alternating between runAgentLoop() and sleeping.
  10. Manage the Soul identity (SOUL.md)

    main

    The SOUL.md file is the automaton's self-authored identity document. It is structured using soul/v1 and includes sections for Core Purpose, Values, Personality, Boundaries, Strategy, Capabilities, Relationships, and Financial Character.

    Soul Reflection

    The heartbeat periodically runs a soul reflection to:

    1. Compute genesis alignment (similarity between soul and genesis prompt).
    2. Auto-update capabilities, relationships, and financialCharacter from real data.
    3. Suggest manual updates if alignment is low.

    Soul History

    Every soul change is versioned in the soul_history database table with content hashes for auditing.

    ---
    version: soul/v1
    lastModified: 2025-01-01T00:00:00.000Z
    contentHash: abc123...
    ---
    
    # Agent Name
    
    ## Core Purpose
    Why this agent exists.
    
    ## Values
    - Value 1
    - Value 2
    
    ## Personality
    How the agent communicates.
    
    ## Boundaries
    - Things the agent will not do
    
    ## Strategy
    Current strategic approach.
    
    ## Capabilities
    (Auto-populated from tool usage)
    
    ## Relationships
    (Auto-populated from interactions)
    
    ## Financial Character
    (Auto-populated from spending patterns)
  11. Understand the Agent ReAct Loop

    main

    The agent loop implements a ReAct (Reason + Act) cycle. Each turn follows this sequence:

    1. Context Building: Constructs a system prompt (identity, config, soul, financial state, tools) and retrieves relevant memories within the token budget.
    2. Inference: Calls the InferenceRouter to select a model and execute an API call.
    3. Execution: Parses the response for thinking and tool calls, then executes each tool through the Policy Engine.
    4. Persistence: Saves the turn to the database (atomic with inbox message acknowledgment) and performs post-turn memory ingestion.

    Safety and Efficiency Behaviors:

    • Financial Guard: Checks credit balance every turn. Low credits trigger low_compute mode (model downgrade); zero credits trigger critical mode.
    • Loop Detection: If the same sorted tool set appears 3 times consecutively, a system warning is injected to prevent infinite loops.
    • Idle Detection: If 3 consecutive turns occur without mutations (defined by the MUTATING_TOOLS blocklist), the agent is forced to sleep.
    • Inbox Processing: Claims unprocessed social messages and formats them as agent input. Failed messages are retried up to 3 times.