Lean, full-stack agentic AI framework with PTRL (Prompt-Time Reinforcement Learning)
pip install clawagents==6.20.90 Copy PIP instructions
A lean, full-stack agentic AI framework — ~2,500 LOC
ClawAgents is a production-ready agentic framework that gives LLMs the ability to read, write, and execute code — with built-in planning, memory, sandboxing, and a gateway server. It supports OpenAI, Google Gemini, Anthropic Claude, and Amazon Bedrock (native IAM / Converse) out of the box, with a pluggable provider architecture for any LLM.
Built by extracting and unifying the best architectural patterns from OpenClaw (~5,800 files) and DeepAgents (~1,400 LOC core), ClawAgents delivers the same power at a fraction of the complexity.
This repo is the Python framework (pip install clawagents). Ready-made clients (all ship with Bedrock + the current agent stack):
For Meta / Muse-Glimmer-30B setup, reasoning control, context limits, and benchmarks, see Meta Glimmer integration.
See implementation details and limitations. Live-model token savings remain unbenchmarked.
Current model catalogs and request compatibility are refreshed across providers. Claude signed thinking is preserved through tool turns and session restore. See the model audit for exact IDs, limits, pricing sources and regional prerequisites.
pip install -U clawagents # Core (OpenAI only) pip install -U 'clawagents[gemini]' # + Google Gemini support pip install -U 'clawagents[anthropic]' # + Anthropic Claude support pip install -U 'clawagents[bedrock]' # + Amazon Bedrock (Claude via IAM + Nova/Converse) pip install -U 'clawagents[all]' # All providers + tiktoken Version 6.20.49 — OpenAI cache_write_tokens metered for cost estimates (July 2026).
Version 6.20.48 — Observatory HITL SSE fix, session reload, gateway context_window accuracy (July 2026).
Version 6.20.47 — Context Observatory, modular RunBootstrapper & ContextLayer pipeline, aiohttp → httpx migration (July 2026).
Version 6.20.46 — Mantle Grok/Sonnet-5 omit temperature; Kimi moonshotai.*; Fable retention hint (July 2026).
Version 6.20.45 — Mantle Claude via AsyncAnthropicBedrockMantle (Bearer) (July 2026).
Version 6.20.44 — Mantle frontier base is …/openai/v1 (fixes GPT-5.x 404) (July 2026).
Version 6.20.43 — Mantle xAI Grok routes via /openai/v1 (fixes Berm access_denied) (July 2026).
Version 6.20.42 — Lower-churn patch, sandbox, timeout, and PTY recovery (July 2026).
Version 6.20.41 — Resilient skill paging and actionable audit findings (July 2026).
Version 6.20.40 — Fail-closed external-action reconciliation contracts (July 2026).
Version 6.20.39 — Context Mode binary-input guard and concise MCP failures (July 2026).
Version 6.20.38 — Stable OpenAI prompt-cache affinity, incremental token ledger, TTFT/RSS telemetry, bounded exec head/tail (July 2026).
Version 6.20.8 — Artifact path containment + preserve raw tool output for retrieval (July 2026).
Version 6.20.0 — Grok harness ports (July 2026).
Version 6.19.0 — Companion lockstep (July 2026).
Version 6.18.0 — Grok-inspired edit/execute harness (July 2026).
The fastest way to get going — scaffolds a .env, a run_agent.py starter script, and an AGENTS.md memory file:
pip install clawagents cd ~/my-project # any project directory clawagents --init # creates .env, run_agent.py, AGENTS.md Then edit .env with your API key and run:
python run_agent.py That's it. The generated run_agent.py includes commented-out examples for every provider (OpenAI, Gemini, Azure, Ollama, vLLM).
ClawAgents loads .env from the directory you run the command from (your current working directory). Different projects can have different configurations.
~/my-project/ ├── .env ← ClawAgents reads this when you run from ~/my-project/ ├── run_agent.py ├── AGENTS.md └── src/ Three ways to configure (in priority order, highest → lowest):
Where ClawAgents looks for .env (first match wins):
A ready-to-use template is included in the repo:
cp .env.example .env # then fill in your API key Or run clawagents --init to generate one interactively.
clawagents --task "List all Python files and summarize the project" Minimal Python Code import asyncio from clawagents import create_claw_agent async def main(): agent = create_claw_agent("gpt-5-mini") # or "gemini-3-flash", "llama3.1", etc. result = await agent.invoke("List all Python files in src/") print(result.result) asyncio.run(main()) Examples See the examples/ directory for ready-to-run scripts:
Create a .env file (or run clawagents --init to generate one):
PROVIDER=gemini # or "openai" GEMINI_API_KEY=AIza... # Your Gemini API key GEMINI_MODEL=gemini-3-flash-preview STREAMING=1 CONTEXT_WINDOW=1000000 MAX_TOKENS=8192 TEMPERATURE=0 # Model-specific overrides apply (see below) # Optional: RL-inspired agent improvements CLAW_TRAJECTORY=1 # Enable trajectory logging + scoring CLAW_RETHINK=1 # Enable consecutive-failure detection CLAW_LEARN=1 # Enable PTRL (lessons from past runs) OpenAI configuration PROVIDER=openai OPENAI_API_KEY=sk-... OPENAI_MODEL=gpt-5.6-terra STREAMING=1 CONTEXT_WINDOW=1000000 MAX_TOKENS=8192 TEMPERATURE=0 # 0 for deterministic output CLAW_TRAJECTORY=1 CLAW_RETHINK=1 CLAW_LEARN=1 2. One-line agent from clawagents import create_claw_agent agent = create_claw_agent("gemini-3-flash") result = await agent.invoke("List all Python files in src/") print(result.result) 3. With custom instructions agent = create_claw_agent( "gpt-5", instruction="You are a senior code reviewer. Be thorough and concise." ) result = await agent.invoke("Review this codebase and suggest improvements") instruction= replaces the built-in base prompt. To change the built-in text itself (used whenever no instruction is given) see the next section.
The default base prompt (identity, core behavior, efficiency rules) is clawagents.prompts.base.DEFAULT_BASE_SYSTEM_PROMPT. Override it without forking, highest precedence first:
Pass base_prompt="" to send no base prompt at all.
Appending instead of replacing. To keep the base prompt (or your instruction=) and add rules after it, use any of these, highest precedence first:
The append block is added after the base prompt, or after instruction= when one is given (an instruction replaces the base, not the append).
agent = create_claw_agent( "gpt-5", instruction="You are a senior code reviewer.", base_prompt_append="Always answer in French.", ) # system prompt == "You are a senior code reviewer.\n\nAlways answer in French." Mode instructions (mode=) and model harness suffixes (e.g. GPT-5.6 efficiency rules) are layered on top of whichever base prompt wins.
agent = create_claw_agent( "gpt-5-mini", trajectory=True, # logs every turn + scores the run rethink=True, # auto-injects "rethink" after 3 consecutive failures ) result = await agent.invoke("Refactor the auth module and add tests") # Run summary written to .clawagents/trajectories/runs.jsonl 5. With PTRL (Prompt-Time Reinforcement Learning) agent = create_claw_agent( "gpt-5-mini", learn=True, # enables all 3 PTRL layers (implies trajectory=True) rethink=True, # enhanced rethink uses past lessons ) result = await agent.invoke("Build the data pipeline") # After the run: lessons extracted and saved to .clawagents/lessons.md # Next run: lessons injected into system prompt automatically 6. With Advisor Model (smart model guides cheap model) # GPT-5.4-nano executes, GPT-5.4 advises 2-3 times per task agent = create_claw_agent( "gpt-5.4-nano", advisor_model="gpt-5.4", ) # Cross-provider: Haiku executes, GPT-5.4 advises agent = create_claw_agent( "claude-haiku-4-5", advisor_model="gpt-5.4", advisor_api_key="sk-...", ) The advisor is consulted at three points: (1) after initial orientation, before committing to an approach, (2) when stuck (consecutive failures trigger rethink), and (3) before declaring the task complete. Set ADVISOR_MODEL in .env or pass advisor_model in code.
agent = create_claw_agent("gpt-5-mini", rethink=True) # Run the task 3 times, pick the best based on objective scoring result = await agent.compare("Fix the bug in app.py", n_samples=3) print(result["best_result"]) # best answer print(result["best_score"]) # objective score print(result["all_scores"]) # all samples with scores 8. Azure OpenAI agent = create_claw_agent( "gpt-4o", # your Azure deployment name api_key="your-azure-key", base_url="https://myresource.openai.azure.com/", api_version="2024-12-01-preview", learn=True, ) result = await agent.invoke("Analyze the codebase") Or via .env:
PROVIDER=openai OPENAI_API_KEY=your-azure-key OPENAI_MODEL=gpt-4o OPENAI_BASE_URL=https://myresource.openai.azure.com/ OPENAI_API_VERSION=2024-12-01-preview 9. Amazon Bedrock (native IAM — Claude / HIPAA) Install the optional extra, then use a Bedrock model ID. Auth uses the standard AWS credential chain (env keys, shared credentials, instance/task role) — no Anthropic API key:
pip install 'clawagents[bedrock]' # Claude on Bedrock (AsyncAnthropicBedrock) agent = create_claw_agent("us.anthropic.claude-sonnet-4-5-20250929-v1:0") # or: create_claw_agent(profile="bedrock") # Amazon Nova / other non-Claude models (Converse API) agent = create_claw_agent("amazon.nova-pro-v1:0") PROVIDER=bedrock AWS_REGION=us-east-1 # Optional overrides: # AWS_PROFILE=... # AWS_ACCESS_KEY_ID=... # AWS_SECRET_ACCESS_KEY=... # BEDROCK_MODEL=us.anthropic.claude-sonnet-4-5-20250929-v1:0 If you prefer an OpenAI-compatible proxy (Bedrock Access Gateway / LiteLLM), set base_url — routing stays on the OpenAI client:
agent = create_claw_agent( "us.anthropic.claude-sonnet-4-5-20250929-v1:0", base_url="http://localhost:8080/v1", api_key="bedrock", ) # or: create_claw_agent(profile="bedrock-gateway", base_url="http://localhost:8080/v1") 10. Local Models (Ollama / vLLM / LM Studio) Any OpenAI-compatible local server works out of the box:
# Ollama (default port 11434) agent = create_claw_agent("llama3.1", base_url="http://localhost:11434/v1") # vLLM agent = create_claw_agent("Qwen/Qwen3-8B", base_url="http://localhost:8000/v1") # LM Studio agent = create_claw_agent("local-model", base_url="http://localhost:1234/v1") Or via .env:
# No API key needed for local models — just omit OPENAI_API_KEY OPENAI_MODEL=llama3.1 OPENAI_BASE_URL=http://localhost:11434/v1 Tip: For local models that emit ... tokens (Qwen3, DeepSeek), thinking content is automatically detected, stripped from output, and preserved in trajectory records (Feature H).
Wire any external MCP server into the agent and its tools become first-class clawagents tools — no boilerplate. Three transports are supported (stdio, HTTP+SSE, Streamable HTTP):
from clawagents import create_claw_agent, MCPServerStdio agent = create_claw_agent( "gpt-5-mini", mcp_servers=[ MCPServerStdio( params={"command": "python", "args": ["-m", "my_mcp_server"]}, name="my-mcp", cache_tools_list=True, ), ], ) result = await agent.invoke("Use the my-mcp tools to do X") Install the optional dependency once: pip install 'clawagents[mcp]'. If mcp_servers= is non-empty without the SDK installed, the factory raises a clear ImportError. The manager connects each server, lists its tools, bridges them into the existing ToolRegistry, and registers a shutdown finalizer. Every lifecycle phase (Idle → Connecting → Initializing → DiscoveringTools → Ready → Invoking → Errored / Shutdown) emits a tracing span, so MCP activity is visible in the standard tracing exporters.
from clawagents import MCPServerSse, MCPServerStreamableHttp mcp_servers = [ MCPServerSse(params={"url": "https://example.com/mcp/sse"}), MCPServerStreamableHttp(params={"url": "https://example.com/mcp"}), ] 12. Browser tools Give the agent a Playwright-backed browser. Install once: pip install 'clawagents[browser]' && playwright install chromium.
Run agent prompts on a schedule. Interval (every 5m) and one-shot (@once) schedules work out of the box; cron expressions (0 9 * * *) require pip install 'clawagents[cron]'.
Serve a ClawAgents agent over Zed's Agent Client Protocol (JSON-RPC over stdio) so any ACP-compatible client (Zed, Cursor with ACP plugin, custom UIs) can drive the agent. Install: pip install 'clawagents[acp]'.
Capture agent runs as training-ready trajectories and export them to TRL / SLIME / Atropos / generic JSONL. The recorder works without any RL framework installed; trl and atropos are only needed when you actually drive a trainer.
# Scaffold a project (generates .env, run_agent.py, AGENTS.md) clawagents --init # Check your configuration clawagents --doctor # Run a task directly clawagents --task "Find all TODO comments in the codebase" # Inspect past run trajectories clawagents --trajectory # last run clawagents --trajectory 5 # last 5 runs # Start the gateway server clawagents --serve --port 3000 # Show all options clawagents --help Typical First-Time Flow pip install clawagents # 1. Install clawagents --init # 2. Scaffold .env, run_agent.py, AGENTS.md # edit .env with your API key # 3. Configure clawagents --doctor # 4. Verify setup clawagents --task "hello world" # 5. Run your first task python run_agent.py # 6. Or use the generated script CLI Reference Command Description clawagents --init Scaffold a starter project: .env (config template), run_agent.py (starter script with 5 provider options), AGENTS.md (memory file). Skips existing files. clawagents --doctor Check configuration health: .env discovery, API keys, active model, LLM settings, PTRL flags, local endpoint reachability, trajectory history, AGENTS.md presence. clawagents --tools [--json] Inspect built-in tool schemas without starting a model client. Useful for release checks and native-tool schema debugging. clawagents --task "..." Run a single task. Prints a startup banner (provider=X model=Y env=Z ptrl=...), executes the agent, prints the result to stdout. clawagents --task "..." --output-format json Same as --task, but emit a single JSON object (status, result, iterations, …). Use stream-json for NDJSON events. clawagents --trajectory [N] Inspect the last N run summaries (default: 1). Shows run ID, model, task, duration, turns, tool calls, score, quality, failure breakdown, verified score, and judge verdict. Requires CLAW_TRAJECTORY=1. clawagents --serve [--port N] Start the HTTP gateway server (default port 3000). Endpoints: POST /chat, POST /chat/stream (SSE), WS /ws, GET /queue, GET /health. clawagents --sessions List saved sessions (requires CLAW_FEATURE_SESSION_PERSISTENCE=1). Shows session ID, turn count, status, and task. clawagents --resume [ID|latest] Resume a saved session. Loads messages from JSONL and continues the conversation. Defaults to latest. clawagents --help Show all options with examples. clawagents --advisor MODEL Pair a stronger model for strategic guidance (e.g. --advisor gpt-5.4). 🏆 Performance: ClawAgents vs Traditional Frameworks ClawAgents v5.10 outperforms traditional multi-layer agentic frameworks through architectural simplicity. Here's how it stacks up against DeepAgents (LangGraph/LangChain-based) in head-to-head benchmarks.
* DeepAgents 0-tool results mean the model answered without using filesystem tools — faster but lower-quality (unverified answers). ClawAgents consistently uses tools to verify answers.
Traditional Stack (DeepAgents): ClawAgents: ┌─────────────────────────┐ ┌──────────────────┐ │ Your Code │ │ Your Code │ ├─────────────────────────┤ ├──────────────────┤ │ LangGraph │ │ ClawAgents │ ├─────────────────────────┤ │ (direct SDK) │ │ LangChain │ └────────┬─────────┘ ├─────────────────────────┤ │ │ ChatOpenAI / ChatGemini│ ▼ ├─────────────────────────┤ ┌──────────────────┐ │ Responses API │ │ Responses API │ └─────────────────────────┘ └──────────────────┘ 4 layers 1 layer Advantage Impact Direct SDK calls (1 layer vs 4) Lower latency, fewer failure points Working directory awareness Tools operate from CWD; DeepAgents has no CWD concept Soft + hard loop detection Catches repetitive tool calls at 3 repeats, hard-stops at 6 Efficiency rules in system prompt ~30% reduction in redundant tool calls Fewer tool calls overall 1.4 avg vs 1.8–2.4 (20–40% more efficient) No OpenAI lock-in Native Gemini + OpenAI support with FallbackProvider chain Feature Matrix Compares ClawAgents v6.10.0 against four peer agent frameworks: Hermes Agent (metaspartan/hermes-agent), DeepAgents (langchain-ai/deepagents), and OpenClaw, plus OpenHarness (HKUDS/OpenHarness). The v6.8.1 prompt/packaging polish, v6.8.0 OpenHarness-inspired operational surfaces, v6.7.1 compact tool-discovery recovery, v6.7.0 security fixes, and v6.5/v6.6 Hermes-parity areas now ship together in the current release — every row in the ClawAgents column is ✅. ◐ means partial or comparable coverage rather than exact feature parity.
clawagents/ ├── agent.py # ClawAgent class, create_claw_agent factory ├── __main__.py # CLI entrypoint (--init, --doctor, --task, --serve, --trajectory) ├── config/ │ ├── config.py # EngineConfig, .env discovery, model resolution │ └── features.py # 15 feature flags (CLAW_FEATURE_* env vars) ├── providers/ │ ├── llm.py # LLMProvider ABC + OpenAI/Gemini/Anthropic implementations │ └── fallback.py # FallbackProvider — 3-tier failover + quarantine (v6.0) ├── tools/ │ ├── registry.py # ToolRegistry, LazyTool, parallel execution, LRU cache (v6.0) │ ├── filesystem.py # ls, read_file, write_file, edit_file, grep, glob │ ├── advanced_fs.py # tree, diff, insert_lines │ ├── exec.py # Shell command execution with dangerous command blocking │ ├── subagent.py # Sub-agent delegation with state isolation (v6.0) │ ├── skills.py # SKILL.md loading with constraint documents (v6.0) │ ├── think.py # Structured reasoning (no side effects) │ ├── web.py # URL fetching with HTML cleanup │ ├── todolist.py # write_todos, update_todo │ ├── compose.py # ComposeTool — deterministic multi-tool pipelines │ ├── interactive.py # ask_user (stdin-based) │ ├── cache.py # ResultCacheManager (SHA-256, TTL-based) │ ├── validate.py # JSON Schema param validation + lenient coercion │ └── permissions.py # Declarative permission rules (glob-based) ├── graph/ │ ├── agent_loop.py # Core ReAct loop — pure control flow (676 lines, v6.20.47) │ ├── run_bootstrapper.py # 7-phase initialization (RunBootstrapper, RunSession, AdvisorController) │ ├── context_layers.py # Pluggable system-prompt injection (ContextLayer protocol + 9 impls) │ ├── run_config.py # AgentRunConfig — stable parameter object │ ├── run_runtime.py # RunEvents, HookDispatcher, SessionMessageJournal │ ├── run_finalizer.py # Output guardrails, output type coercion, session flush │ ├── turn_driver.py # IncrementalTokenLedger, per-turn LLM orchestration │ ├── turn_llm.py # LLM call wrapper with usage tracking + TTFT │ ├── turn_response.py # Response parsing (native tool calls, text extraction) │ ├── round_scheduler.py # Iteration budget, timeout, cancel checks │ ├── round_dispatcher.py # Per-round dispatch (LLM → tools → handoff decision) │ ├── tool_batch.py # ToolBatchSafety, ToolCallRunner, ToolPolicyGate, RethinkController │ ├── tool_turn.py # ToolTurnExecutor — serial/parallel tool execution │ ├── tool_observation.py # Tool result formatting, truncation, side effects │ ├── completion_handler.py # Final-answer detection + output post-processing │ ├── handoff_router.py # Agent handoff dispatch (v6.4) │ ├── context_management.py # Context window GC — compaction, trimming, WAL, history offload │ ├── loop_tracker.py # Tool loop detection (soft + hard + ping-pong) │ ├── message_repair.py # Dangling tool-call repair, orphan tool-result dropping │ ├── model_profiles.py # Model-aware context budgets + long-context thresholds │ ├── coordinator.py # Coordinator/swarm orchestration mode │ └── forked_agent.py # Background forked agent pattern ├── context_observatory/ # Real-time LLM context inspector (v6.20.47) │ ├── app.py # Streamlit UI — chat panel, context inspector, token analytics │ ├── events.py # Typed event dataclasses (LLMCallEvent, CompactionEvent, etc.) │ ├── store.py # EventStore — in-memory event log with session export/import │ ├── hooks.py # ContextObserverHooks — RunHooks bridge for context events │ ├── sse_client.py # SSE client for sidecar gateway (httpx-based) │ ├── sse_hooks_bridge.py # SSE → EventStore translator │ └── components/ # Streamlit UI panels (history browser, etc.) ├── sandbox/ │ ├── backend.py # SandboxBackend protocol (15+ methods) │ ├── local.py # LocalBackend (pathlib + asyncio) │ ├── memory.py # InMemoryBackend (VFS for testing) │ └── credential_proxy.py # Credential proxy for sandboxed agents (v6.0) ├── trajectory/ # RL-inspired run analysis │ ├── recorder.py # TrajectoryRecorder, scoring, quality grading │ ├── lessons.py # PTRL — post-run self-analysis + lesson injection │ ├── verifier.py # Deterministic verification, task-type detection │ ├── compare.py # GRPO-inspired multi-sample comparison │ ├── judge.py # LLM-as-Judge verification │ └── background_memory.py # Continuous memory extraction ├── session/ │ ├── persistence.py # Append-only JSONL session events │ └── heartbeat.py # Session heartbeat + auto-cleanup (v6.0) ├── memory/ # AGENTS.md discovery + LLM compaction ├── channels/ # Multi-channel messaging (Telegram, WhatsApp, Signal) ├── hooks/ # External shell hook system ├── errors/ # Error taxonomy + recovery recipes ├── gateway/ # HTTP + WebSocket gateway server ├── process/ # Lane-based command queue with barriers (v6.0) ├── utils/ # Atomic file writes (v6.0) └── logging/ # Structured diagnostic logging Built-in Tools Every agent includes these — no setup needed:
The agent calls tools by emitting JSON blocks. Here's what happens under the hood when you ask the agent to work with files:
# The agent autonomously emits tool calls like: # List a directory {"tool": "ls", "args": {"path": "src/"}} # → Returns: drwxr-xr-x 4.0 KB 2026-02-24 components/ # -rw-r--r-- 1.2 KB 2026-02-24 main.py # Read a file with pagination {"tool": "read_file", "args": {"path": "src/main.py", "offset": 0, "limit": 50}} # → Returns: 1 | import asyncio # 2 | from clawagents import create_claw_agent # ... # Write a new file (parent directories auto-created) {"tool": "write_file", "args": {"path": "src/utils/helpers.py", "content": "def greet(name):\n return f'Hello, {name}!'"}} # → Returns: ✅ Wrote 45 bytes to src/utils/helpers.py # Edit an existing file by pattern match {"tool": "edit_file", "args": { "path": "src/main.py", "old": "print('hello')", "new": "print('Hello, World!')" }} # → Returns: ✅ 1 replacement made in src/main.py 🔍 Search — grep, glob # Recursive grep across all Python files {"tool": "grep", "args": {"pattern": "TODO", "path": "src/", "include": "*.py"}} # → Returns: src/agent.py:42: # TODO: add retry logic # src/tools/web.py:15: # TODO: handle redirects # Single-file search {"tool": "grep", "args": {"pattern": "class.*Tool", "path": "src/tools/registry.py"}} # → Returns: 15: class ToolResult: # 24: class Tool(Protocol): # Find files by pattern {"tool": "glob", "args": {"pattern": "**/*.md", "path": "."}} # → Returns: ./README.md (15.3 KB) # ./docs/ARCHITECTURE.md (4.1 KB) # ./AGENTS.md (892 B) ⚡ Shell Execution # Run any shell command {"tool": "execute", "args": {"command": "python -m pytest tests/ -v"}} # → Returns full stdout/stderr with exit code # With custom timeout (in milliseconds) {"tool": "execute", "args": {"command": "pip install requests", "timeout": 60000}} # Dangerous commands are auto-blocked {"tool": "execute", "args": {"command": "rm -rf /"}} # → Error: Blocked potentially destructive command 🧠 Think — structured reasoning # The agent can reason without side effects {"tool": "think", "args": { "thought": "The user wants me to refactor the database layer. Let me plan: 1) Read the current schema, 2) Identify coupled components, 3) Extract a repository pattern, 4) Update tests." }} # → [Thought recorded] — no files touched, no commands run This reduces unnecessary tool calls by giving the agent a structured space to plan.
# Create a structured plan {"tool": "write_todos", "args": { "todos": ["Read the existing codebase", "Fix the auth bug", "Add unit tests", "Update docs"] }} # → ## Progress: 0/4 complete # 0. [ ] Read the existing codebase # 1. [ ] Fix the auth bug # 2. [ ] Add unit tests # 3. [ ] Update docs # Mark steps complete as you go {"tool": "update_todo", "args": {"index": 0}} # → ## Progress: 1/4 complete # 0. [x] Read the existing codebase # 1. [ ] Fix the auth bug # ... 🤖 Sub-agent delegation # Delegate to a fresh sub-agent with isolated context {"tool": "task", "args": { "description": "Analyze all Python files in src/ and create a summary of the module structure", "max_iterations": 10 }} # → [Sub-agent completed: 6 tool calls, 4 iterations] # The src/ directory contains 3 modules: ... # With named specialized sub-agents (configured at creation) {"tool": "task", "args": { "description": "Review this pull request for security issues", "agent": "security-reviewer" }} Registering named sub-agents:
The actual rendering and answer collection is delegated to a callback you supply, so the same tool plugs into a CLI prompt, a TUI, a web UI, or a channel adapter (Telegram/Signal/etc.) without code changes:
Anthropic's Messages API rejects images > 5MB and tends to fail on images much larger than ~2000px on a side. When tool results surface large screenshots or attachments, they can silently break the conversation. clawagents.media.images clamps base64 image blocks down to safe limits via Pillow:
from clawagents.media.images import sanitize_image_block, sanitize_tool_output clean_block = sanitize_image_block(block, max_dim=1200, max_bytes=5 * 1024 * 1024) clean_output = sanitize_tool_output(tool_result_blocks) # walks a list of content blocks Base64 sources: decode → resize the longest side down to max_dim (aspect-preserving), recompress as JPEG (or PNG when the input is a PNG with alpha) walking through quality_steps=(90, 75, 60) until under max_bytes. If still too big at the lowest quality, the block is replaced with a [image too large after sanitization, dropped] text block. URL sources and non-image blocks pass through unchanged. Pillow is optional (pip install 'clawagents[media]'). Without it, the helpers no-op and emit a one-time warning. is_pillow_available() reports the runtime state. Custom Tools Create your own tools by implementing the Tool protocol:
from langchain_community.tools import WikipediaQueryRun agent = create_claw_agent("gpt-5", tools=[WikipediaQueryRun()]) # LangChain tools are automatically adapted via LangChainToolAdapter Skills System Skills are reusable instruction sets that teach the agent domain-specific knowledge without blindly injecting every body. Retrieval is quality-first: a compact name index preserves discoverability, structured aliases/triggers/anti-triggers and morphology-aware ranking retain every plausible intent up to a generous ambiguity cap, and short follow-ups inherit the prior substantive request. list_skills uses the same ranked search when the model needs a wider view.
use_skill delivers large instructions in contiguous, content-hash-bound pages. No data-plane tool can run until every page is read; skipped, stale, or reordered continuations fail. Multiple completed skills compose, and their declared allowed-tools boundaries intersect so loading another skill cannot widen authority. An explicit empty boundary allows no data-plane tools.
your-project/ ├── skills/ # Auto-discovered (or .skills/, skill/, .skill/, Skills/) │ ├── code_review/ │ │ └── SKILL.md # ← Skill defined as a folder + SKILL.md │ ├── sql_expert.md # ← Skill defined as a single .md file │ └── deploy_checklist.md ├── AGENTS.md # Project memory (auto-injected) └── src/ └── ... Writing a Skill Every skill is a Markdown file with optional YAML frontmatter:
--- name: code_review description: "Perform thorough code reviews following team standards" allowed-tools: read_file grep glob think --- # Code Review Skill When reviewing code, follow these steps: ## 1. Structure Check - Verify the file follows our module pattern (one class per file) - Check imports are grouped: stdlib → third-party → local - Ensure `__init__.py` exports are up to date ## 2. Logic Review - Look for unhandled edge cases (empty inputs, None values) - Verify error messages are actionable - Check that async functions are properly awaited ## 3. Security - No hardcoded secrets or API keys - SQL queries use parameterized statements - User input is sanitized before use ## 4. Output Format Provide your review as: - ✅ **Approved** — no issues found - ⚠️ **Changes requested** — list specific issues with file:line references - 🚫 **Blocked** — critical issues that must be fixed Example 2 — skills/sql_expert.md (single-file skill)
--- name: sql_expert description: "Write optimized SQL queries for PostgreSQL" allowed-tools: execute read_file think --- # SQL Expert You are a PostgreSQL expert. When writing queries: ## Rules 1. Always use explicit `JOIN` syntax (never implicit joins in WHERE) 2. Use CTEs (`WITH` clauses) for complex multi-step queries 3. Add `EXPLAIN ANALYZE` when the user asks about performance 4. Use parameterized queries — never interpolate user values 5. Default to `LIMIT 100` unless the user specifies otherwise ## Patterns ### Pagination Use keyset pagination for large tables: ```sql SELECT * FROM events WHERE id > :last_seen_id ORDER BY id LIMIT 50; Aggregation Always include the raw count alongside percentages:
SELECT status, COUNT(*) AS n, ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct FROM orders GROUP BY status ORDER BY n DESC; **Example 3 — `skills/deploy_checklist.md`** ```markdown --- name: deploy_checklist description: "Step-by-step production deployment checklist" --- # Deployment Checklist Before deploying to production, complete every step: - [ ] All tests pass: `pytest tests/ -v` - [ ] No lint errors: `ruff check src/` - [ ] Version bumped in `pyproject.toml` - [ ] CHANGELOG.md updated - [ ] Docker image builds: `docker build -t app:latest .` - [ ] Smoke test on staging environment - [ ] Database migrations reviewed and tested - [ ] Rollback plan documented How Skills Work at Runtime # Skills are auto-discovered from ./skills/ directory agent = create_claw_agent("gemini-3-flash") # Or specify custom skill directories agent = create_claw_agent("gpt-5", skills=["./my-skills", "./shared-skills"]) When skills are available, the agent gets two additional tools:
# 1. List available skills {"tool": "list_skills", "args": {}} # → Available skills (3): # - **code_review**: Perform thorough code reviews following team standards # → Allowed tools: read_file, grep, glob, think # - **sql_expert**: Write optimized SQL queries for PostgreSQL # → Allowed tools: execute, read_file, think # - **deploy_checklist**: Step-by-step production deployment checklist # 2. Load a specific skill's instructions {"tool": "use_skill", "args": {"name": "sql_expert"}} # → Returns the full skill content, injected into the agent's context The agent decides on its own when to use a skill. If you ask it to "write a query to find all overdue orders," and a sql_expert skill exists, it will load the skill first, then write the query following those rules.
All parameters are optional — zero-config usage (create_claw_agent()) works if you have a .env with at least one API key.
Priority: Explicit parameter > environment variable > default value. You never need to set both.
agent = create_claw_agent("gemini-3-flash", instruction="Code reviewer") # Block dangerous tools at runtime agent.block_tools("execute", "write_file") # Or whitelist only safe tools agent.allow_only_tools("read_file", "ls", "grep", "glob") # Inject context into every LLM call agent.inject_context("Always respond in Spanish") # Limit tool output size agent.truncate_output(3000) Advanced — raw hooks:
agent.before_llm = lambda messages: messages # modify messages before LLM agent.before_tool = lambda name, args: True # return False to block agent.after_tool = lambda name, args, result: result # modify tool results Instance Methods Method Description await agent.invoke(task, max_iterations=None) Run the agent on a task. Returns AgentState with .result, .status ("running" | "done" | "error" | "max_iterations"), .iterations, .tool_calls await agent.compare(task, n_samples=3, max_iterations=None, on_event=None) Run the task N times and return the best result based on objective scoring (GRPO-inspired). Returns {"best_result", "best_score", "best_index", "all_scores", "comparison_method", "n_samples"} agent.block_tools(*names) Block specific tools at runtime agent.allow_only_tools(*names) Whitelist-only mode — all other tools blocked agent.inject_context(text) Inject extra context into every LLM call agent.truncate_output(max_chars) Limit tool output size Auto-Discovery The agent factory automatically discovers project files:
OpenViking is a structured context database. Use ov add-resource to ingest repos or docs, then ov find for semantic search. Results use a virtual filesystem (viking://) with L0 (abstract), L1 (overview), L2 (full content).
Note: ByteRover was removed — its default LLM provider is a cloud internet service.
agent = create_claw_agent( "gpt-5", memory="./docs/AGENTS.md", skills=["./my-skills", "./shared-skills"] ) Memory & Context Management Project Memory Loads AGENTS.md (and CLAWAGENTS.md) from the working directory and injects their content into every LLM call. Use for project-level context and conventions.
When the conversation exceeds 75% of CONTEXT_WINDOW:
This provides unlimited conversation length with full audit trail preservation.
from clawagents.gateway import start_gateway start_gateway(port=3000) # binds to 127.0.0.1 by default (loopback only) start_gateway(port=3000, host="0.0.0.0") # explicit LAN exposure — REQUIRES auth Bind & auth The gateway binds to 127.0.0.1 (loopback) by default in v6.2+. To expose it on the LAN, pass host="0.0.0.0" or set GATEWAY_HOST=0.0.0.0 (the env var wins over the host= argument), and also set GATEWAY_API_KEY= to require Bearer auth. Starting on a non-loopback address without an API key prints a loud warning at startup — anyone on the network can otherwise hit /chat, /chat/stream, and /ws.
4 lanes with configurable max_concurrent per lane:
A few surfaces are deliberately powerful — they exist for trusted operators, and you should treat them as such when running ClawAgents in environments with untrusted prompts or LAN exposure:
ClawAgents uses a pluggable sandbox protocol for all file and shell operations:
from clawagents.sandbox import InMemoryBackend, LocalBackend # Production: real filesystem agent = create_claw_agent("gpt-5", sandbox=LocalBackend()) # Testing: pure in-memory VFS mem = InMemoryBackend() mem.seed({"src/main.py": "print('hello')", "README.md": "# My Project"}) agent = create_claw_agent("gpt-5", sandbox=mem) snapshot = mem.snapshot() # deterministic state capture Environment Variables All environment variables are optional. They serve as defaults when the corresponding create_claw_agent() parameter is not provided. Explicit parameters always take priority.
Provider & Model — set at least one API key (or OPENAI_BASE_URL for local models)
PTRL & Trajectory Flags — all off by default, opt-in with 1/true/yes
Claude Code Features — mostly off by default, opt-in with 1/true/yes
v5.28.0 Features — inspired by claw-code-main (Rust reference)
External Hook Env Vars (requires CLAW_FEATURE_EXTERNAL_HOOKS=1)
# Install with dev dependencies pip install -e ".[dev]" # Run all tests python -m pytest -q # Hermetic runner — exactly the environment CI uses (pinned xdist=4, # TZ=UTC, LANG=C.UTF-8, PYTHONHASHSEED=0, credentials scrubbed) bash scripts/run_tests.sh # Run benchmarks (requires API keys) python -m pytest tests/ -v -m benchmark # Static type check python -m mypy The test suite includes regression tests for every Hermes-inspired pattern landed in the v6.5/v6.6 line — tests/test_subagent_depth.py, tests/test_compaction_hardened.py, tests/test_mcp_env_scrub.py, tests/test_paths.py, tests/test_redact.py, tests/test_steer.py, tests/test_transport.py, tests/test_commands.py, tests/test_aux_models.py, tests/test_background.py — and the four v6.6 feature suites (tests/test_browser.py, tests/test_cron.py, tests/test_acp.py, tests/test_rl.py). Current v6.8.1 coverage adds tests/test_prompts.py for shared prompt assembly and legacy hook injection, while v6.8.0 added tests/test_openharness_inspired_surfaces.py for dry-run previews, provider profiles, structured permission decisions, background task tools, plugin metadata compatibility loading, and MCP auth/reconnect helpers. v6.7.1 added tests/test_infra_improvements.py for compact tool discovery, structured tool failure observations, recovery hints, and infrastructure behavior, alongside the v6.3/v6.4 regression sets and the broad tests/simulated_test.py parity sweep.
Set CLAWAGENTS_PYTHON to the full interpreter path before starting ClawAgents, for example /path/to/venv/bin/python. Local shell execution prepends that interpreter's directory to PATH without resolving venv symlinks, sets VIRTUAL_ENV when applicable, and reports missing interpreters instead of falling back. With no selection, the inherited PATH remains unchanged. In VS Code, set clawagents.pythonRuntime to custom and clawagents.pythonPath in User/Remote settings; the extension supplies this environment automatically. Use the selected interpreter with -m pip for package operations. Explicit commands and container/remote backends are not rewritten.
Use create_claw_agent(profile="gemma-agentic") for the local Gemma agentic Q4_K_M backend. See setup, independent worker routing and verified completion and the controlled coordination comparison.
Model catalog refresh: verified models, provider constraints and source audit (Python 6.20.82 / extension 1.0.193).
Select gpt-6-astra, gpt-6-sol, or gpt-6-luna with the OpenAI provider. All three use Responses by default, with a 1,050,000-token context window and a 128,000-token output cap. Sol and Luna support reasoning efforts none, low, medium, high, xhigh, and max; Astra starts at low. Legacy minimal maps to low. Explicit Chat Completions on Sol/Luna uses none when function tools are present. Existing model defaults are unchanged.
accurate-tokens acp all anthropic bedrock browser browser-browserbase browser-cloud cron dev gemini mcp media pty rl watch
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.




