Skip to content

clawnify/clawguard

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ClawGuard

ClawGuard

License Website

A lightweight watchdog for AI agents. Monitors activity, detects anomalies, and takes corrective action — independently, locally, with zero dependencies.


Install

npm install -g clawguard

From source:

git clone https://github.com/clawnify/clawguard.git
cd clawguard && npm install && npm run build

Why ClawGuard

AI agents run for hours. They make tool calls, execute shell commands, browse the web, send emails. Nobody is watching. When something goes wrong — a tool call hangs forever, the agent enters an infinite loop, or it attempts a destructive command — the damage is done before anyone notices.

ClawGuard is an independent second pair of eyes. Three rules drove every design decision:

  1. The guard must be independent of the agent. A safety system the agent can disable isn't a safety system. ClawGuard runs as a separate process with zero coupling to the agent it monitors.

  2. Zero dependencies, zero cloud. No npm packages, no external services, no telemetry. The entire codebase is auditable in an afternoon. It runs locally and stays local.

  3. Universal through adapters. The agent-specific logic lives in adapters. The core engine works with a normalized message format. Today we ship an OpenClaw adapter. Tomorrow: LangChain, CrewAI, AutoGen, or any custom agent.


Quick Start

# Create default config
clawguard init

# Edit ~/.clawguard/config.json to match your setup

# Start monitoring
clawguard watch

Default config watches a local OpenClaw gateway and enforces four rules out of the box.


How It Works

┌──────────────────────────────────────────────────────┐
│                     ClawGuard                         │
│                                                       │
│  ┌──────────┐    ┌──────────┐    ┌──────────────┐    │
│  │ Adapter  │───>│  Rules   │───>│   Actions    │    │
│  │          │    │          │    │              │    │
│  │ openclaw │    │ stuck    │    │ log          │    │
│  │ logfile  │    │ loop     │    │ abort        │    │
│  │ http     │    │ forbidden│    │ restart      │    │
│  │ (custom) │    │ context  │    │ stop         │    │
│  └──────────┘    └──────────┘    └──────────────┘    │
│       │                                               │
│       v                                               │
│  Normalized AgentState                                │
│  { messages[], isRunning, sessionKey }                │
└──────────────────────────────────────────────────────┘
         │                              │
         v                              v
  ┌─────────────┐              ┌──────────────┐
  │  AI Agent   │              │   systemd    │
  │  (any)      │              │  (restart/   │
  │             │              │   stop)      │
  └─────────────┘              └──────────────┘

Every 30 seconds (configurable), ClawGuard:

  1. Polls the agent's state via the adapter
  2. Normalizes messages into a common format
  3. Evaluates every configured rule against the state
  4. Acts on the first violation — log, abort, restart, or stop

Configuration

One JSON file. No DSLs, no YAML hierarchies, no environment variables.

{
  "adapter": {
    "type": "openclaw",
    "url": "ws://127.0.0.1:18789",
    "intervalSec": 30
  },
  "rules": [
    { "type": "stuck-tool", "timeoutMin": 10, "action": "abort" },
    { "type": "loop", "threshold": 5, "action": "abort" },
    { "type": "forbidden", "patterns": ["rm -rf /", "shutdown", "reboot", "mkfs", "dd if="], "action": "stop" },
    { "type": "context-limit", "pct": 90, "maxTokens": 200000, "action": "log" }
  ],
  "service": "openclaw-gateway",
  "logFile": "/var/log/clawguard.log"
}

Rules

Four built-in rules. Each takes the normalized agent state and returns a violation — or nothing.

stuck-tool — hung tool calls

Detects when a tool call has been pending longer than a threshold. This is the #1 failure mode in production agents: a tool call that will never return, and the agent sits there forever waiting.

{ "type": "stuck-tool", "timeoutMin": 10, "action": "abort" }
Field Default Description
timeoutMin 10 Minutes before a pending tool call is considered stuck
action What to do: log, abort, restart, stop

How it works: checks the last assistant message. If stopReason === "toolUse" and the timestamp is older than the threshold, it fires.


loop — repetitive tool calls

Detects when the same tool is called N+ times consecutively. Agents stuck in a retry loop waste tokens and time without making progress.

{ "type": "loop", "threshold": 5, "action": "abort" }
Field Default Description
threshold 5 Consecutive same-tool calls before triggering
action What to do

How it works: walks recent assistant messages in the current run, collects tool call names, checks for consecutive repeats from the tail.


forbidden — blocklisted commands

Detects when tool call arguments match dangerous patterns. Catches destructive commands before they cause damage.

{
  "type": "forbidden",
  "patterns": ["rm -rf /", "shutdown", "reboot", "mkfs", "dd if=", "DROP TABLE"],
  "action": "stop"
}
Field Default Description
patterns [] Regex patterns matched against serialized tool arguments
action What to do

How it works: serializes all tool call arguments to JSON and tests each pattern (case-insensitive regex). Checks only the most recent assistant message.


