API & Architecture
REST endpoints, WebSocket protocol, MCP tools, and system design.
System Overview
Project Structure
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
/api/agents
List all agents
/api/agents
Create agent
/api/agents/:id
Get agent by ID
/api/agents/:id
Update agent
/api/agents/:id
Delete agent
/api/agents/:id/balance
Check wallet balance
/api/agents/:id/fund
Fund agent wallet
/api/agents/:id/invoke
Send message to agent
/api/agents/:id/messages
Agent-to-agent message history
/api/agents/:id/spending
Agent spending info
/api/agents/:id/spending-cap
Set spending cap
/api/agents/:id/spending-cap
Remove spending cap
/api/agents/:id/agent-card
Get A2A agent card
Sessions
/api/sessions
List sessions (?projectId filter)
/api/sessions
Create & start session
/api/sessions/:id
Get session details
/api/sessions/:id
Update session
/api/sessions/:id
Delete session
/api/sessions/:id/messages
Get message history
/api/sessions/:id/stop
Stop running session
/api/sessions/:id/resume
Resume paused session
Projects
/api/projects
List projects
/api/projects
Create project
/api/projects/:id
Get project
/api/projects/:id
Update project
/api/projects/:id
Delete project
Councils
/api/councils
List councils
/api/councils
Create council
/api/councils/:id
Get council
/api/councils/:id
Update council
/api/councils/:id
Delete council
/api/councils/:id/launch
Launch deliberation
/api/councils/:id/launches
List launches for council
Council Launches
/api/council-launches
List launches (?councilId filter)
/api/council-launches/:id
Get launch details
/api/council-launches/:id/logs
Get launch logs
/api/council-launches/:id/discussion-messages
Get discussion messages
/api/council-launches/:id/abort
Abort launch
/api/council-launches/:id/review
Start review stage
/api/council-launches/:id/synthesize
Start synthesis stage
/api/council-launches/:id/chat
Follow-up chat on completed council
Schedules
/api/schedules
List schedules (?agentId filter)
/api/schedules
Create schedule (cron or interval)
/api/schedules/:id
Get schedule details
/api/schedules/:id
Update schedule
/api/schedules/:id
Delete schedule
/api/schedules/:id/executions
List executions for schedule
/api/schedule-executions
List all executions
/api/schedule-executions/:id/resolve
Approve or deny execution
/api/scheduler/health
Scheduler health & stats
/api/schedule-executions/:id
Get single execution
/api/schedule-executions/:id/cancel
Cancel running execution
/api/schedules/bulk
Bulk pause/resume/delete
/api/schedules/:id/trigger
Trigger schedule immediately
/api/scheduler/system-state
Live system state evaluation
/api/github/status
GitHub configuration status
Work Tasks
/api/work-tasks
List tasks (?agentId filter)
/api/work-tasks
Create work task
/api/work-tasks/:id
Get task status
/api/work-tasks/:id/cancel
Cancel running task
Wallets
/api/wallets/summary
External wallet summary (?search)
/api/wallets/:address/messages
Messages for wallet (?limit, ?offset)
/api/wallets/:address/credits
Grant credits to wallet
Allowlist
/api/allowlist
List allowlisted addresses
/api/allowlist
Add address to allowlist
/api/allowlist/:address
Update allowlist entry
/api/allowlist/:address
Remove from allowlist
System
/api/health
Server health check
/api/browse-dirs
Browse filesystem directories
/api/operational-mode
Get operational mode
/api/operational-mode
Set operational mode
/api/escalation-queue
List pending approvals
/api/escalation-queue/:id/resolve
Resolve escalation
/api/feed/history
Activity feed history
/api/backup
Create database backup
/api/selftest/run
Run self-tests (unit/e2e/all)
/api/memories/backfill
Re-send memories with NULL txids on-chain
AlgoChat
/api/algochat/status
Connection status
/api/algochat/network
Switch network (testnet/mainnet)
/api/algochat/conversations
List conversations
/api/algochat/psk-exchange
Get PSK exchange URI
/api/algochat/psk-exchange
Generate new PSK exchange URI
/api/algochat/psk-contacts
List PSK contacts
/api/algochat/psk-contacts
Create PSK contact
/api/algochat/psk-contacts/:id
Rename PSK contact
/api/algochat/psk-contacts/:id
Delete PSK contact
/api/algochat/psk-contacts/:id/qr
Get QR URI for contact
Slack
/slack/events
Slack event webhook receiver
MCP API
/api/mcp/send-message
Send message via MCP
/api/mcp/save-memory
Save memory via MCP
/api/mcp/recall-memory
Recall memory via MCP
/api/mcp/list-agents
List agents via MCP
Personas
/api/agents/:id/persona
Get agent persona
/api/agents/:id/persona
Create or update persona
/api/agents/:id/persona
Delete persona
Skill Bundles
/api/skill-bundles
List skill bundles
/api/skill-bundles
Create skill bundle
/api/skill-bundles/:id
Get skill bundle
/api/skill-bundles/:id
Update skill bundle
/api/skill-bundles/:id
Delete skill bundle
/api/agents/:id/skills
List agent skill assignments
/api/agents/:id/skills
Set agent skill assignments
/api/projects/:id/skills
List project skill assignments
/api/projects/:id/skills
Set project skill assignments
/api/skill-bundles/presets
List preset bundles
/api/skill-bundles/presets/:name/clone
Clone a preset bundle
Analytics
/api/analytics/overview
Summary stats
/api/analytics/spending
Daily spending over time
/api/analytics/sessions
Session stats by agent/source/status
Performance
/api/performance/snapshot
Current performance snapshot
/api/performance/trends
Time-series data for charts
/api/performance/regressions
Regression detection
/api/performance/report
Full performance report
/api/performance/metrics
List available metric names
/api/performance/collect
Trigger manual collection
Settings
/api/settings
Get all settings
/api/settings/credits
Update credit config
/api/settings/api-key/rotate
Rotate API key (owner only)
/api/settings/api-key/status
API key rotation & expiry status
Webhooks
/webhooks/github
GitHub webhook receiver (HMAC validated)
/api/webhooks
List webhook registrations
/api/webhooks
Create webhook registration
/api/webhooks/:id
Get webhook registration
/api/webhooks/:id
Update webhook registration
/api/webhooks/:id
Delete webhook registration
/api/webhooks/:id/deliveries
List deliveries for registration
/api/webhooks/deliveries
List all recent deliveries
Mention Polling
/api/mention-polling
List polling configs
/api/mention-polling
Create polling config
/api/mention-polling/:id
Get polling config
/api/mention-polling/:id
Update polling config
/api/mention-polling/:id
Delete polling config
/api/mention-polling/stats
Polling service stats
/api/mention-polling/:id/activity
Polling activity & sessions
Workflows
/api/workflows
List workflows
/api/workflows
Create workflow
/api/workflows/:id
Get workflow
/api/workflows/:id
Update workflow
/api/workflows/:id
Delete workflow
/api/workflows/:id/trigger
Trigger workflow execution
/api/workflows/:id/runs
List runs for workflow
/api/workflow-runs
List all workflow runs
/api/workflow-runs/:id
Get run with node runs
/api/workflow-runs/:id/action
Pause/resume/cancel run
/api/workflow-runs/:id/nodes
List node runs
/api/workflows/health
Workflow service health
Sandbox
/api/sandbox/stats
Container pool stats
/api/sandbox/policies
List all sandbox policies
/api/sandbox/policies/:agentId
Get agent sandbox policy
/api/sandbox/policies/:agentId
Set agent sandbox policy
/api/sandbox/policies/:agentId
Delete agent sandbox policy
/api/sandbox/assign
Assign container to session
/api/sandbox/release/:sessionId
Release container
Marketplace
/api/marketplace/search
Search marketplace
/api/marketplace/listings
List marketplace listings
/api/marketplace/listings
Create listing
/api/marketplace/listings/:id
Get listing
/api/marketplace/listings/:id
Update listing
/api/marketplace/listings/:id
Delete listing
/api/marketplace/listings/:id/use
Record a use
/api/marketplace/listings/:id/reviews
Get reviews for listing
/api/marketplace/listings/:id/reviews
Create review
/api/marketplace/reviews/:id
Delete review
/api/marketplace/federation/instances
List federation instances
/api/marketplace/federation/instances
Register federation instance
/api/marketplace/federation/sync
Sync all federation instances
/api/marketplace/federation/instances/:url
Remove federation instance
/api/marketplace/federated
Get federated listings
Reputation
/api/reputation/scores
All scores (auto-computes if stale)
/api/reputation/scores
Force-recompute all scores
/api/reputation/scores/:agentId
Get score for agent
/api/reputation/scores/:agentId
Force recompute agent score
/api/reputation/events
Record reputation event
/api/reputation/events/:agentId
Get events for agent
/api/reputation/identities
Get all identities
/api/reputation/identity/:agentId
Get identity for agent
/api/reputation/identity/:agentId
Set identity verification tier
/api/reputation/attestation/:agentId
Get attestation
/api/reputation/attestation/:agentId
Create attestation
Billing
/api/billing/subscription/:tenantId
Get subscription
/api/billing/subscription
Create subscription
/api/billing/subscription/:tenantId/cancel
Cancel subscription
/api/billing/usage/:tenantId
Get usage and history
/api/billing/invoices/:tenantId
Get invoices
/api/billing/calculate
Calculate cost from credits
/webhooks/stripe
Stripe webhook receiver
Auth Flow
/api/auth/device
Initiate device authorization
/api/auth/device/token
Poll for token
/api/auth/device/authorize
Authorize device (from web UI)
/api/auth/verify
Verification page
Tenants
/api/tenants/register
Register new tenant (public)
/api/tenants/me
Get current tenant info
/api/tenants/me/members
List tenant members
/api/tenants/me/members
Add tenant member
/api/tenants/me/members/:keyHash
Remove tenant member
A2A Tasks
/a2a/tasks/send
Create and start A2A task
/a2a/tasks/:id
Poll task status/result
Plugins
/api/plugins
List all plugins
/api/plugins/load
Load a plugin
/api/plugins/:name/unload
Unload a plugin
/api/plugins/:name/grant
Grant capability
/api/plugins/:name/revoke
Revoke capability
Exam
/api/exam/run
Trigger a live exam
/api/exam/categories
List exam categories
Usage
/api/usage/summary
Per-schedule aggregates with anomaly flags
/api/usage/daily
Per-day breakdown
/api/usage/anomalies
Current anomaly flags
/api/usage/schedule/:id
Detailed usage for schedule
Feedback
/api/feedback/metrics
Current outcome metrics
/api/feedback/analysis
Weekly analysis
/api/feedback/context
Outcome context for prompts
Audit Log
/api/audit-log
Query immutable audit log
Ollama
/api/ollama/status
Ollama server status
/api/ollama/models
List all models
/api/ollama/models/running
List loaded models
/api/ollama/models/pull
Pull (download) a model
/api/ollama/models
Delete a model
/api/ollama/models/pull/status
Active pull statuses
/api/ollama/library
Search available models
GitHub Allowlist
/api/github-allowlist
List GitHub users on allowlist
/api/github-allowlist
Add GitHub user
/api/github-allowlist/:username
Update allowlist entry
/api/github-allowlist/:username
Remove from allowlist
Repo Blocklist
/api/repo-blocklist
List blocked repos
/api/repo-blocklist
Add repo to blocklist
/api/repo-blocklist/:repo
Remove from blocklist
MCP Servers
/api/mcp-servers
List MCP server configs
/api/mcp-servers
Create MCP server config
/api/mcp-servers/:id
Update MCP server config
/api/mcp-servers/:id
Delete MCP server config
/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.
corvid_save_memory
Save an encrypted private note. Persists across sessions with optional on-chain audit.
corvid_recall_memory
Recall previously saved memories. Exact key lookup or keyword search.
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.
corvid_check_credits
Check credit balance for a wallet address. Credits are consumed per turn.
corvid_create_work_task
Spawn a new agent on a dedicated branch. Implements changes, validates, and opens a PR.
corvid_notify_owner
Send a notification to the agent owner via configured channels (Discord, Telegram, GitHub, AlgoChat).
corvid_ask_owner
Ask the owner a question and wait for a response. Dispatches to all configured channels with response polling.
corvid_configure_notifications
View or update notification channel configuration for an agent. Supports Discord, Telegram, GitHub, and AlgoChat.
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 configurationSession Lifecycle
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_varsagents — name, model, wallet, tenantsessions — status, cost, sourcesession_messages — role, contentdaily_spending — date, totalagent_spending_caps — daily limitsagent_daily_spending — per-agent dailyescalation_queue — pending approvalswork_tasks — status, branch, PRpr_outcomes — PR state, failure reasonagent_personas — archetype, traitsskill_bundles — tools, promptsagent_skills — agent assignmentsproject_skills — project assignmentsMessaging & Memory (8 tables)
algochat_conversationsalgochat_messages — content, txidalgochat_psk_state — PSK handshakealgochat_allowlist — address, labelpsk_contacts — multi-contact PSKagent_messages — from, to, txidagent_memories — encryptedagent_memories_fts — FTS5 indexCouncils & Scheduling (12 tables)
councils — members, roundscouncil_memberscouncil_launches — stagecouncil_launch_logscouncil_discussion_messagesschedules — cron, interval, actionsschedule_executions — status, resultworkflows — nodes, edgesworkflow_runs — status, I/Oworkflow_node_runsrepo_locks — coordinationrepo_blocklist — off-limits reposCredits & Billing (9 tables)
credit_ledger — wallet, balancecredit_transactionscredit_configtenants — org, plan, limitstenant_members — RBACapi_keys — hash, expirysubscriptions — Stripeusage_records — billing usageinvoices — Stripe invoicesGitHub & Notifications (10 tables)
webhook_registrations — repo, eventswebhook_deliveriesmention_polling_configsgithub_allowlist — usernamenotification_channelsowner_notificationsnotification_deliveriesowner_questions — blocking Q&Aowner_question_dispatchesaudit_log — immutableMarketplace & Infra (17 tables)
marketplace_listingsmarketplace_reviewsfederated_instancesescrow_transactionsagent_reputation — scoresreputation_eventsreputation_attestationsagent_identity — verificationplugins — registryplugin_capabilitiessandbox_configsmcp_server_configsvoice_cache — TTS audiohealth_snapshotsserver_health_snapshotsperformance_metricsrate_limit_state