AGENTS.md
Documents the architecture, source layout, tool system, memory model, database, web API, hooks, and build commands for a Rust multi-channel agent runtime.
What this file does
Documents the architecture, source layout, tool system, memory model, database, web API, hooks, and build commands for a Rust multi-channel agent runtime.
When to use it
- Onboarding to the DrugClaw codebase
- Planning a similar multi-channel agent architecture
- Understanding the agent loop and memory design
- Setting up local development and testing
Assumes this stack
AGENTS.md
Project overview
DrugClaw is a Rust multi-channel agent runtime for Telegram, Discord, and Web.
It shares one channel-agnostic agent loop (src/agent_engine.rs) and one provider-agnostic LLM layer (src/llm.rs), with channel adapters for ingress/egress.
Core capabilities:
- Tool-using chat agent loop (multi-step tool calls)
- Session resume and context compaction
- Scheduled tasks + background scheduler
- File memory (
AGENTS.md) + structured SQLite memory - Memory reflector, quality gate, and observability metrics
- Skills + MCP tool federation
- ClawHub skill registry integration (search/install/lockfile)
Tech stack
- Language: Rust (edition 2021)
- CLI args: clap
- Async runtime: Tokio
- Telegram: teloxide
- Discord: serenity
- Web API/UI: axum + React (in
web/) - Database: SQLite (rusqlite)
- LLM runtime: provider abstraction with native Anthropic and OpenAI-compatible providers
Source index (src/ + crates/)
Main orchestration files in src/:
main.rs: CLI entry (start,setup, etc.)runtime.rs: app wiring (AppState), provider/tool initialization, channel bootagent_engine.rs: shared agent loop (process_with_agent), explicit-memory fast path, compaction, tool loophooks.rs: hooks discovery/runtime/CLI (hooks list/info/enable/disable)llm.rs: provider implementations + stream handling + format translationotlp.rs: OTLP metrics exporter (HTTP/protobuf)web.rs: Web API router, shared web state, stream APIs, config endpointsweb/auth.rs: auth handlers (session login/logout, password, API key lifecycle)web/config.rs: config read/update + config self-check handlersweb/sessions.rs: session/history/reset/delete/fork/tree handlersweb/metrics.rs: metrics snapshot/history handlersweb/stream.rs: streaming send/status/SSE handlersscheduler.rs: scheduled-task runner + memory reflector loopskills.rs: skill discovery/activationmcp.rs: MCP server/tool integrationgateway.rs: event stream / request lifecycle infrasetup.rs: interactive setup wizard and provider presetsdoctor.rs: environment diagnosticschannels/*.rs: concrete channel adapters (Telegram/Discord/Slack/Feishu)tools/*.rs: built-in tool implementations and registry assembly
Modularized crates in crates/:
drugclaw-core: shared error/types/text (error,llm_types,text)drugclaw-storage: SQLite DB, memory domain, usage report assemblydrugclaw-tools: tool runtime primitives, sandbox, path guards, web/todo helpersdrugclaw-channels: channel abstractions (channel,channel_adapter, delivery boundary)drugclaw-app: app-level support modules (logging, builtin skills, transcribe)
Tool system
src/tools/mod.rs assembles built-in tools, while shared runtime primitives live in drugclaw-tools::runtime:
Tooltrait (name,definition,execute)ToolRegistrydispatch and auth context injection- risk/approval gate for high-risk tools in sensitive contexts
Current built-in tools are generated from code to avoid drift:
docs/generated/tools.mdwebsite/docs/generated-tools.md
Regenerate docs artifacts with:
node scripts/generate_docs_artifacts.mjs
Skills Storage
- Default skills dir:
<data_dir>/skills(defaultdata_diris~/.drugclaw) - Config override:
skills_dirindrugclaw.config.yaml(e.g.~/.drugclaw/skills) - Compatibility policy: existing configured
data_dir/skills_dir/working_dirkeep working; new defaults apply only when unset - ClawHub lockfile:
~/.drugclaw/clawhub.lock.json
Agent loop (high level)
process_with_agent flow:
- Optional explicit-memory fast path (
remember .../记住...) writes structured memory directly - Load resumable session from
sessions, or rebuild from chat history - Build system prompt from file memory + structured memory context + skills catalog
- Compact old context if session exceeds limits
- Call provider with tool schemas
- If
tool_use: execute tool(s), append results, loop - If
end_turn: persist session and return text
Memory architecture
Two layers:
- File memory:
- Global:
runtime/groups/AGENTS.md - Chat:
runtime/groups/{chat_id}/AGENTS.md
- Structured memory (
memoriestable):
- category, confidence, source, last_seen, archived lifecycle
- explicit remember fast path
- reflector extraction from conversation history
- dedup/supersede handling with
memory_supersede_edges
Observability tables:
memory_reflector_runsmemory_injection_logs
Surfaces:
/api/usagesummary block/api/memory_observabilitytime-window series API- Web Usage Panel trends/cards
Database
drugclaw-storage::db includes:
- schema creation + schema-version migrations (
db_meta,schema_migrations) - chat/message/session/task persistence
- structured memory CRUD + archive/supersede
- auth/session/api-key persistence (scopes, expiry, rotation)
- audit log persistence (
audit_logs) - usage and memory observability queries
- metrics history persistence (
metrics_history)
Web/API
web.rs routes include:
- chat send/send_stream + SSE stream replay
- auth APIs (
/api/auth/*) with session cookie + API key scopes - sessions/history/reset/delete/fork/tree
- config read/update + self-check (
/api/config/self_check) - audit query (
/api/audit) - metrics APIs (
/api/metrics,/api/metrics/summary,/api/metrics/history) - usage text report (
/api/usage) - memory observability series (
/api/memory_observability)
Hooks
Hook assets and spec:
- runtime hook dirs:
hooks/<name>/HOOK.md - hook spec doc:
docs/hooks/HOOK.md - sample hooks:
hooks/block-bash/,hooks/redact-tool-output/
Hook runtime supports:
- events:
BeforeLLMCall,BeforeToolCall,AfterToolCall - outcomes:
allow,block,modify(structured fields only)
ClawHub
- local doc:
docs/clawhub/overview.md - web doc:
website/docs/clawhub.md
Observability Docs
- metrics docs:
docs/observability/metrics.md - operations runbook:
docs/operations/runbook.md - PR/release checklist:
docs/releases/pr-release-checklist.md - upgrade guide:
docs/releases/upgrade-guide.md - regression/stability reports:
docs/reports/*.md
OTLP exporter supports bounded queue + retry backoff tuning:
otlp_queue_capacityotlp_retry_max_attemptsotlp_retry_base_msotlp_retry_max_ms
Build and test
cargo build
cargo test
npm --prefix web run build
npm --prefix website run build
Docs drift guard (CI + local):
node scripts/generate_docs_artifacts.mjs --check
Collaboration conventions
- For the separate
websiterepository (drugclaw.github.io), do not open a PR by default; commit/push directly unless explicitly requested otherwise.
What's inside
14 sections covering project overview, tech stack, source index, tool system, skills storage, agent loop, memory, database, web API, hooks, ClawHub, observability, build/test, and collaboration conventions.
Change this for your project
- Replace
DrugClawwith your own project name - Replace
~/.drugclawwith your own default data directory - Replace
drugclaw.github.iowith your own website repository - Replace
drugclaw.config.yamlwith your own config file name
Where it goes
Save as AGENTS.md in your repository root. Read by Codex, Cursor and other agents that follow the AGENTS.md convention.
Worth borrowing
- Separate channel-agnostic agent loop from channel adapters
- Two-layer memory with file-based and structured SQLite storage
- Generated docs artifacts from code to prevent drift
Related Documents
Browser-only development
Guides AI assistants on an Electron + React + TypeScript desktop app for browsing and organizing AI-generated images locally.
Claude Agents — Reference & Recommendations
Catalogues 40+ Claude agents and marketing skills for building a cat adoption charity landing page, with a ready-to-paste prompt and backend API reference.
Golden DKG Prototype -- Master Plan
Defines an 8-phase implementation plan for a Rust prototype of the Golden non-interactive DKG protocol using BLS12-381 and tokio.
Swarms Examples Index
Lists 60+ example scripts for building single and multi-agent systems with the Swarms framework, organized by category and use case.