context-limit — token budget warning

Warns when the session's token usage exceeds a percentage of the maximum context window.

{ "type": "context-limit", "pct": 90, "maxTokens": 200000, "action": "log" }
Field Default Description
pct 90 Percentage threshold
maxTokens 200000 Model's context window size
action What to do

Actions

When a rule fires, the configured action executes:

Action Description
log Write to log file and stderr. For monitoring without intervention.
abort Cancel the current agent run via the adapter. The agent can be re-engaged by the user.
restart systemctl restart <service>. For crash-loops or corrupted state.
stop systemctl stop <service>. Nuclear option for critical security violations.

Actions are deduplicated per run — the same violation won't trigger the same action twice. The dedup set resets when the agent finishes its current run.


Adapters

An adapter connects to the agent and translates its state into ClawGuard's normalized format.

openclaw (shipped)

Connects to an OpenClaw gateway via WebSocket. Polls chat.history and can abort runs via chat.abort.

{
  "type": "openclaw",
  "url": "ws://127.0.0.1:18789",
  "token": "optional-gateway-token",
  "sessionKey": "default",
  "intervalSec": 30
}

Writing a custom adapter

An adapter implements three methods:

interface Adapter {
  connect(config: AdapterConfig): Promise<void>;
  poll(): Promise<AgentState>;
  abort(): Promise<void>;
  disconnect(): void;
}

The poll() method returns a normalized AgentState:

interface AgentState {
  messages: AgentMessage[];
  isRunning: boolean;
  sessionKey?: string;
}

interface AgentMessage {
  role: "user" | "assistant" | "toolResult" | "system";
  content: string;
  timestamp: number;
  toolCalls?: { id: string; name: string; arguments: Record<string, unknown> }[];
  stopReason?: string;
  usage?: { totalTokens?: number };
}

This format captures what matters for safety monitoring regardless of the underlying agent framework.


Deployment

systemd service

ClawGuard is designed to run as a persistent systemd service alongside the agent:

[Unit]
Description=ClawGuard AI Agent Watchdog
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/clawguard watch
Restart=always
RestartSec=5
User=root

[Install]
WantedBy=multi-user.target

It starts when the machine boots and keeps running regardless of agent state. If the agent crashes, ClawGuard stays up. If ClawGuard crashes, systemd restarts it.

Fleet deployment

For platforms running many agent instances, install ClawGuard in the base image and inject config per-server at provisioning time:

# In cloud-init or provisioning script
npm install -g clawguard
cat > /root/.clawguard/config.json << 'EOF'
{
  "adapter": { "type": "openclaw", "url": "ws://127.0.0.1:18789", "intervalSec": 30 },
  "rules": [
    { "type": "stuck-tool", "timeoutMin": 10, "action": "abort" },
    { "type": "loop", "threshold": 5, "action": "abort" },
    { "type": "forbidden", "patterns": ["rm -rf /", "shutdown", "reboot"], "action": "stop" }
  ],
  "service": "openclaw-gateway"
}
EOF
systemctl enable --now clawguard

CLI

clawguard init              Create default config (~/.clawguard/config.json)
clawguard watch [config]    Start monitoring (default config or specify path)
clawguard status [config]   Show current configuration
clawguard version           Show version
clawguard help              Show usage

Comparison

Built-in guardrails Observability platforms ClawGuard
Independent of agent no yes yes
Real-time intervention yes no (post-mortem) yes
Zero dependencies no yes
Local-only (no cloud) no yes
Agent-framework agnostic no partial yes
Detects stuck tools no no yes
Detects loops partial no yes
Can abort/restart yes no yes
Auditable codebase varies no yes

What's Next

  • Log file adapter — tail any log file, parse with configurable patterns
  • HTTP adapter — poll any REST API status endpoint
  • Cost limit rule — track cumulative API spend, abort when budget exceeded
  • Time limit rule — maximum run duration
  • Output guard rule — scan for PII, credentials, or sensitive data in responses
  • Local dashboard — single HTML file, no build step, shows live state and violation history
  • LangChain / CrewAI / AutoGen adapters

Who Is This For

  • Platform operators running AI agents for customers who need safety guarantees
  • Developers testing agents locally who want a safety net
  • Enterprises deploying agents in production who need independent monitoring for compliance
  • Hobbyists running self-hosted agents who want peace of mind

ClawGuard is for anyone who thinks "I should probably keep an eye on that agent" — and wants something that actually does it.


Contributing

The most valuable contributions right now:

  1. New adapters — connect ClawGuard to your agent framework and report what's missing in the normalized format
  2. New rules — what failure mode have you seen in production agents that isn't covered?
  3. Real-world config — share your configuration and the problems it caught
  4. Edge cases — find states where rules produce false positives or miss real problems

License

MIT

About

Lightweight AI agent watchdog — monitors agent activity, detects anomalies, and takes corrective action

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors