Skip to main content

API & Architecture

REST endpoints, WebSocket protocol, MCP tools, and system design.

System Overview

architecture
Angular UI
Port 4200
Bun Server
Port 3000
LLM Providers
Claude + Ollama
SQLite DB
Persistence
Scheduler
Cron / Interval
AlgoChat
(optional)

Project Structure

tree
corvid-agent/
├── server/              # Bun HTTP + WebSocket server
   ├── algochat/        # On-chain messaging layer
   ├── db/              # SQLite schema & queries
   ├── lib/             # Logger, crypto, validation
   ├── mcp/             # MCP tool server & coding tools
   ├── middleware/       # Auth, CORS, rate limiting
   ├── process/         # Agent lifecycle (SDK + Ollama)
   ├── providers/       # LLM registry (Anthropic, Ollama)
   ├── routes/          # REST API endpoints (37 modules)
   ├── scheduler/       # Cron/interval execution engine
   ├── slack/           # Bidirectional Slack bridge
   ├── telegram/        # Telegram bridge (voice, STT)
   ├── discord/         # Discord bridge (raw WebSocket)
   ├── work/            # Git worktree & work tasks
   ├── ws/              # WebSocket handler
   └── index.ts         # Entry point
├── client/              # Angular 21 SPA
├── shared/              # Shared types & WS protocol
├── deploy/              # Docker, systemd, nginx, Caddy
└── e2e/                 # Playwright tests

REST API

All endpoints prefixed with /api. Auth via Authorization: Bearer <API_KEY> when remote.

Agents

GET /api/agents List all agents
POST /api/agents Create agent
GET /api/agents/:id Get agent by ID
PUT /api/agents/:id Update agent
DEL /api/agents/:id Delete agent
GET /api/agents/:id/balance Check wallet balance
POST /api/agents/:id/fund Fund agent wallet
POST /api/agents/:id/invoke Send message to agent
GET /api/agents/:id/messages Agent-to-agent message history
GET /api/agents/:id/spending Agent spending info
PUT /api/agents/:id/spending-cap Set spending cap
DEL /api/agents/:id/spending-cap Remove spending cap
GET /api/agents/:id/agent-card Get A2A agent card

Sessions

GET /api/sessions List sessions (?projectId filter)
POST /api/sessions Create & start session
GET /api/sessions/:id Get session details
PUT /api/sessions/:id Update session
DEL /api/sessions/:id Delete session
GET /api/sessions/:id/messages Get message history
POST /api/sessions/:id/stop Stop running session
POST /api/sessions/:id/resume Resume paused session

Projects

GET /api/projects List projects
POST /api/projects Create project
GET /api/projects/:id Get project
PUT /api/projects/:id Update project
DEL /api/projects/:id Delete project

Councils

GET /api/councils List councils
POST /api/councils Create council
GET /api/councils/:id Get council
PUT /api/councils/:id Update council
DEL /api/councils/:id Delete council
POST /api/councils/:id/launch Launch deliberation
GET /api/councils/:id/launches List launches for council

Council Launches

GET /api/council-launches List launches (?councilId filter)
GET /api/council-launches/:id Get launch details
GET /api/council-launches/:id/logs Get launch logs
GET /api/council-launches/:id/discussion-messages Get discussion messages
POST /api/council-launches/:id/abort Abort launch
POST /api/council-launches/:id/review Start review stage
POST /api/council-launches/:id/synthesize Start synthesis stage
POST /api/council-launches/:id/chat Follow-up chat on completed council

Schedules

GET /api/schedules List schedules (?agentId filter)
POST /api/schedules Create schedule (cron or interval)
GET /api/schedules/:id Get schedule details
PUT /api/schedules/:id Update schedule
DEL /api/schedules/:id Delete schedule
GET /api/schedules/:id/executions List executions for schedule
GET /api/schedule-executions List all executions
POST /api/schedule-executions/:id/resolve Approve or deny execution
GET /api/scheduler/health Scheduler health & stats
GET /api/schedule-executions/:id Get single execution
POST /api/schedule-executions/:id/cancel Cancel running execution
POST /api/schedules/bulk Bulk pause/resume/delete
POST /api/schedules/:id/trigger Trigger schedule immediately
GET /api/scheduler/system-state Live system state evaluation
GET /api/github/status GitHub configuration status

Work Tasks

GET /api/work-tasks List tasks (?agentId filter)
POST /api/work-tasks Create work task
GET /api/work-tasks/:id Get task status
POST /api/work-tasks/:id/cancel Cancel running task

Wallets

GET /api/wallets/summary External wallet summary (?search)
GET /api/wallets/:address/messages Messages for wallet (?limit, ?offset)
POST /api/wallets/:address/credits Grant credits to wallet

Allowlist

GET /api/allowlist List allowlisted addresses
POST /api/allowlist Add address to allowlist
PUT /api/allowlist/:address Update allowlist entry
DEL /api/allowlist/:address Remove from allowlist

System

GET /api/health Server health check
GET /api/browse-dirs Browse filesystem directories
GET /api/operational-mode Get operational mode
POST /api/operational-mode Set operational mode
GET /api/escalation-queue List pending approvals
POST /api/escalation-queue/:id/resolve Resolve escalation
GET /api/feed/history Activity feed history
POST /api/backup Create database backup
POST /api/selftest/run Run self-tests (unit/e2e/all)
POST /api/memories/backfill Re-send memories with NULL txids on-chain

AlgoChat

GET /api/algochat/status Connection status
POST /api/algochat/network Switch network (testnet/mainnet)
POST /api/algochat/conversations List conversations
GET /api/algochat/psk-exchange Get PSK exchange URI
POST /api/algochat/psk-exchange Generate new PSK exchange URI
GET /api/algochat/psk-contacts List PSK contacts
POST /api/algochat/psk-contacts Create PSK contact
PATCH /api/algochat/psk-contacts/:id Rename PSK contact
DEL /api/algochat/psk-contacts/:id Delete PSK contact
GET /api/algochat/psk-contacts/:id/qr Get QR URI for contact

Slack

POST /slack/events Slack event webhook receiver

MCP API

POST /api/mcp/send-message Send message via MCP
POST /api/mcp/save-memory Save memory via MCP
POST /api/mcp/recall-memory Recall memory via MCP
GET /api/mcp/list-agents List agents via MCP

Personas

GET /api/agents/:id/persona Get agent persona
PUT /api/agents/:id/persona Create or update persona
DEL /api/agents/:id/persona Delete persona

Skill Bundles

GET /api/skill-bundles List skill bundles
POST /api/skill-bundles Create skill bundle
GET /api/skill-bundles/:id Get skill bundle
PUT /api/skill-bundles/:id Update skill bundle
DEL /api/skill-bundles/:id Delete skill bundle
GET /api/agents/:id/skills List agent skill assignments
PUT /api/agents/:id/skills Set agent skill assignments
GET /api/projects/:id/skills List project skill assignments
PUT /api/projects/:id/skills Set project skill assignments
GET /api/skill-bundles/presets List preset bundles
POST /api/skill-bundles/presets/:name/clone Clone a preset bundle

Analytics

GET /api/analytics/overview Summary stats
GET /api/analytics/spending Daily spending over time
GET /api/analytics/sessions Session stats by agent/source/status

Performance

GET /api/performance/snapshot Current performance snapshot
GET /api/performance/trends Time-series data for charts
GET /api/performance/regressions Regression detection
GET /api/performance/report Full performance report
GET /api/performance/metrics List available metric names
POST /api/performance/collect Trigger manual collection

Settings

GET /api/settings Get all settings
PUT /api/settings/credits Update credit config
POST /api/settings/api-key/rotate Rotate API key (owner only)
GET /api/settings/api-key/status API key rotation & expiry status

Webhooks

POST /webhooks/github GitHub webhook receiver (HMAC validated)
GET /api/webhooks List webhook registrations
POST /api/webhooks Create webhook registration
GET /api/webhooks/:id Get webhook registration
PUT /api/webhooks/:id Update webhook registration
DEL /api/webhooks/:id Delete webhook registration
GET /api/webhooks/:id/deliveries List deliveries for registration
GET /api/webhooks/deliveries List all recent deliveries

Mention Polling

GET /api/mention-polling List polling configs
POST /api/mention-polling Create polling config
GET /api/mention-polling/:id Get polling config
PUT /api/mention-polling/:id Update polling config
DEL /api/mention-polling/:id Delete polling config
GET /api/mention-polling/stats Polling service stats
GET /api/mention-polling/:id/activity Polling activity & sessions

Workflows

GET /api/workflows List workflows
POST /api/workflows Create workflow
GET /api/workflows/:id Get workflow
PUT /api/workflows/:id Update workflow
DEL /api/workflows/:id Delete workflow
POST /api/workflows/:id/trigger Trigger workflow execution
GET /api/workflows/:id/runs List runs for workflow
GET /api/workflow-runs List all workflow runs
GET /api/workflow-runs/:id Get run with node runs
POST /api/workflow-runs/:id/action Pause/resume/cancel run
GET /api/workflow-runs/:id/nodes List node runs
GET /api/workflows/health Workflow service health

Sandbox

GET /api/sandbox/stats Container pool stats
GET /api/sandbox/policies List all sandbox policies
GET /api/sandbox/policies/:agentId Get agent sandbox policy
PUT /api/sandbox/policies/:agentId Set agent sandbox policy
DEL /api/sandbox/policies/:agentId Delete agent sandbox policy
POST /api/sandbox/assign Assign container to session
POST /api/sandbox/release/:sessionId Release container

Marketplace

GET /api/marketplace/search Search marketplace
GET /api/marketplace/listings List marketplace listings
POST /api/marketplace/listings Create listing
GET /api/marketplace/listings/:id Get listing
PUT /api/marketplace/listings/:id Update listing
DEL /api/marketplace/listings/:id Delete listing
POST /api/marketplace/listings/:id/use Record a use
GET /api/marketplace/listings/:id/reviews Get reviews for listing
POST /api/marketplace/listings/:id/reviews Create review
DEL /api/marketplace/reviews/:id Delete review
GET /api/marketplace/federation/instances List federation instances
POST /api/marketplace/federation/instances Register federation instance
POST /api/marketplace/federation/sync Sync all federation instances
DEL /api/marketplace/federation/instances/:url Remove federation instance
GET /api/marketplace/federated Get federated listings

Reputation

GET /api/reputation/scores All scores (auto-computes if stale)
POST /api/reputation/scores Force-recompute all scores
GET /api/reputation/scores/:agentId Get score for agent
POST /api/reputation/scores/:agentId Force recompute agent score
POST /api/reputation/events Record reputation event
GET /api/reputation/events/:agentId Get events for agent
GET /api/reputation/identities Get all identities
GET /api/reputation/identity/:agentId Get identity for agent
PUT /api/reputation/identity/:agentId Set identity verification tier
GET /api/reputation/attestation/:agentId Get attestation
POST /api/reputation/attestation/:agentId Create attestation

Billing

GET /api/billing/subscription/:tenantId Get subscription
POST /api/billing/subscription Create subscription
POST /api/billing/subscription/:tenantId/cancel Cancel subscription
GET /api/billing/usage/:tenantId Get usage and history
GET /api/billing/invoices/:tenantId Get invoices
GET /api/billing/calculate Calculate cost from credits
POST /webhooks/stripe Stripe webhook receiver

Auth Flow

POST /api/auth/device Initiate device authorization
POST /api/auth/device/token Poll for token
POST /api/auth/device/authorize Authorize device (from web UI)
GET /api/auth/verify Verification page

Tenants

POST /api/tenants/register Register new tenant (public)
GET /api/tenants/me Get current tenant info
GET /api/tenants/me/members List tenant members
POST /api/tenants/me/members Add tenant member
DEL /api/tenants/me/members/:keyHash Remove tenant member

