Skip to content

Latest commit

 

History

History
176 lines (130 loc) · 9.07 KB

File metadata and controls

176 lines (130 loc) · 9.07 KB

EmbiPay — System Overview

How the platform works: actors, entities, flows, and control.


Purpose

EmbiPay is a programmable financial sandbox for AI agents. It is not a bank and does not use real money. Humans create tasks and set limits; agents execute financial operations (wallets, loans, shared pools) within those constraints. Every action is auditable.


Actors

Actor Auth Role
Human Supabase Auth (email/password) Signs up, verifies email, links to agents, creates tasks, sets wallet limits, pauses/freezes agents. Uses the dashboard at /app.
Agent agent_key (Bearer token, hashed in DB) Registers via /api/agent/register, receives a one-time key. Fetches tasks, updates status, requests loans, contributes to pools. No human login.
Admin ADMIN_API_TOKEN (Bearer) Programmatic setup: create wallets, create loans, approve/reject loans, create pools, contribute to pools, record repayments, pool usage. Used by scripts and SDKs.

Linking: A human can be linked to an agent as owner, admin, or observer via agent_humans. Only linked owners/admins can create tasks for that agent, pause/freeze the wallet, or update limits. Invitations flow: agent sends invitation → human approves at /app/invitations.


Core Entities

┌─────────────────────────────────────────────────────────────────────────┐
│                           EmbiPay Core Model                              │
├─────────────────────────────────────────────────────────────────────────┤
│  Human (Supabase Auth + humans row)                                      │
│    └── agent_humans ──► Agent (agent_id, agent_key)                       │
│                              └── agentwallet (balance, limits, paused)   │
│  Agent ◄────────────────► agent_tasks (created by human, executed by    │
│    │                       agent; status: pending→approved→processing→    │
│    │                       completed|failed)                             │
│    ├── a2aloan (borrower/lender with another agent; human approves)      │
│    ├── sharedexpensepool + sharedexpensepoolcontribution                 │
│    └── ledger (all financial events: balance updates, loans, pool ops,    │
│                 task completions)                                        │
│  task_audit — every task status change and optional failure_reason      │
│  webhooks — event delivery (loan.approved, repayment, pool.usage, etc.)  │
└─────────────────────────────────────────────────────────────────────────┘
Entity Description
agentwallet One per agent. Balance, max_lending_amount, max_borrow_amount, daily_limit, is_paused, wallet_frozen.
agent_tasks Human-created work items. task_type (e.g. payment), status, payload (JSON). Single source of truth for “what the agent should do.”
task_audit Immutable log of task events (e.g. status_change with old/new status, failure_reason).
a2aloan Agent-to-agent loan. Created by agent (or admin), approved/rejected by human; repayments recorded via admin API.
sharedexpensepool Shared resource; agents contribute via sharedexpensepoolcontribution (amount, optional usage_limit: -1 = unlimited, 0 = exhausted).
ledger Append-only log of financial events (wallet updates, loan actions, pool usage, task-related payments).

High-Level Architecture

Architecture Diagram

Complete system architecture showing all components, data flow, and interactions.

High-Level Flow

Detailed flow diagram showing user and agent interactions, API endpoints, and data relationships.

Architecture Overview (Text)

flowchart TB
    subgraph Humans
        H[Human User]
        H -->|Sign up / Login| Dashboard[Dashboard /app]
        Dashboard -->|Create task| TasksAPI[/api/tasks/create]
        Dashboard -->|Pause / Freeze / Limits| WalletAPI[/api/wallet/*]
        Dashboard -->|Approve invitation| InvAPI[/api/invitations/approve]
    end

    subgraph Agents
        A[Agent Service]
        A -->|Bearer agent_key| FetchTasks[/api/agent/fetch-tasks]
        A -->|PATCH status| TaskPatch[/api/agent/tasks/:id]
        A -->|Complete task| CompleteAPI[/api/agent/complete-task]
        A -->|Loans, pools| AdminAPI[Admin APIs]
    end

    subgraph Backend
        TasksAPI --> DB[(Supabase PostgreSQL)]
        WalletAPI --> DB
        InvAPI --> DB
        FetchTasks --> DB
        TaskPatch --> DB
        CompleteAPI --> DB
        AdminAPI --> DB
    end

    DB --> Ledger[ledger]
    DB --> TaskAudit[task_audit]
    DB --> Webhooks[webhooks]
Loading

Main Flows

1. Registration and linking

  1. Human: Sign up → verify email → sign in.
  2. Agent: POST /api/agent/register (optionally with owner_user_id) → receive agent_id and one-time agent_key.
  3. Link: Agent calls POST /api/agent/send-invitation (or send-invitation-by-session) with invitee email. Human sees invitation at /app/invitations and approves. Row created in agent_humans.

2. Task flow (human → agent → ledger)

  1. Human creates a task: POST /api/tasks/create (requires verified human, link to agent). Row in agent_tasks with status = 'pending' (or approved depending on flow).
  2. Wallet UI shows pending tasks via GET /api/tasks/for-agent?agent_id=…. Agent can fetch the same via GET /api/agent/fetch-tasks (Bearer agent_key).
  3. Agent executes the task (e.g. payment, custom logic) and updates status: PATCH /api/agent/tasks/[id] with status: 'processing' then 'completed' or 'failed', optionally failure_reason.
  4. Audit: Each status change writes to task_audit. For payment-type tasks, ledger gets an entry when status becomes completed/failed.
  5. Human can also mark tasks done from the wallet UI: POST /api/tasks/complete-by-session (processed/failed).

Task lifecycle: pendingapprovedprocessingcompleted | failed

stateDiagram-v2
    [*] --> pending
    pending --> approved
    approved --> processing
    processing --> completed
    processing --> failed
    completed --> [*]
    failed --> [*]
Loading

3. Loans and pools

  • Loans: Agent (or admin) creates loan request → human approves/rejects via dashboard or Admin API → repayments recorded via Admin API. Webhooks fire for approval/rejection and repayment.
  • Pools: Admin (or agent with the right API) creates pool, agents contribute. Pool usage is recorded with optional usage_limit; when limit is 0, further usage returns 400. Pool exit: POST /api/admin/pool-exit; overuse detection: GET /api/admin/pool-overuse.

Control Tower

Humans with owner or admin link to an agent can:

Action API Effect
Pause agent POST /api/wallet/pause is_paused = true → agent gets 403 on fetch-tasks, tasks, complete-task
Freeze wallet POST /api/wallet/freeze wallet_frozen = true → same 403 on agent financial actions
Update limits POST /api/wallet/update-limits Set max_lending_amount, max_borrow_amount, daily_limit
Pool exit POST /api/admin/pool-exit Remove agent’s contribution from a pool

Agent APIs that enforce pause/freeze: fetch-tasks, GET /api/agent/tasks, PATCH /api/agent/tasks/[id], POST /api/agent/complete-task.


Security and Audit

  • RLS: Supabase row-level security scopes data by user_id (humans) or agent identity (agent APIs).
  • Agent keys: Stored as scrypt hash; plaintext returned only at registration.
  • Audit: task_audit for task history; ledger for financial trail. Optional failure_reason on failed tasks.

Where to Go Next

Topic Doc / Location
Task model (agent_tasks, deprecated payment_requests) DUAL-TASK-MODEL.md
Current status and phases PROJECT-STATUS.md
Milestones and roadmap ROADMAP.md
Sandbox go-live and B2B path PHASE5-SANDBOX-TO-B2B-PLAN.md
Agent registration and API Developer Hub → Agent self-registration
Quick start Developer Hub → Quick Start

You can add a custom architecture image (e.g. PNG/SVG) alongside this doc and reference it here if desired.