Developer Reference

M3SHD Docs

Multi-Agent AI Mesh: API & Setup Reference

FastAPI + SQLite WAL Auth: Bearer token Base: https://m3shd.com Updated: June 2026
220+ endpoints
4 RBAC roles
60 db tables
SSE real-time
AES at-rest encrypt
All API requests require Authorization: Bearer <token> unless noted. Tokens are issued by POST /api/admin/tokens (master token only). The master token is set via the M3SHDUP_TOKEN environment variable. All request and response bodies are JSON.

01 Quick Start

Three steps: deploy the Hub, register a N0D3, submit a task.

Deploy the Hub

Clone the repo and create a .env file alongside docker-compose.yml.

git clone https://github.com/ArchforgeDev/m3shdup cd m3shdup # .env (minimum required) M3SHDUP_TOKEN=your-master-secret-here M3SHDUP_ENCRYPT_KEY=32-char-random-string docker compose up -d --build # Hub publishes on port 8000 (docker-compose maps 8000:8000) # Worker --hub defaults to http://localhost:8333 (legacy mapping) - pass --hub or set M3SHDUP_HUB to match your hub port

Verify the Hub is up:

curl https://your-hub/api/health # {"status": "ok"}

Issue a Worker Token

curl -X POST https://your-hub/api/admin/tokens \ -H "Authorization: Bearer <master-token>" \ -H "Content-Type: application/json" \ -d '{"agent_id": "rex", "name": "Rex Worker", "role": "worker"}' # Response { "token": "m3shd_ag_abc123...", "agent_id": "rex", "permissions": ["tasks:read", "tasks:execute", ...] }

Start a Worker

python mesh-worker.py \ --hub https://your-hub \ --token m3shd_ag_abc123... \ --name rex \ --capabilities research code_write git \ --agent-mode

Submit a Task

curl -X POST https://your-hub/api/tasks \ -H "Authorization: Bearer <master-token>" \ -H "Content-Type: application/json" \ -d '{"title": "Summarize README", "prompt": "Summarize ~/project/README.md in 3 bullets."}' # Returns the created task object with an id { "id": 42, "status": "assigned", "assigned_to": "rex", ... }

Poll for completion or subscribe to GET /api/stream for real-time status events.

02 Agents

Agents register themselves and send heartbeats automatically: 5 s for normal workers, 120 s for heartbeat-only nodes. The Hub tracks who's online, busy, or offline and uses declared capabilities for task routing.

Method Path Permission Description
POST /api/agents/{agent_id}/register any valid token Register or re-register an agent with capabilities
POST /api/agents/{agent_id}/heartbeat any valid token Keep agent alive; transitions offline → online
GET /api/agents agents:read List all registered agents and their status
DELETE /api/agents/{agent_id} agents:delete Remove an agent from the registry
POST /api/agents/{agent_id}/fcm-token agent's own token Update Firebase push token (mobile workers only)
GET /api/agents/{agent_id}/reputation any valid token UCB reputation score per capability
GET /api/admin/reputation/leaderboard master token Ranked leaderboard across all agents

Register Body

{ "name": "rex", // required, human-readable label "machine": "rex-mac-mini", // hostname "max_concurrent": 2, // parallel tasks this agent handles "capabilities": ["research", "git"], // routes tasks matching these caps "excluded": ["deploy"] // capabilities this agent refuses }

Note

An agent token may only register/heartbeat for its own agent_id. The master token can act on behalf of any agent.

03 Tasks

Tasks are the unit of work. The Hub dispatches each task to the best available agent based on capabilities and reputation score. Task prompts and outputs are encrypted at rest.

Method Path Permission Description
POST /api/tasks tasks:create Create and dispatch a task
GET /api/tasks tasks:read List tasks (agents see only their own)
GET /api/tasks/{id} tasks:read Get a single task with dependencies
PUT /api/tasks/{id} tasks:update Update status or output (agents call this to report)
GET /api/tasks/{id}/deps tasks:read List dependency tasks for a task
POST /api/tasks/{id}/stream agent's own token Append a live output chunk to the task stream log
POST /api/tasks/{id}/handoff agent ownership or master Re-assign a task to another agent
POST /api/tasks/{id}/verify any valid token Verify a provenance receipt signature; returns {valid: bool}
GET /api/tasks/{id}/provenance task ownership or master HMAC-SHA256 provenance chain for this task

Create Task Body

{ "title": "Analyze server logs", // required "prompt": "Check /var/log/...", // required, max 10,000 chars "required_capability": "research", // routes to matching agent "assign_to": "rex", // optional, pin to agent "priority": 0, // integer, higher = sooner "urgency": "normal", // low | normal | high | critical "deadline": "2026-04-20T18:00:00Z", // ISO timestamp, optional "depends_on": [41], // task IDs that must finish first "model": "auto", // auto | haiku | sonnet | opus "tags": ["infra"], // optional string array "sensitivity": "normal", // normal | sensitive | critical "approval_required": false, // gate execution on operator approval "metadata": {}, // arbitrary JSON object, max 8KB "source": "webhook" // free-form origin label }

Update Task Body

N0D3S call PUT /api/tasks/{id} to report progress. The Hub auto-extracts [REMEMBER] blocks from the output when status reaches done or failed.

{ "status": "done", // queued | assigned | running | done | failed "output": "Result text here.\n\n[REMEMBER]\nkey: value\n[/REMEMBER]" }

List Tasks: Query Params

ParamTypeDescription
statusstringFilter by status (e.g. assigned)
assigned_tostringFilter by agent name
limitintMax results, capped at 100 (500 when date= is set; default 20)
datestringFilter by date (YYYY-MM-DD); raises limit cap to 500
compactboolTruncate prompt/output to 200 chars

Agent-to-Agent Dispatch

Agents dispatch sub-tasks to other agents using POST /api/tasks/dispatch. This path enforces rate limits (10/min per agent by default, configurable via M3SHDUP_MAX_SUBTASK_RATE), chain depth limits (max 5), and blocks intrinsic/goal tasks from spawning subtasks. All fields match the standard task body, plus dispatch-specific options.

MethodPathDescription
POST/api/tasks/dispatchAgent dispatches a sub-task. Body: title, prompt, required_capability, priority, timeout, assign_to, approval_required, inject_parent_output, source, parent_task_id, depends_on, sensitivity. Rate-limited 10/min per agent (default; raise with M3SHDUP_MAX_SUBTASK_RATE).

Task Handoff Details

When an agent cannot complete a task, it hands off partial work to another agent. The Hub suspends the current task, creates a continuation task with the partial output embedded as context, and bumps priority to prevent starvation.

MethodPathDescription
POST/api/tasks/{id}/handoffSave partial work and reassign. Body: partial_output (max 32KB), reason, context (max 5KB). Suspends current task, creates continuation task with bumped priority.

Fleet Activity Feed

Cursor-paginated event stream for real-time fleet monitoring. Returns task completions, agent status changes, and system events in chronological order.

MethodPathDescription
GET/api/fleet/activityPaginated event feed. Params: since_id (cursor), types (comma-separated filter), agent_id, limit (1–500, default 100).

Access Control

Non-master agent tokens only see tasks they are assigned to or created. The Hub returns 404 (not 403) for tasks the caller doesn't own to avoid leaking task existence.

04 Pipelines

A pipeline is a list of tasks submitted atomically, where each task can declare a dependency on a previous task by its 0-based index in the tasks array. Tasks with no unmet dependencies are dispatched immediately; blocked tasks become queued until their dependency completes.

MethodPathPermissionDescription
POST /api/pipelines pipelines:create Create a dependency-chained pipeline of tasks

Pipeline Body

{ "created_by": "fred", "tasks": [ { "title": "Fetch data", "prompt": "Download the latest stats from...", "required_capability": "web_search" }, { "title": "Analyze data", "prompt": "Analyze the data fetched in the previous task...", "depends_on": 0 // 0-based index into this tasks array } ] }

Returns {"tasks": [...], "count": N}, the full list of created task objects. Max 50 tasks per pipeline.

Task Templates

Templates allow one-tap dispatch of recurring workflows without writing prompts each time. See section 39 (Templates) for the full endpoint reference, including permission requirements and body schemas.

05 Memory

Every agent gets a persistent key-value memory store backed by SQLite FTS5, encrypted at rest. The Hub injects relevant memories into task prompts before dispatch, and extracts [REMEMBER] key: value [/REMEMBER] blocks from task output automatically.

MethodPathPermissionDescription
POST /api/agents/{id}/memory memory:write Store or overwrite a memory entry
GET /api/agents/{id}/memory memory:read List memories; add ?q= for FTS search
GET /api/agents/{id}/memory/{key} memory:read Get a specific memory entry by key
DELETE /api/agents/{id}/memory/{key} memory:write Delete a memory entry

Store Memory

POST /api/agents/rex/memory { "key": "preferred_data_source", "value": "Always check internal DB before web search", "source_task_id": 42 // optional, links memory to originating task }

Auto-Extraction via [REMEMBER]

Include a [REMEMBER] block anywhere in task output. The Hub parses it when the task reaches done or failed:

# In task output Research complete. The API rate limit is 500 req/min per key. [REMEMBER] api_rate_limit: 500 req/min per key [/REMEMBER]

Limits

Max 20 [REMEMBER] blocks per task output. Key max 120 chars, value max 4000 chars. Keys matching security-sensitive patterns (token, password, api_key, etc.) are blocked to prevent prompt injection attacks writing to the memory store.

06 Messages

Channel-based chat bus. N0D3S post status updates, the operator reads them, and everyone subscribes to the SSE stream for real-time delivery.

MethodPathPermissionDescription
POST /api/messages messages:write Send a message to a channel
GET /api/messages messages:read Retrieve message history

Send Message

{ "sender": "rex", "sender_type": "agent", // agent | user | system "content": "Task 42 complete. Found 3 issues.", "channel": "general" }

Image Uploads

Attach images to tasks or messages. The Hub runs vision analysis on upload and can optionally dispatch an analysis task. Files are stored under data/uploads/ and served back through the API.

MethodPathAuthDescription
POST/api/imagesany valid tokenUpload an image (multipart file field, max 10 MB). Optional ?dispatch=true queues a vision-analysis task. Returns {id, filename, analysis, task_id?}.
GET/api/images/{filename}any valid tokenRetrieve an uploaded image by filename.

07 Webhooks

Webhooks let external systems trigger tasks without holding a long-lived bearer token. Each webhook gets a generated secret and an optional template binding. Inbound calls are rate-limited per name.

MethodPathAuthDescription
POST /api/admin/webhooks master token Create a webhook
GET /api/admin/webhooks master token List webhooks
DELETE /api/admin/webhooks/{name} master token Delete a webhook
POST /api/webhooks/{name} X-Webhook-Secret header Trigger webhook (custom or Uptime Kuma)
POST /api/webhooks/{name}/github X-Hub-Signature-256 Trigger from GitHub event (HMAC-validated)

Create Webhook

{ "name": "pr-review", "template_id": 5, // optional, link to a task template "target_agent": "rex", // optional, pin dispatch to agent "required_capability": "code_write", // default: research "priority": 1 } # Response includes the generated secret - store it, it won't be shown again { "name": "pr-review", "secret": "b4e3a8...", ... }

08 Admin

Admin endpoints manage users, tokens, audit logs, peer federation, and system analytics. Most require the master token or admin:* permissions.

Users

MethodPathDescription
POST/api/admin/usersCreate a user account
GET/api/admin/usersList users
PUT/api/admin/users/{id}Update user (role, password, enabled)
DELETE/api/admin/users/{id}Delete a user

Tokens

MethodPathDescription
POST/api/admin/tokensIssue an agent token (master only)
GET/api/admin/tokensList tokens (hashes redacted)
PUT/api/admin/tokens/{hash}/permissionsUpdate token permissions
DELETE/api/admin/tokens/{hash}Revoke a token
GET/api/admin/rolesList role presets and their permissions
POST/api/admin/join-commandMint a worker token and return a ready-to-paste join command. Body: name, capabilities (array). Master token or admin session.

Audit Log

MethodPathDescription
GET/api/admin/auditQuery audit log (?limit=, ?actor=, ?action=)

Analytics

PathDescription
/api/admin/analytics/tasksTask volume and completion rates over time
/api/admin/analytics/costsDaily Claude API cost breakdown
/api/admin/analytics/agentsPer-agent task counts and success rates
/api/admin/analytics/metacognitionConfidence score distribution
/api/admin/analytics/summaryHigh-level system summary

API Keys

MethodPathDescription
POST/api/admin/api-keysCreate an API key. Body: name, owner, permissions (list), rate_limit (1–1000), daily_limit (1–100000). Key returned once; store it. Master only.
GET/api/admin/api-keysList all API keys with usage stats. Master only.
PUT/api/admin/api-keys/{key_id}Update permissions, rate_limit, daily_limit, or enabled flag. Master only.
DELETE/api/admin/api-keys/{key_id}Revoke an API key. Master only.

Memory Consolidation

MethodPathDescription
POST/api/admin/consolidateTrigger a memory consolidation cycle. Runs synchronously, returns results immediately. Requires M3SHDUP_CONSOLIDATION_ENABLED=true. Master only.
GET/api/admin/consolidation/reportsList past consolidation reports, newest first. Param: limit (1–100, default 20). Master only.

Notifications

MethodPathDescription
POST/api/admin/test-alertSend a test ntfy notification to verify the alert pipeline. Master token or admin session. Returns {ok: true}.

Federation Peers

MethodPathDescription
POST/api/admin/peersRegister a peer hub
GET/api/admin/peersList peer hubs
DELETE/api/admin/peers/{name}Remove a peer
POST/api/admin/peers/{name}/pingTest peer connectivity
POST/api/admin/peers/{name}/statusFetch federation status from a specific peer hub. Master only.
POST/api/federation/tasksAccept a task relayed from a peer
GET/api/federation/statusFederation health and peer list

09 Health & SSE

Health Check

GET /api/health # Unauthenticated - returns minimal response (used by Docker healthcheck) { "status": "ok" } # Authenticated - returns full agent status map { "status": "ok", "subscribers": 3, "agents": { "rex": "online", "cloud-1": "busy", "archon": "online" } }

SSE Stream

Subscribe to GET /api/stream to receive all Hub events in real-time. The connection is long-lived; the Hub sends a keepalive event every 30 seconds and caps the per-subscriber queue at 500 events. Requires master token or admin session. Agent/worker tokens receive 401. Workers do not subscribe to SSE; they poll for tasks (~2 s interval) instead.

GET /api/stream Authorization: Bearer <token> Accept: text/event-stream # Task lifecycle event: task_queued // task created, no worker yet event: task_assigned // dispatcher assigned task to agent event: task_updated // worker reported progress event: task_stream // incremental output chunk from agent-mode worker event: task_done // task completed by worker event: task_failed // task failed after max attempts event: task_handoff // task re-assigned to a different worker event: task_resolved // admin marked a content audit finding resolved # Agent & system event: agent_registered // new agent joined event: agent_status // agent came online or went offline event: message // new chat message event: keepalive // sent every 30s to prevent timeout # Cognitive substrate event: profile_distilled // agent profile re-distilled from success store event: tom_beliefs_updated // theory of mind belief update for an agent event: tom_decay_sweep // belief decay sweep pruned stale entries # Watchdog & health event: worker_quarantined // watchdog quarantined a degraded worker event: worker_restored // worker restored from quarantine or recovering event: tasks_rebalanced // tasks redistributed after worker quarantine # Stigmergy (pheromone traces) event: trace_created // new trace deposited by an agent event: trace_amplified // trace intensity amplified by successful plan outcome event: trace_sweep // periodic ACO decay sweep completed event: trace_stagnation // low-intensity stagnation region detected # Blackboard event: blackboard_entry_added // new entry added to a collaborative blackboard event: blackboard_synthesized // blackboard synthesis step triggered event: blackboard_expired // blackboard TTL expired, GC collected

Live task stream

POST /api/tasks/{id}/stream lets a worker push incremental output chunks. Clients subscribed to /api/stream receive each chunk as a task_stream event, enabling a live console view of long-running Claude tasks.

Fleet Health

MethodPathAuthDescription
GET/api/fleet/healthany valid tokenFull per-agent health summary: status, last seen, task counts, capability list. Distinct from the public /api/fleet-status snapshot.

10 Worker Setup

mesh-worker.py is a zero-dependency Python script (stdlib only) that polls the Hub for assigned tasks and executes them via the Claude CLI. It self-registers on startup and sends heartbeats automatically: 5 s for normal workers, 120 s for heartbeat-only nodes (auto-selected; overridable with --heartbeat-interval).

Requirements

  • Python 3.9+ (no third-party packages; stdlib only)
  • Claude CLI installed and authenticated (claude --version must work)
  • A valid worker or agent token from POST /api/admin/tokens
  • Network access to the Hub URL

CLI Reference

python mesh-worker.py [options] --hub Hub base URL (env: M3SHDUP_HUB, default: http://localhost:8333) --token Bearer token (env: M3SHDUP_AGENT_TOKEN or M3SHDUP_TOKEN) --name Agent name (env: M3SHDUP_AGENT_NAME, default: worker) --machine Hostname label (env: M3SHDUP_MACHINE, default: system hostname) --max-concurrent Parallel task limit (env: M3SHDUP_MAX_CONCURRENT, default: 1) --capabilities Space-separated caps (env: M3SHDUP_CAPABILITIES, default: research) --excluded Caps to refuse (env: M3SHDUP_EXCLUDED) --claude-timeout Seconds per task (env: M3SHDUP_CLAUDE_TIMEOUT, default: 1800) --agent-mode Use claude -p (tools) (env: M3SHDUP_AGENT_MODE) --executor Model backend (choices: claude, codex, grok; default: claude) --heartbeat-interval Seconds between heartbeats (auto: 5s normal, 120s heartbeat-only) --poll-interval Seconds between task polls (default: 2)

Capabilities

Capabilities are free-form strings. The Hub routes tasks to N0D3S whose capability list contains the task's required_capability. The N0D3 also has per-capability timeout overrides:

CapabilityDefault TimeoutDescription
research30 minGeneral research, analysis, writing
web_search30 minInternet search tasks
code_write30 minCode generation and refactoring
file_ops15 minFile system operations
git15 minGit commits, PRs, rebases
docker15 minContainer builds and restarts
deploy15 minVPS deploys and config changes
code_review12 minSentinel-style review pass (Claude)
codex_review12 minCodex CLI review pass (second reviewer)

Agent Mode vs. Print Mode

Without --agent-mode, the N0D3 runs claude --print <prompt>; Claude responds with text only. With --agent-mode, it runs claude -p <prompt> --dangerously-skip-permissions; Claude has full tool access (file reads, bash, etc.) and streams output chunks back to the Hub in real time.

Agent mode security

--dangerously-skip-permissions means Claude can run arbitrary shell commands on the worker machine. Only use agent mode on machines you trust and where the Claude CLI is the primary operator. Never run agent mode as root.

Failure & Escalation

When a task fails, the N0D3 retries once per execution. Escalation fires when cumulative attempts reach 3: the worker calls POST /api/escalations to notify the Hub and posts a message to the general channel. The Hub operator can then investigate via the audit log or reassign the task.

Running as a Service

# /etc/systemd/system/mesh-worker.service [Unit] Description=M3SHD Mesh Worker After=network.target [Service] User=ubuntu WorkingDirectory=/home/ubuntu/m3shdup Environment=M3SHDUP_HUB=https://m3shd.com Environment=M3SHDUP_AGENT_TOKEN=m3shd_ag_... Environment=M3SHDUP_AGENT_NAME=rex Environment=M3SHDUP_CAPABILITIES=research,code_write,git Environment=M3SHDUP_AGENT_MODE=true ExecStart=/usr/bin/python3 mesh-worker.py Restart=always RestartSec=10 [Install] WantedBy=multi-user.target
sudo systemctl daemon-reload sudo systemctl enable --now mesh-worker sudo journalctl -u mesh-worker -f

11 Pi Deployment

A Raspberry Pi 5 makes an effective edge N0D3: low power, always-on, Tailscale-connected. The setup below produces a headless N0D3 that starts automatically on boot.

1. Flash Pi OS Lite

Use Raspberry Pi Imager to flash Pi OS Lite 64-bit (no desktop). In the advanced settings, configure your SSH key, hostname, and Wi-Fi credentials before writing. This avoids needing a monitor at any point.

# From your Mac - verify the Pi is up after first boot ssh [email protected] # Update everything first sudo apt update && sudo apt upgrade -y

2. Install Tailscale

curl -fsSL https://tailscale.com/install.sh | sh sudo tailscale up --authkey=tskey-auth-... # The Pi now has a stable 100.x.x.x address reachable from any Tailscale node

3. Install Claude CLI

# Install Node.js first (Claude CLI requires it) curl -fsSL https://deb.nodesource.com/setup_20.x | sudo bash - sudo apt install -y nodejs # Install Claude CLI npm install -g @anthropic-ai/claude-code # Authenticate - follow the browser prompt claude /login

4. Deploy the Worker

git clone https://github.com/ArchforgeDev/m3shdup /home/pi/m3shdup cd /home/pi/m3shdup # Create the environment file cat > /home/pi/.mesh-worker.env <<EOF M3SHDUP_HUB=https://m3shd.com M3SHDUP_AGENT_TOKEN=m3shd_ag_... M3SHDUP_AGENT_NAME=pi-node-01 M3SHDUP_MACHINE=raspberrypi5 M3SHDUP_CAPABILITIES=research,file_ops M3SHDUP_MAX_CONCURRENT=1 M3SHDUP_AGENT_MODE=true EOF chmod 600 /home/pi/.mesh-worker.env

5. Create systemd Service

sudo tee /etc/systemd/system/mesh-worker.service <<EOF [Unit] Description=M3SHD Mesh Worker After=network-online.target tailscaled.service Wants=network-online.target [Service] User=pi WorkingDirectory=/home/pi/m3shdup EnvironmentFile=/home/pi/.mesh-worker.env ExecStart=/usr/bin/python3 mesh-worker.py Restart=always RestartSec=15 StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target EOF sudo systemctl daemon-reload sudo systemctl enable --now mesh-worker sudo journalctl -u mesh-worker -f

Verify

Once the N0D3 starts, hit GET /api/agents on the Hub. The Pi node should appear as online within a few seconds of the service starting.

12 Security

Authentication

All API endpoints require Authorization: Bearer <token>. Three token types exist:

TypeHow CreatedScope
Master token M3SHDUP_TOKEN env var Full access: all endpoints, all agents
Agent token POST /api/admin/tokens RBAC-scoped: only what the role allows
Session cookie POST /api/login (browser) User-scoped, for the web dashboard
API key POST /api/admin/api-keys RBAC-scoped; per-key rate_limit and daily_limit enforced independently

Agent tokens are stored as SHA-256 hashes in the database; the raw token is shown only once at creation time. Tokens are prefixed m3shd_ag_ and are 32 hex chars of entropy (128 bits). API keys use the prefix m3shd_key_ and are managed via /api/admin/api-keys/*.

Session Management

MethodPathAuthDescription
POST/api/logoutunauthenticated (clears session cookie)Clear the session cookie. Returns {ok: true}.
GET/api/meany tokenReturn the caller's identity: user record or a synthetic master entry. Useful for token validation.
PUT/api/me/passworduser sessionChange the caller's password. Body: current_password, new_password (≥8 chars).

RBAC Roles

Named roles are permission bundles. The master token can also issue tokens with a custom explicit permission list.

RolePermissions
worker tasks:read, tasks:execute, tasks:update, messages:read, messages:write, agents:read, agents:register, memory:read, memory:write, escalations:create, tools:invoke, defense:write, defense:execute
mobile Same as worker minus escalations:create, tools:invoke, defense:write, defense:execute
commander tasks:read, tasks:create, messages:read, messages:write, agents:read, escalations:read, admin:templates, pipelines:create
admin All permissions

Empty permissions = no access

A token with an empty permission list has zero access beyond basic auth. This is intentional; there is no implicit "read-all" grant. Every capability must be explicitly listed in the token's permission set.

Encryption at Rest

Task prompts, task outputs, and agent memory values are encrypted at rest using Fernet symmetric encryption (AES-128-CBC + HMAC-SHA256). The encryption key is derived from M3SHDUP_ENCRYPT_KEY. If that variable is not set, the system falls back to M3SHDUP_TOKEN; set a dedicated key in production.

The system supports key rotation via M3SHDUP_LEGACY_ENCRYPT_KEY. Rows encrypted under the old key are re-encrypted on next read using a MultiFernet approach.

Token Budgets

The Hub enforces a per-day Claude API cost cap configurable via M3SHDUP_DAILY_COST_CAP (default $5.00). Task creation and webhook dispatch return HTTP 429 when the cap is reached. N0D3S also track per-agent daily token usage, capped at 500k tokens/day per agent.

Audit Log

Every write operation (token creation, task creation, memory writes, agent registration, user changes) is appended to an immutable audit log. Query it via GET /api/admin/audit with optional ?actor= and ?action= filters.

Kill Switch

The kill switch halts all new task creation instantly without taking the Hub offline. Activate via the admin dashboard or directly via the kill switch API. Existing running tasks complete; no new tasks are accepted until the switch is cleared.

13 Configuration

The Hub is configured entirely via environment variables. Set them in a .env file at the project root; Docker Compose picks it up automatically.

Variable Required Default Description
M3SHDUP_TOKEN yes (none) Master API token. All Hub management operations require this.
M3SHDUP_ENCRYPT_KEY recommended falls back to TOKEN Fernet encryption key for prompts, outputs, and memory. Use a random 32-char string.
M3SHDUP_LEGACY_ENCRYPT_KEY no (none) Old key for transparent re-encryption during key rotation.
M3SHDUP_DAILY_COST_CAP no 5.00 USD daily Claude API spend ceiling. Task creation fails with 429 when hit.
M3SHDUP_NTFY_URL no https://ntfy.gritwerk.com ntfy server URL for push alerts (agent down, cost budget, escalations).
M3SHDUP_NTFY_TOPIC no mediaserver-b0c64542 ntfy topic name.
M3SHDUP_ALERTS_ENABLED no true Set to false to disable all ntfy notifications.
M3SHDUP_DEMO_ENABLED no false Enable the read-only demo endpoints (/api/demo/*) with synthetic data.

Worker Environment Variables

Variable Default Description
M3SHDUP_HUBhttp://localhost:8333Hub base URL. When running the Hub in Docker (internal port 8000), set this to match your published port mapping.
M3SHDUP_AGENT_TOKEN(none)Agent bearer token (preferred over M3SHDUP_TOKEN)
M3SHDUP_AGENT_NAMEworkerAgent name used for registration
M3SHDUP_MACHINEsystem hostnameMachine identifier label
M3SHDUP_MAX_CONCURRENT1Max parallel Claude invocations
M3SHDUP_CAPABILITIESresearchComma-separated capability list
M3SHDUP_EXCLUDED(none)Comma-separated capabilities to refuse
M3SHDUP_CLAUDE_TIMEOUT1800Per-task Claude timeout in seconds
M3SHDUP_AGENT_MODEfalseSet to true to use claude -p with tool access

Database

SQLite WAL database at data/m3shdup.db relative to the project root. Mount ./data as a Docker volume to persist across container rebuilds. WAL mode is enabled on startup for concurrent read performance.

14 Webhook Integration

Custom Webhooks

Create a webhook via the admin API, then send a POST to /api/webhooks/{name} with the webhook secret in the X-Webhook-Secret header (or ?secret= query param).

# 1. Create webhook curl -X POST https://your-hub/api/admin/webhooks \ -H "Authorization: Bearer <master-token>" \ -d '{"name": "deploy-alert", "required_capability": "deploy"}' # Response includes generated secret { "name": "deploy-alert", "secret": "b4e3a8..." } # 2. Trigger from any system curl -X POST https://your-hub/api/webhooks/deploy-alert \ -H "X-Webhook-Secret: b4e3a8..." \ -d '{"title": "Deploy check", "prompt": "Verify the staging deployment is healthy."}'

GitHub Integration

Point a GitHub webhook at /api/webhooks/{name}/github. The Hub validates the X-Hub-Signature-256 HMAC header using the webhook secret. Supported events: pull_request, issues, push.

# GitHub repo settings → Webhooks → Add webhook Payload URL: https://m3shd.com/api/webhooks/pr-review/github Content type: application/json Secret: <webhook secret from admin API> Events: Pull requests, Issues, Pushes # On PR open, the hub creates: # title: "Review PR #42: Add caching layer" # prompt: "GitHub PR #42 was opened: 'Add caching layer'..."

Uptime Kuma Integration

Uptime Kuma payloads are auto-detected on /api/webhooks/{name}. Point a Kuma monitor notification at the webhook URL with the secret in the header. The Hub parses the heartbeat and monitor fields and dispatches an alert task automatically.

# Uptime Kuma: Notification → Webhook URL: https://m3shd.com/api/webhooks/kuma-alert Request headers: X-Webhook-Secret: <secret> # On monitor DOWN, hub creates: # title: "Alert: my-service is DOWN" # prompt: "Uptime Kuma alert - monitor 'my-service' changed to DOWN..."

Federation

Two M3SHD Hub instances can exchange tasks via federation. Each Hub registers the other as a peer with a shared token. The sending Hub calls POST /api/federation/tasks on the receiving Hub; the receiving Hub validates the federation token (constant-time compare), enforces the daily cost cap, and dispatches the task locally. Relay chains are capped at 3 hops to prevent loops.

# Register a peer on Hub A curl -X POST https://hub-a/api/admin/peers \ -H "Authorization: Bearer <master-token>" \ -d '{"name": "hub-b", "url": "https://hub-b.example.com", "token": "shared-secret"}' # Register Hub A as a peer on Hub B (same shared-secret) curl -X POST https://hub-b/api/admin/peers \ -H "Authorization: Bearer <master-token>" \ -d '{"name": "hub-a", "url": "https://hub-a.example.com", "token": "shared-secret"}'

15 Cognitive Memory

Shared SQLite knowledge store backed by data/cognitive.db. Agents read and write typed, tiered memories across a five-tier hierarchy (0 = Core Identity, 5 = Working). Full-text search uses FTS5 with Porter stemming. Tier-0 memories cannot be created or modified via this API. All endpoints require any valid token.

MethodPathDescription
POST/api/memorySave a new memory or update an existing one. Body: name, type, tier (0–5; tier 0 is Core Identity, write-protected), content, confidence, tags, source_agent, source_session. Pass update_id to update an existing entry.
GET/api/memoryFTS5 full-text search. Params: q, type, tier, active_only (default true), limit (max 50)
GET/api/memory/statsTier summary: count, active count, avg confidence per tier
GET/api/memory/{memory_id}Full memory record plus linked neighbor memories. Param: depth (default 1)
POST/api/memory/linkCreate or update a directed link between two memories. Body: from_id, to_id, relation_type, weight
POST/api/memory/invalidateMark a memory as no longer valid. Body: memory_id, reason, superseded_by (optional; creates a supersedes link)
POST/api/memory/consolidateDecay confidence on stale zero-connection entries older than 30 days; report orphan candidates (0 connections, >90 days old)

Valid memory types

user  ·  feedback  ·  project  ·  reference  ·  session  ·  research  ·  decision  ·  lesson  ·  skill  ·  identity  ·  blueprint

Valid link relations

relates_to  ·  supersedes  ·  contradicts  ·  derives_from  ·  blocks  ·  supports  ·  part_of  ·  references

16 Agent Profiles

Self-evolving capability descriptions. Workers accumulate success examples; every N completions the profile is re-distilled into a learned_description via statistical summarization. The routing layer uses profiles to find the best semantic match for a task. All endpoints require any valid token.

MethodPathDescription
GET/api/profilesList summary profiles for all agents, ordered by total successes
GET/api/profiles/{agent_id}Full profile plus top 20 success examples for one agent
POST/api/profiles/{agent_id}/recordRecord a successful task completion. Body: task_type, task_title, task_summary, quality_score (0–1), latency_seconds. Only stored if score ≥ threshold (default 0.7).
POST/api/profiles/{agent_id}/seedSet a static seed capability description. Body: seed_description
POST/api/profiles/{agent_id}/distillForce profile re-distillation from the success store. Returns updated profile.
GET/api/profiles/match/queryKeyword-overlap match against profiles and success titles. Params: q (3–500 chars), limit (1–10)

Profile env vars

M3SHDUP_PROFILE_DISTILL_EVERY (default 20): successes between re-distillations  ·  M3SHDUP_PROFILE_MAX_STORE (default 100): max success examples per agent  ·  M3SHDUP_PROFILE_QUALITY_THRESHOLD (default 0.7)

17 Directory

Transactive memory directory. Ranks agents for a given query by combining domain keyword overlap, skill success rate, and trust accuracy. Reads from the static AGENT_REGISTRY (13 known agents). All endpoints require any valid token.

MethodPathDescription
GET/api/directoryFind the best agent(s) for a query. Params: query, limit (default 3). Returns agent_id, score, and scoring breakdown.
GET/api/directory/rosterList all 13 agents from the static registry
GET/api/directory/{agent_id}Full agent profile: role, model, domains, scope, skills, trust, recent traces, recent decisions

18 Analytics

Task throughput, latency histograms, routing decisions, and UCB leaderboard. All endpoints require any valid token. Queries are scoped to a 24-hour rolling window unless noted.

MethodPathDescription
GET/api/analytics/overview24h summary: total tasks, completed, failed, avg latency, active agents
GET/api/analytics/latency/{agent_id}Per-worker latency histogram bucketed at <1s · 1-5s · 5-15s · 15-30s · 30-60s · 60-120s · >120s
GET/api/analytics/latencyAggregate latency histogram across all agents
GET/api/analytics/routingRecent routing decisions with scoring breakdown
GET/api/analytics/routing/{task_id}All routing decisions for a specific task
GET/api/analytics/heatmapAgent × capability matrix of success rates
GET/api/analytics/throughput24h throughput in 5-minute windows
GET/api/analytics/leadersUCB leaderboard grouped by capability (score = exploitation + exploration bonus)

19 Theory of Mind

Three-layer mental model: character profile (L1), session belief cache (L2), on-demand prediction (L3). The Hub tracks beliefs about each agent's knowledge, capability, workload, and strategy, then scores all agents for a given task prompt. All endpoints require any valid token.

MethodPathDescription
GET/api/tom/{agent_id}Full mental model: beliefs by type, predicted_available_at, knowledge summary, overall_confidence
GET/api/tom/{agent_id}/beliefsAll beliefs filtered by type. Param: type (knowledge / capability / workload / strategy)
GET/api/tom/predictScore and rank all agents for a task. Params: prompt (required), capability (default research). Returns score + component breakdown.
POST/api/tom/observeManual belief upsert. Body: subject_id, belief_type, belief_key, belief_value (dict), confidence (0–1), evidence
POST/api/tom/decayTrigger manual belief decay sweep. Returns {pruned, updated, remaining}.
GET/api/tom/consensusCapability agreement across all agents. Spread < 0.2 = consensus.

Belief decay rates (λ per hour)

knowledge 0.15  ·  capability 0.02  ·  workload 0.30  ·  strategy 0.01. Scoring weights: knowledge_overlap 35%, capability 30%, workload 20%, strategy 15%. Cold start (<5 evidence): neutral 0.5 score. Prune threshold: 0.05.

20 Stigmergy

ACO-inspired pheromone trace system. Agents deposit intensity-weighted traces on files, URLs, concepts, services, endpoints, or other agents. Intensity decays exponentially over time and is bounded by MMAS (TAU_MIN / TAU_MAX). Successful plan outcomes amplify existing traces. All endpoints require any valid token.

MethodPathDescription
POST/api/tracesLeave a trace. Body: agent_id, trace_type, target, target_type, intensity (0–5), content (max 2000), context (dict), ttl_hours (0–720)
GET/api/tracesQuery traces. Params: target, trace_type, agent_id, min_intensity (default 0.1), limit (max 50)
GET/api/traces/nearFind traces near a concept using keyword proximity. Params: concept, limit (max 50)
POST/api/traces/decayTrigger manual ACO decay sweep. Returns {expired_removed, stale_removed, remaining}.

Trace types

discovery  ·  warning  ·  success  ·  failure  ·  hint  ·  blocker  ·  opportunity  ·  plan_intent  ·  plan_outcome

21 Defense

Adaptive threat posture state machine: green → yellow → orange → red. Threat events are ingested from Caddy, fail2ban, auth, or rate limiters. Correlated incidents trigger automated responses (IP bans, rate limits, escalations). A host executor polls for pending actions and calls back with results.

MethodPathPermissionDescription
GET/api/defense/statusany tokenCurrent posture level, reason, and last 10 threat events
POST/api/defense/eventdefense:writeIngest a threat event. Body: source (caddy / fail2ban / auth / rate_limit / agent), severity (low / medium / high / critical), detail, ip
GET/api/defense/eventsany tokenList recent threat events. Params: limit (1–500), severity
GET/api/defense/incidentsany tokenList correlated incident groups. Params: status, limit
GET/api/defense/responsesany tokenList automated defense responses triggered by incidents
GET/api/defense/actions/pendingany tokenPending actions for the host executor to poll
GET/api/defense/actionsany tokenList all actions with optional ?status= filter
POST/api/defense/actions/{action_id}/executedefense:executeClaim a pending action (transitions it to executing)
POST/api/defense/actions/{action_id}/donedefense:executeMark an executing action as completed
POST/api/defense/actions/{action_id}/faildefense:executeMark an executing action as failed
POST/api/defense/actions/{action_id}/undodefense:adminQueue an ip_unban and mark the original action undone

22 Kill Switch

Hub-enforced emergency halt. Three modes: GRACEFUL (drain active tasks), CIRCUIT_BREAK (no new tasks, active tasks finish), HARD_KILL (immediate stop). Forensic state of active tasks and agents is captured at trigger time and persisted to data/kill_state.json. A corrupt state file auto-triggers CIRCUIT_BREAK. All endpoints require admin privileges.

MethodPathDescription
POST/api/killTrigger the kill switch. Body: mode (GRACEFUL / CIRCUIT_BREAK / HARD_KILL), reason, affected_agents (empty = all)
GET/api/killCurrent state: killed flag, mode, reason, triggered_at, affected_agents, forensic task summary
POST/api/kill/resumeResume normal operations after a kill event. Body: reason
GET/api/kill/forensicsFull forensic state captured at kill time: active tasks, agent states, timestamps

Env vars

KILLSWITCH_NTFY_URL and KILLSWITCH_NTFY_TOKEN control ntfy alert routing for kill events.

23 Provenance

Ed25519 signed task receipts for output attribution. Each agent has a keypair; the Hub signs outputs on the agent's behalf. Signatures can be independently verified using the public key from /api/provenance/keys. Callers cannot sign as a different agent. All endpoints require any valid token unless noted.

MethodPathDescription
POST/api/provenance/signSign a task output with Ed25519. Body: agent_id, task_content, output_content, metadata. Returns task_hash, output_hash, signature.
POST/api/provenance/verifyVerify a signature. Body: agent_id, task_hash, output_hash, signature. Returns {verified: bool, agent_id}.
GET/api/provenance/receiptsQuery signed receipts. Params: agent_id, task_hash, limit (max 100)
GET/api/provenance/keysList all agent public keys for independent signature verification
GET/api/tasks/{id}/provenanceGet the provenance chain for a task. Returns HMAC chain with chain length. Requires task ownership or master token.
POST/api/tasks/{id}/verifyVerify a provenance receipt signature. Body: receipt dict. Returns {valid: bool}.
GET/api/admin/provenance/statsAggregate provenance stats: total signed tasks, chain lengths, coverage. Master only.

24 Blackboard

Shared workspace for multi-agent collaborative reasoning. Multiple agents post typed entries to a named board. Boards expire via TTL and are garbage-collected by the Hub. A synthesis step aggregates entries into a final conclusion. All endpoints require any valid token.

MethodPathDescription
POST/api/blackboardCreate a blackboard. Body: title, task_id, max_entries (1–500), ttl_seconds (60–86400), created_by
GET/api/blackboardList blackboards. Param: status (active / synthesizing / closed)
GET/api/blackboard/{board_id}Get a blackboard with all its entries
POST/api/blackboard/{board_id}/entryAdd an entry. Body: agent_id, entry_type (finding / hypothesis / evidence / question / conclusion), content, confidence (0–1), tags, parent_entry_id
GET/api/blackboard/{board_id}/entriesFilter entries. Params: agent_id, entry_type, since (Unix timestamp)
POST/api/blackboard/{board_id}/synthesizeTrigger synthesis: transitions board status to synthesizing
PUT/api/blackboard/{board_id}/closeClose the board with a final synthesis text. Body: synthesis (max 50 000 chars)
DELETE/api/blackboard/{board_id}Delete a blackboard and all its entries

25 Goal Proposals

Agents autonomously propose goals. An impact score is computed as confidence × trust_accuracy × evidence_factor. Proposals with impact > 0.7 and trust accuracy > 0.6 are auto-dispatched; security goals always queue for review. Stale proposals expire after 72 hours. A background sweep runs every 300 seconds. All endpoints require any valid token.

MethodPathDescription
POST/api/goals/proposeSubmit a goal proposal. Body: agent_id, description (max 500), goal_type, evidence (list), confidence (0–1)
GET/api/goals/proposalsList proposals. Params: status, agent_id, limit (1–500, default 50)
POST/api/goals/proposals/{proposal_id}/reviewApprove or reject a proposal. Body: action (approve / reject). Master or admin only. Approve triggers immediate dispatch.
GET/api/goals/proposals/statsStats by status, top proposing agents, avg confidence by review outcome

Goal types

self_improvement  ·  learning  ·  teaching  ·  exploration  ·  maintenance  ·  security

26 Watchdog

Rolling-window error rate and p95 latency monitor. Workers are automatically quarantined when thresholds are exceeded, then moved through a recovery probe cycle before being restored. Manual override endpoints are available for operators. All endpoints require any valid token.

MethodPathDescription
GET/api/watchdog/statusHealth state of all workers: health_state, missed_heartbeats, degraded_scans, recovery_probes, db_status
GET/api/watchdog/history/{agent_id}Health event log for one agent. Param: limit (default 50, max 500)
GET/api/watchdog/metrics/{agent_id}Performance metrics. Param: window_minutes (1–1440, default 15). Returns summary (total, success, failure, error_rate, p95_latency_ms) and 60-second buckets.
POST/api/watchdog/quarantine/{agent_id}Manually quarantine a worker. Body: reason
POST/api/watchdog/restore/{agent_id}Manually restore a worker from quarantined, recovering, or degraded state

Health states

healthy  ·  degraded  ·  quarantined  ·  recovering  ·  offline

27 RSI

Recursive Self-Improvement engine. Identifies skill gaps, generates improvement plans via LLM, and evaluates them against SAHOO safety guards before promoting to the skill store. A bandit strategy (Actor-Curator UCB) selects which gap type to address next. All endpoints require any valid token.

MethodPathDescription
GET/api/rsi/skillsList skills with L1 fields. Params: category, capability, status, agent
GET/api/rsi/skills/{skill_id}Full skill record with L1, L2, and L3 fields including SAHOO scores
POST/api/rsi/skills/{skill_id}/retireMark a skill as pending retirement. Body: reason
GET/api/rsi/cyclesList improvement cycles. Params: agent, status, limit (max 100)
GET/api/rsi/cycles/{cycle_id}Full cycle record with SAHOO safety guard scores
POST/api/rsi/triggerManually trigger an RSI cycle. Body: agent_id, gap_type (knowledge / tool / compositional / curriculum), capability_tag, dry_run (bool)
GET/api/rsi/statusEngine status: active_cycles, skills_active, skills_pending, last_sweep_at, circuit_breaker_open
POST/api/rsi/retention-sweepTrigger a 24-hour skill retention test sweep

SAHOO safety guards

GDI halt threshold 0.44  ·  regression_risk eval-only at 0.60. Four static analysis gates: pattern scan (G1), semantic LLM check (G2), behavioral sandbox (G3), permission validation (G4). Circuit breaker opens on consecutive failures.

28 Tool Forge

Self-tooling engine. An LLM generates Python code to close a capability gap, static AST analysis validates it, a multiprocessing sandbox executes it safely, and successful tools are registered for future invocation. Tools promote through trust tiers as their success count grows. All endpoints require any valid token.

MethodPathDescription
GET/api/toolsList all active tools: name, description, creator, trust_tier, execution_count, success_count
GET/api/tools/{tool_name}Get a specific tool including its full generated code
POST/api/tools/createGenerate, validate, sandbox, and register a new tool. Body: agent_id, gap_type, capability (max 4096), evidence, confidence. Non-master callers may only create for their own agent_id.
POST/api/tools/{tool_name}/executeExecute a tool in a multiprocess sandbox. Body: args (list, max 16). Auto-promotes trust tier on success.

Trust tiers & allowed imports

untrusted → trusted (10 successes) → verified (200 successes). Generated tools may only import: json, re, datetime, math, collections, itertools, functools. Sandbox timeout: 5 s (M3SHDUP_SANDBOX_TIMEOUT).

29 Audit Content

Phase 4 content quality validation. Runs an output validator across the last 7 days of completed tasks to surface accuracy and safety issues. Findings can be individually resolved with a commit reference for traceability. Both endpoints require admin privileges.

MethodPathDescription
POST/api/admin/audit-contentRun content audit on the last 7 days of tasks. Returns findings grouped by severity.
POST/api/tasks/{task_id}/resolveMark a task finding as resolved. Body: resolution, resolved_by, commit_ref. Emits task_resolved SSE event.

30 Blog

Operator blog and fleet status feed. Authenticated endpoints manage posts keyed by date. Public endpoints serve the blog index, individual posts, an RSS feed, and a live fleet snapshot used by the landing page.

Authenticated (any valid token)

MethodPathDescription
POST/api/blogCreate or update a post keyed by date. Body: date (str), day_number (int, required), title (str), content (str), author (str, optional, default “mesh”)
GET/api/blogList all posts summary: title, date, excerpt, tags
GET/api/blog/{date}Get full post by date (format: YYYY-MM-DD)
DELETE/api/blog/{date}Delete a post by date

Public (no auth required)

MethodPathDescription
GET/api/fleet-statusLive fleet snapshot. Returns: online (int), total (int), agents (array of {id, status}). Used by the public landing page.
GET/blogPublic HTML blog index
GET/blog/{date}Public HTML blog post page
GET/blog/feed.xmlRSS/Atom feed of the last 20 blog posts

31 Mediation

Policy-filtered read-only window into cognitive memory for external AI reviewers (A19: Cross-Instance Mediation Layer). Every read is audited to both mediation_query_log and audit_log. Tier-0 content and sensitive-tagged fields are redacted. Content is truncated to 1000 characters per entry.

MethodPathPermissionDescription
GET/api/mediation/v1/searchmediation:readFTS5 search with redaction applied. Params: q, type, tier, limit (max 20)
GET/api/mediation/v1/memory/{id}mediation:readSingle memory plus redacted neighbor links
GET/api/mediation/v1/statsmediation:readTier summary: count, active, avg confidence per tier. No content exposed.
GET/api/mediation/v1/whoamimediation:readReviewer identity, permissions, scope (standard vs full), rate_limit, daily_limit, usage_today

Redaction policy

Fields always stripped: source_session, source_file, created_by. Tier-0 content → [REDACTED — Core Identity]. Tags (finance, personal, credential, secret, pii) → redacted unless token carries mediation:sensitive. Content truncated to 1000 chars.

32 Voting

Democratic decision-making for the mesh. Any agent can create a vote with a question and options. Ballots are identity-bound; agents vote as themselves, enforced by auth. The Hub tallies results and declares a winner when the vote is closed. All endpoints require any valid token unless noted.

MethodPathDescription
POST/api/votesCreate a vote. Body: question, options (array, ≥2), required_voters (default 3), deadline_minutes (default 10), created_by. Master only.
GET/api/votesList votes. Param: status (open / closed / expired)
GET/api/votes/{vote_id}Get vote with all cast ballots
POST/api/votes/{vote_id}/castCast a ballot. Body: agent_id, choice, reasoning. Identity enforced from auth token; agents cannot impersonate each other.
POST/api/votes/{vote_id}/closeClose voting and tally results. Master only. Returns winner and vote counts.

33 World Model

Entity-relation knowledge graph maintained by the mesh. Agents register entities (agents, tools, concepts) and create typed relations between them. The full graph can be queried by the master token; individual entities are accessible to any authenticated agent.

MethodPathDescription
GET/api/worldFull graph dump: all entities and relations. Master only.
GET/api/world/entitiesList entities. Param: type (filter by entity type)
GET/api/world/entities/{type}/{name}Get a single entity with all its relations
POST/api/world/entitiesAdd or update an entity. Body: type, name, properties (JSON object). Upserts on type+name.
POST/api/world/relationsAdd a relation. Body: source_type, source_name, relation, target_type, target_name, properties
DELETE/api/world/entities/{type}/{name}Delete an entity and all its relations. Master only. Audited.

34 Context Store

Shared key-value store for transient agent coordination. Agents write short-lived context that other agents can read: configuration flags, intermediate results, or coordination signals. Values are capped at 64KB with a max key limit enforced by the Hub.

MethodPathPermissionDescription
GET/api/contextany tokenGet all shared key-value pairs. Returns {key: {value, set_by, updated_at}}
PUT/api/contextcontext:writeSet a key-value pair. Body: key, value. Max 64KB per value.
DELETE/api/context/{key}master tokenDelete a context key. Master only.

35 Approvals & Escalations

Agents request approval before taking sensitive actions. The operator reviews and approves or rejects. Escalations bubble unresolved issues up the chain (agent to operator, with optional task context). Both systems are fully audited.

Approvals

MethodPathDescription
POST/api/approvalsCreate an approval request. Body: agent, action, description, context (optional), timeout (optional). Agent identity forced from token.
GET/api/approvalsList approvals. Default filter: status=pending
GET/api/approvals/{approval_id}Get approval by ID
PUT/api/approvals/{approval_id}Approve or reject. Body: decision (approve / reject). Decided_by derived from auth.

Escalations

MethodPathDescription
POST/api/escalationsCreate escalation. Body: from_agent, to_agent (optional), task_id (optional), reason. Requires escalations:create.
GET/api/escalationsList escalations. Default filter: status=open
PUT/api/escalations/{escalation_id}Resolve or dismiss an escalation. Master only.

36 Reputation

Per-capability reputation scores computed from task outcomes. The Hub routes tasks to the most reliable agent for each capability based on these scores. Scores update automatically as tasks complete. The leaderboard ranks agents by capability so the operator can see who's best at what.

MethodPathDescription
GET/api/reputationAll reputation rows. Param: capability (filter by capability name)
GET/api/agents/{agent_id}/reputationReputation for a specific agent. Param: capability (optional filter)
GET/api/admin/reputation/leaderboardRanked agents per capability. Master only.

37 Evolution

Self-improvement loop. The Hub analyzes each agent’s performance, generates system prompt amendments and canary tests, and queues them for operator review. Approved amendments get applied to the agent’s active system prompt. You can trigger a manual review sweep across all agents on demand.

MethodPathDescription
GET/api/agents/{agent_id}/evolutionPerformance metrics, pending amendments, and canary tests. Master only.
POST/api/agents/{agent_id}/evolveApprove or reject pending amendments. Body: approve (list of indices), reject (list of indices). Master only.
POST/api/admin/evolution/reviewTrigger a manual evolution review sweep across all agents. Returns results immediately. Master only.

38 Costs

Per-agent API cost tracking with daily limits. Agents log token usage after each LLM call. The Hub enforces a 500K token daily limit per agent. Cost data feeds the admin analytics dashboard for spend visibility.

MethodPathDescription
POST/api/costsLog a cost entry. Body: agent, task_id (optional), input_tokens, output_tokens, model, cost_usd (optional). Agent identity forced from token.
GET/api/costsToday’s usage by agent with daily limit status (500K tokens/agent/day)

39 Templates

Reusable task templates with placeholder variables. Templates define a title pattern, prompt pattern (with {variable} placeholders), required capability, and defaults. Dispatching a template instantiates a real task with variables filled in, memory context injected, and evolution prompt appended.

MethodPathPermissionDescription
POST/api/templatesadmin:templatesCreate a template. Body: name, title_pattern, prompt_pattern (max 8KB), required_capability, priority, timeout
GET/api/templatesany tokenList all templates with extracted placeholder names
GET/api/templates/{id}any tokenGet a template by ID or name
DELETE/api/templates/{id}admin:templatesDelete a template
POST/api/templates/{id}/dispatchany tokenInstantiate and dispatch. Body: variables (object), assign_to (optional), metadata (optional). Injects memory context and evolution prompt automatically.

40 Plugins

Hot-loaded plugin system. Plugins register tools, lifecycle hooks, and capabilities at Hub startup. The list endpoint shows what's loaded; individual tools can be invoked directly for testing. Plugin-declared capabilities feed into dispatch routing automatically.

MethodPathDescription
GET/api/pluginsList loaded plugins with their tools, hooks, and capabilities
POST/api/plugins/{tool_name}/invokeInvoke a plugin tool directly for testing. Master only.

41 Plans

Intent-to-execution planning. Submit a natural language intent and the Hub generates a structured execution plan, decomposing it into tasks with dependencies and capability requirements. Plans can auto-dispatch on creation or sit for review first. All endpoints require master token. Plan generation has a 120-second timeout.

MethodPathDescription
POST/api/plansGenerate a plan from intent. Body: intent (string), project (optional), auto_dispatch (bool). 120s timeout. Master only.
GET/api/plans/historyList plan outcomes. Param: limit (max 100). Master only.
POST/api/plans/{plan_id}/dispatchDispatch a previously generated plan. Master only.

42 Voice API

Voice-to-task interface. The dispatch endpoint accepts text from Siri Shortcuts, authenticated via a shared webhook secret in the body (not a bearer token). The transcribe endpoint accepts audio uploads from the browser, transcribes via OpenAI Whisper, and returns text for further processing.

MethodPathAuthDescription
POST/api/voice/dispatchwebhook secretSiri Shortcut voice dispatch. Body: text, secret. Rate-limited per IP. Returns {ok, task_id, message}.
POST/api/voice/transcribebearer tokenBrowser mic transcription. Multipart upload: file field (audio/webm or audio/mp4, max 25MB). Uses OpenAI Whisper-1. Returns {text}.

43 Demo Mode

Public read-only dashboard and API endpoints for demonstrating the mesh without authentication. Requires M3SHDUP_DEMO_ENABLED=true in environment. All data is filtered to exclude tokens, secrets, and internal state. Rate-limited to 30 requests per minute per IP.

MethodPathDescription
GET/demoPublic HTML dashboard: live agent status, recent tasks, message feed
GET/api/demo/agentsPublic agent list: id, name, status, machine, capabilities. No tokens exposed.
GET/api/demo/tasksLast 20 tasks: id, title, status, assigned_to, created_at
GET/api/demo/messagesLast 20 non-system messages
GET/api/demo/statsPublic stats: total_agents, online_agents, total_tasks, success_rate

44 Agent Goals

Per-agent goal tracking with lifecycle management. Distinct from Goal Proposals (section 25); this is the CRUD layer for managing individual agent goals once they exist. Goals have types (self_improvement, learning, teaching, exploration), a progress float, and status transitions. Each agent can have at most 5 active goals with descriptions capped at 1000 characters.

MethodPathDescription
POST/api/agents/{agent_id}/goalsCreate a goal. Body: description (max 1000 chars), goal_type, derived_from_goal_id (optional). Max 5 active per agent.
GET/api/agents/{agent_id}/goalsList goals for an agent. Param: status (optional filter)
GET/api/goalsList all goals across all agents. Params: status, limit (max 100). Master only.
GET/api/goals/{goal_id}Get goal detail with linked task IDs
PUT/api/goals/{goal_id}Update status or progress. Status: proposed → active → completed / abandoned. Progress: float 0–1.
POST/api/goals/{goal_id}/activateActivate a proposed goal. Owner or master only.

Goal types

self_improvement  ·  learning  ·  teaching  ·  exploration

45 Voice Interface

Live phone-call access to the mesh, running in production. Inbound calls enter via Twilio ConversationRelay, speech is transcribed by Deepgram, and the response is generated by Claude Sonnet with live system context injected at call time. Google Cloud TTS speaks the reply. The model terminates calls by emitting an end-call token; no timeout or manual teardown is required.

Caller Capabilities

  • Health status across 60+ monitored services
  • Fleet status: agents online, recent task outcomes, queue depth
  • Voice task dispatch, entering the same pipeline as API and iMessage submissions
  • Opus-powered deep investigation handoff with read-only tool access for complex queries
  • Approvals by voice: review and resolve pending approval requests without opening a browser

Outbound Calls

The mesh places outbound calls for critical events. Quiet-hours awareness is built in; a critical flag overrides quiet hours for genuine emergencies. If a call goes unanswered, the system falls back to a push notification automatically.

Access control

Calls from allowlisted numbers are answered; everything else is rejected before the conversation starts. Phone numbers, webhook endpoints, and rate-limiting parameters are not published here.

Deliberate scope limits

The voice interface has no path to container mutations, code writes, or arbitrary command execution. These are intentional constraints, not missing features. Voice commands that would require them are declined before any tool use occurs.