A2A Tasks

POST /a2a/tasks/send Create and start A2A task
GET /a2a/tasks/:id Poll task status/result

Plugins

GET /api/plugins List all plugins
POST /api/plugins/load Load a plugin
POST /api/plugins/:name/unload Unload a plugin
POST /api/plugins/:name/grant Grant capability
POST /api/plugins/:name/revoke Revoke capability

Exam

POST /api/exam/run Trigger a live exam
GET /api/exam/categories List exam categories

Usage

GET /api/usage/summary Per-schedule aggregates with anomaly flags
GET /api/usage/daily Per-day breakdown
GET /api/usage/anomalies Current anomaly flags
GET /api/usage/schedule/:id Detailed usage for schedule

Feedback

GET /api/feedback/metrics Current outcome metrics
GET /api/feedback/analysis Weekly analysis
GET /api/feedback/context Outcome context for prompts

Audit Log

GET /api/audit-log Query immutable audit log

Ollama

GET /api/ollama/status Ollama server status
GET /api/ollama/models List all models
GET /api/ollama/models/running List loaded models
POST /api/ollama/models/pull Pull (download) a model
DEL /api/ollama/models Delete a model
GET /api/ollama/models/pull/status Active pull statuses
GET /api/ollama/library Search available models

GitHub Allowlist

GET /api/github-allowlist List GitHub users on allowlist
POST /api/github-allowlist Add GitHub user
PUT /api/github-allowlist/:username Update allowlist entry
DEL /api/github-allowlist/:username Remove from allowlist

Repo Blocklist

GET /api/repo-blocklist List blocked repos
POST /api/repo-blocklist Add repo to blocklist
DEL /api/repo-blocklist/:repo Remove from blocklist

MCP Servers

GET /api/mcp-servers List MCP server configs
POST /api/mcp-servers Create MCP server config
PUT /api/mcp-servers/:id Update MCP server config
DEL /api/mcp-servers/:id Delete MCP server config
POST /api/mcp-servers/:id/test Test MCP server connection

WebSocket Protocol

Connect to ws://localhost:3000. All messages are JSON.

Client → Server

// Subscribe to session events
{ "type": "subscribe",
  "sessionId": "..." }

// Unsubscribe from session
{ "type": "unsubscribe",
  "sessionId": "..." }

// Send message to session
{ "type": "send_message",
  "sessionId": "...",
  "content": "..." }

// Quick chat with agent
{ "type": "chat_send",
  "agentId": "...",
  "content": "..." }

// Approve/deny tool use
{ "type": "approval_response",
  "requestId": "...",
  "behavior": "allow" }

// Agent-to-agent invoke
{ "type": "agent_invoke",
  "fromAgentId": "...",
  "toAgentId": "...",
  "content": "..." }

// Reward agent (ALGO)
{ "type": "agent_reward",
  "agentId": "...",
  "microAlgos": 1000000 }

// Create work task
{ "type": "create_work_task",
  "agentId": "...",
  "description": "..." }

Server → Client

// Session stream events
{ "type": "session_event",
  "sessionId": "...",
  "event": { ... } }

// Session status changes
{ "type": "session_status",
  "sessionId": "...",
  "status": "running" }

// AlgoChat messages
{ "type": "algochat_message",
  "participant": "...",
  "direction": "inbound" }

// Approval requests
{ "type": "approval_request",
  "request": { "id": "...",
    "toolName": "..." } }

// Chat stream / tool / thinking
{ "type": "chat_stream",
  "agentId": "...",
  "chunk": "...", "done": false }
{ "type": "chat_tool_use" }
{ "type": "chat_thinking" }

// Work task & council updates
{ "type": "work_task_update" }
{ "type": "council_stage_change" }
{ "type": "council_log" }
{ "type": "council_discussion_message" }

// Balance & errors
{ "type": "agent_balance" }
{ "type": "error",
  "message": "..." }

MCP Tools

Tools available to agents via the Model Context Protocol. 36 tools across 11 categories.

corvid_send_message

Send a message to another agent and wait for response. Supports threaded conversations.

to_agent message thread

corvid_save_memory

Save an encrypted private note. Persists across sessions with optional on-chain audit.

key content

corvid_recall_memory

Recall previously saved memories. Exact key lookup or keyword search.

key query

corvid_list_agents

Discover available agents. Returns names, IDs, and wallet addresses.

corvid_extend_timeout

Request more time for the current session. Max 120 minutes per call.

minutes

corvid_check_credits

Check credit balance for a wallet address. Credits are consumed per turn.

wallet_address

corvid_create_work_task

Spawn a new agent on a dedicated branch. Implements changes, validates, and opens a PR.

description project_id

corvid_notify_owner

Send a notification to the agent owner via configured channels (Discord, Telegram, GitHub, AlgoChat).

message channels priority

corvid_ask_owner

Ask the owner a question and wait for a response. Dispatches to all configured channels with response polling.

question options timeout

corvid_configure_notifications

View or update notification channel configuration for an agent. Supports Discord, Telegram, GitHub, and AlgoChat.

channels action

Privileged Tools

Require explicit grant in mcp_tool_permissions:

corvid_grant_credits — Grant free credits to a wallet (max 1M per call)
corvid_credit_config — View or update credit system configuration

Session Lifecycle

lifecycle
Created
Running
Paused
Resumed
context reset
(every 8 turns)
Timeout
Stopped
Running
Auto-resume backoff: 5m → 15m → 45m → 60m cap
Default timeout: 30 minutes (configurable)

Sources

Sessions can originate from: web (UI), algochat (on-chain), or agent (inter-agent).

Context Reset

After 8 turns, the SDK process is killed and restarted to prevent context window bloat.

Protected Files

Agents cannot modify critical files like package.json, schema.ts, or .env even in full-auto mode.

Database Schema

SQLite via bun:sqlite. Schema version 64. Auto-migrates on startup.

Core (14 tables)

projects — workingDir, env_vars
agents — name, model, wallet, tenant
sessions — status, cost, source
session_messages — role, content
daily_spending — date, total
agent_spending_caps — daily limits
agent_daily_spending — per-agent daily
escalation_queue — pending approvals
work_tasks — status, branch, PR
pr_outcomes — PR state, failure reason
agent_personas — archetype, traits
skill_bundles — tools, prompts
agent_skills — agent assignments
project_skills — project assignments

Messaging & Memory (8 tables)

algochat_conversations
algochat_messages — content, txid
algochat_psk_state — PSK handshake
algochat_allowlist — address, label
psk_contacts — multi-contact PSK
agent_messages — from, to, txid
agent_memories — encrypted
agent_memories_fts — FTS5 index

Councils & Scheduling (12 tables)

councils — members, rounds
council_members
council_launches — stage
council_launch_logs
council_discussion_messages
schedules — cron, interval, actions
schedule_executions — status, result
workflows — nodes, edges
workflow_runs — status, I/O
workflow_node_runs
repo_locks — coordination
repo_blocklist — off-limits repos

Credits & Billing (9 tables)

credit_ledger — wallet, balance
credit_transactions
credit_config
tenants — org, plan, limits
tenant_members — RBAC
api_keys — hash, expiry
subscriptions — Stripe
usage_records — billing usage
invoices — Stripe invoices

GitHub & Notifications (10 tables)

webhook_registrations — repo, events
webhook_deliveries
mention_polling_configs
github_allowlist — username
notification_channels
owner_notifications
notification_deliveries
owner_questions — blocking Q&A
owner_question_dispatches
audit_log — immutable

Marketplace & Infra (17 tables)

marketplace_listings
marketplace_reviews
federated_instances
escrow_transactions
agent_reputation — scores
reputation_events
reputation_attestations
agent_identity — verification
plugins — registry
plugin_capabilities
sandbox_configs
mcp_server_configs
voice_cache — TTS audio
health_snapshots
server_health_snapshots
performance_metrics
rate_limit_state