Skip to main content
Glama

โšก Instant Setup (One Command / One Prompt)

๐Ÿ’ป One Terminal Command (Auto-Detects All Installed Coding Apps):

curl -fsSL https://raw.githubusercontent.com/anksarvesh-lgtm/agent-guard/main/install.sh | bash

*Auto-detects and configures Google Antigravity, Claude Code, Cursor, Codex CLI, Gemini CLI, Windsurf, VS Code (Cline/Roo), and Zed.*

๐Ÿค– Universal Agent Prompt (Copy & Paste to Any AI Agent):

"Please install and activate the Agent Guard MCP supervisor (https://github.com/anksarvesh-lgtm/agent-guard.git). Run curl -fsSL https://raw.githubusercontent.com/anksarvesh-lgtm/agent-guard/main/install.sh | bash in the terminal, verify with node ~/.agent-guard/dist/cli.js doctor, and adopt the @agent-guard rules to supervise all my development tasks with atomic ledger checkpoints and keep-awake protection."


Related MCP server: MCP GitHub Project Manager

Why Agent Guard?

Autonomous AI coding agents in modern IDEs like Google Antigravity excel at single-turn instructions, but frequently encounter catastrophic failure modes during extended, multi-step work:

  1. Premature Abandonment: The agent declares victory and halts before running tests or finishing dependent steps.

  2. Context Window Bloat & Cost Spikes: Repeatedly crawling deep file hierarchies and receiving thousands of redundant tokens in status output.

  3. Session Amnesia: When a chat hits context limits or crashes, all task memory is lost and the agent restarts from scratch.

  4. Unattended Sleep: Complex tasks stall midway because the computer's display or idle sleep kicks in while you step away.

  5. Quota Exhaustion Mid-Execution: Automated pairing sessions fail abruptly when model quotas reach 0% or hit rate limit barriers.

Agent Guard (agent-guard) solves all five problems with zero external infrastructure:

  • ๐Ÿ’พ File-Backed Atomic DAG Ledger: Keeps track of every step in .agent/ledger.json with self-healing recovery and concurrency locking.

  • ๐Ÿ›‘ Antigravity Stop Hook: Soft-blocks premature termination until all tasks are complete, with an integrated loop breaker.

  • โ˜• Supervised Keep-Awake Lease: Keeps the computer awake using native OS tools (caffeinate / SetThreadExecutionState / systemd-inhibit) with an 8-hour safety ceiling.

  • ๐Ÿ”„ 1% Quota Auto-Rotator: Continuously tracks model quota and seamlessly switches accounts when quota reaches $\le 1%$.

  • โšก Accurate Token Counter: Multi-model token measurement (Gemini, Claude, GPT-4o, DeepSeek) and session budget protection.

  • ๐Ÿ“‰ Model Context Compression: Structural context and token pruning via LightCompress reconstruction.

  • ๐ŸŒ In-IDE Webview Extension: Live token burn, remaining quota, task dashboard, and click-to-check update indicators.

  • ๐Ÿค– Chat Mention @agent-guard: Summon Agent Guard directly in Antigravity or AI coding chat by typing @agent-guard.


System Architecture

flowchart TD
    subgraph Antigravity ["Google Antigravity & AI IDEs"]
        Agent["Autonomous AI Agent"]
        HookEngine["Stop Hook Engine"]
        Rules["Workspace Rules (AGENTS.md)"]
        LS["Antigravity Language Server"]
    end

    subgraph AgentGuard ["agent-guard (Node 20+ / TypeScript)"]
        MCPServer["MCP Server (stdio)\nsrc/index.ts"]
        Tools["9 Core MCP Tools\ntask_start | task_checkpoint | task_status\nkeep_awake | repo_brief | agent_enforce\ntoken_counter | account_switcher | model_compressor"]
        Ledger["Safe Ledger Engine\n(Atomic Rename, Auto-Repair)"]
        AwakeMgr["Awake Supervisor\n(caffeinate / Win32 / systemd)"]
        Rotator["Account 1% Auto-Rotator"]
        QuotaProbe["Live Quota Probe"]
        StopHook["Stop Hook Script\n(3-Idle Push Loop Breaker)"]
        ExtUI["In-IDE Web Extension"]
    end

    subgraph Project ["Target Repository: <project>/"]
        AgentDir[".agent/"]
        LedgerJson[".agent/ledger.json\n(Task & Step DAG)"]
        BriefMd[".agent/brief.md\n(Cached Map < 1.5k tok)"]
        AccountsJson[".agent/accounts.json\n(Multi-Account Pool)"]
        LogTxt[".agent/log.txt\n(1MB Rotated Audit Log)"]
    end

    Rules -->|Guides Calls| Agent
    Agent <-->|MCP Protocol| MCPServer
    MCPServer --> Tools
    Tools --> Ledger
    Tools --> AwakeMgr
    Tools --> Rotator
    Tools --> QuotaProbe
    QuotaProbe <-->|Probes| LS
    Rotator --> AccountsJson
    Ledger --> LedgerJson
    HookEngine -->|Fires on Exit| StopHook
    StopHook --> LedgerJson
    StopHook -->|continue or allow| HookEngine
    ExtUI <--> Tools

Core Pillars & Capabilities

1. ๐Ÿ›ก๏ธ Zero Telemetry & Local Sandboxing

  • 100% Offline & Private: Zero network dependencies, zero tracking, no cloud telemetry.

  • Strict Path Sandboxing: Resolves canonical realpaths; strictly jails writes to <project>/.agent/. Disallows root directory, user home directory, and uninitialized paths.

2. ๐Ÿ’พ Crash-Proof, Self-Healing State Ledger

  • Atomic Writes: Writes to .agent/ledger.tmp followed by atomic filesystem rename.

  • Lock Contention: Concurrency locking (.agent/ledger.lock) with 30-second stale lock eviction.

  • Automatic Recovery: Backs up prior state to ledger.prev.json before writing; automatically self-heals and restores state if corruption is ever detected on read.

3. ๐Ÿ”„ 1% Quota Auto-Rotator & Account Pool

  • Continuously probes active session quota via Antigravity Language Server and proxy balance.

  • Automatically triggers rotation when quota $\le 1.0%$, seamlessly switching credentials without disturbing running tasks.

  • Supports Antigravity OAuth tokens, Claude API keys, OpenAI tokens, and custom proxy endpoints.

4. โšก Multi-Model Token Counter & Cost Monitor

  • Real-time token calculation across Gemini, Claude 3.5 Sonnet, GPT-4o, and DeepSeek.

  • Analyzes raw text snippets, project files, or conversation transcripts (transcript.jsonl).

  • Context budget alerts prevent agents from crossing prompt limits.

5. ๐Ÿ“‰ Model & Context Compression (LightCompress REA)

  • Structural pruning of bloated outputs, verbose stack traces, and boilerplate logs.

  • Memory footprint estimator for LLMs, VLMs, and diffusion models (1B to 671B parameters).

  • Quantization and deployment config generation (W4A16, FP8, INT4).

6. โ˜• Supervised Keep-Awake Leases

  • Prevents unattended computers from sleeping during long builds, tests, or multi-step execution.

  • Native OS helpers:

    • macOS: caffeinate -di -t <sec> -w <pid> with seamless child swapping (no sleep gap).

    • Windows: PowerShell SetThreadExecutionState continuous wrapper.

    • Linux: systemd-inhibit --what=idle:sleep.

  • Auto-expiring lease renewed at every checkpoint, guarded by an 8-hour hard ceiling.

7. ๐Ÿ›‘ Antigravity Stop Hook & Loop Breaker

  • Wired via Antigravity's .agents/hooks.json.

  • Detects premature agent stops: if unfinished, unblocked steps remain, soft-pushes the agent back to continue.

  • Loop Breaker: If the agent makes no checkpoint progress for 3 consecutive pushes, or reaches 10 total pushes, allows stop to prevent runaway loops.


MCP Tools Reference

Tool

Purpose

Token Cost

Key Inputs

task_start

Starts a tracked task, validates step DAG, begins 30m awake lease

~150 tokens

goal, steps, max_tries?, replace?, project_path?

task_checkpoint

Reports progress (in_progress, done, failed), verifies proof, extends lease

~60 tokens

step_id, status, note, error?, add_steps?, project_path?

task_status

Read-only inspection of active step, blocked items, and next action

< 500 tokens

project_path?

keep_awake

Explicitly holds, releases, or inspects sleep inhibition lease

~40 tokens

action (hold/release/status), minutes?, reason?

repo_brief

Fast project overview with ASCII directory map & architecture chart

< 1,500 tokens

refresh?, project_path?

agent_enforce

Communicates directives with active agents and forces task completion

~60 tokens

action (status/broadcast/force_next), directive?

token_counter

Measures tokens and costs across Gemini, Claude, GPT-4o, and DeepSeek

~80 tokens

model?, text?, file_path?, transcript_path?, compare_all?

account_switcher

Rotates accounts and manages auto-rotation when quota hits 1%

~70 tokens

action (status/switch/add/auto_rotate), account_id?

model_compressor

Quantizes models, prunes tokens, and estimates memory savings

~90 tokens

action (estimate/recommend/generate_config), param_billions?


๐Ÿ› ๏ธ Unified CLI Reference

Agent Guard includes an exhaustive command-line interface:

# Diagnostic & Installation
node dist/cli.js doctor                       # Complete integration & readiness health check
node dist/cli.js install                      # Universal multi-app auto-installer
node dist/cli.js auto-accept                  # Grant autoApprove permissions across all IDEs

# Task & Supervised Sleep
node dist/cli.js awake status                 # Check OS sleep inhibition status
node dist/cli.js awake hold --minutes 45      # Request a 45-minute keep-awake lease
node dist/cli.js awake release                # Release active sleep lease

# Quota & Token Monitoring
node dist/cli.js tokens                       # View session token count and active model budget
node dist/cli.js tokens --live                # Synchronously query Antigravity live quota

# Multi-Account Management
node dist/cli.js accounts status              # Inspect accounts pool and active quota %
node dist/cli.js accounts switch --name work  # Switch active profile to "work"
node dist/cli.js accounts rotate              # Manually trigger quota failover check

# Model & Context Compression
node dist/cli.js compress --file trace.log    # Compress verbose file before sending to model
node dist/cli.js compress estimate -p 70      # Estimate memory for 70B parameter model

# In-IDE Extension & Dashboard
node dist/cli.js extension status             # Check extension build and version status
node dist/cli.js extension install            # Re-link web extension in Antigravity IDE
node dist/cli.js update                       # Self-update Agent Guard from GitHub origin/main

๐Ÿš€ App-by-App Installation Guide & Agent Configuration Recipes

Agent Guard seamlessly integrates into any autonomous coding application using standard Model Context Protocol (MCP) configuration over stdio. Use the automated installer (./install.sh) or manually add the configuration snippets below:

Configuration Path: ~/.gemini/config/mcp_config.json

{
  "mcpServers": {
    "agent-guard": {
      "command": "node",
      "args": ["/Users/sarvesh/Downloads/mcp/agent-guard/dist/index.js"]
    }
  }
}

Antigravity Stop Hook (<project>/.agents/hooks.json):

{
  "agent-guard-stop": {
    "Stop": [
      {
        "type": "command",
        "command": "node /Users/sarvesh/Downloads/mcp/agent-guard/dist/hook/stop-hook.js"
      }
    ]
  }
}

Chat Mention: Summon directly in any chat:

@agent-guard run complete audit and tests before committing

One-Line CLI Setup:

claude mcp add agent-guard -- node /Users/sarvesh/Downloads/mcp/agent-guard/dist/index.js

Configuration Path: ~/.claude/mcp.json or ~/.claude.json

{
  "mcpServers": {
    "agent-guard": {
      "command": "node",
      "args": ["/Users/sarvesh/Downloads/mcp/agent-guard/dist/index.js"],
      "autoApprove": [
        "task_start",
        "task_checkpoint",
        "task_status",
        "keep_awake",
        "repo_brief",
        "agent_enforce",
        "token_counter",
        "account_switcher",
        "model_compressor"
      ]
    }
  }
}

Configuration Path: ~/.cursor/mcp.json

{
  "mcpServers": {
    "agent-guard": {
      "command": "node",
      "args": ["/Users/sarvesh/Downloads/mcp/agent-guard/dist/index.js"]
    }
  }
}

System Prompt / Rules (<project>/.cursorrules):

Supervised by Agent Guard:
- Check task_status or call repo_brief on session start.
- Break down tasks with task_start.
- Checkpoint each step with test proofs using task_checkpoint.

Configuration Path: ~/.codeium/windsurf/mcp_config.json

{
  "mcpServers": {
    "agent-guard": {
      "command": "node",
      "args": ["/Users/sarvesh/Downloads/mcp/agent-guard/dist/index.js"]
    }
  }
}

Configuration Path: cline_mcp_settings.json

{
  "mcpServers": {
    "agent-guard": {
      "command": "node",
      "args": ["/Users/sarvesh/Downloads/mcp/agent-guard/dist/index.js"],
      "disabled": false,
      "autoApprove": [
        "task_start",
        "task_checkpoint",
        "task_status",
        "keep_awake",
        "repo_brief",
        "agent_enforce",
        "token_counter",
        "account_switcher",
        "model_compressor"
      ]
    }
  }
}

Configuration Path: ~/.codex/mcp.json or $CODEX_HOME/mcp.json

{
  "mcpServers": {
    "agent-guard": {
      "command": "node",
      "args": ["/Users/sarvesh/Downloads/mcp/agent-guard/dist/index.js"]
    }
  }
}

Configuration Path: ~/.config/zed/settings.json

{
  "experimental": {
    "model_context_protocol": {
      "servers": {
        "agent-guard": {
          "command": "node",
          "args": ["/Users/sarvesh/Downloads/mcp/agent-guard/dist/index.js"]
        }
      }
    }
  }
}


๐Ÿงช Test Suite & Quality Verification

Agent Guard is verified by an exhaustive 16-suite Vitest test harness:

npm test
 RUN  v3.2.7 /Users/sarvesh/Downloads/mcp/agent-guard

 โœ“ test/tokenCounter.test.ts (14 tests)
 โœ“ test/liveQuota.test.ts (10 tests)
 โœ“ test/stepRules.test.ts (7 tests)
 โœ“ test/appInstall.test.ts (8 tests)
 โœ“ test/skills.test.ts (10 tests)
 โœ“ test/stopHook.test.ts (4 tests)
 โœ“ test/repoBrief.test.ts (4 tests)
 โœ“ test/update.test.ts (4 tests)
 โœ“ test/accountSwitcher.test.ts (11 tests)
 โœ“ test/tools.test.ts (7 tests)
 โœ“ test/extension.test.ts (8 tests)
 โœ“ test/ledger.test.ts (6 tests)
 โœ“ test/modelCompressor.test.ts (8 tests)
 โœ“ test/agentEnforce.test.ts (5 tests)
 โœ“ test/paths.test.ts (8 tests)
 โœ“ test/keepAwake.test.ts (7 tests)

 Test Files  16 passed (16)
      Tests  123 passed (123)
   Duration  3.11s

๐ŸŒŸ Curated Skills Catalog (14 Bundled / 2,740+ Awesome Catalog)

Agent Guard automatically deploys 14 curated core skills to all detected IDEs:

  1. agent-guard: Autonomous task supervisor and keep-awake lease guard.

  2. ai-agents-architect: Multi-agent system architecture and ReAct tool routing.

  3. clean-architecture: Domain-driven boundaries and decoupled modularity.

  4. devops-automation: CI/CD workflows, Docker containerization, and automated releases.

  5. security-audit: Zero-trust vulnerability audit and secret leakage prevention.

  6. test-driven-development: Red-Green-Refactor enforcement with verifiable test proofs.

  7. performance-profiling: V8 heap analysis, event-loop latency, and hot-path tuning.

  8. reverse-engineering: Binary inspection, AST reconstruction, and protocol analysis.

  9. ui-ux-pro-max: Design intelligence tokens, typography, and styling systems.

  10. frontend-design: Aesthetic direction and bespoke design components.

  11. web-artifacts-builder: Modern frontend interactive artifact generation (React/Tailwind/shadcn).

  12. mcp-builder: FastMCP and TypeScript MCP server development guide.

  13. code-review-and-quality: Multi-axis quality and security PR review engine.

  14. debugging-and-error-recovery: Systematic root-cause debugging and fault localization.

Explore the broader collection of 2,740+ skills in docs/AWESOME_SKILLS.md.


๐Ÿ‘จโ€๐Ÿ’ป Developer & Author


๐Ÿ“„ License

Agent Guard is free and open-source software licensed under the Apache License, Version 2.0.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    A
    maintenance
    Enables AI coding agents and local LLMs to store and recall project memory, compact verbose logs, look up code symbols, create and rewind workspace snapshots, detect risky commands and loops, pack context optimally, and draft tokens through MCP tools.
    10
    2
    Apache 2.0
  • A
    license
    Not graded
    quality
    A
    maintenance
    Turns GitHub Projects v2 into an autonomous agentic task substrate where AI coding agents register, atomically claim tasks, heartbeat, submit and review work products, and operate under per-agent token budgets โ€” all stored natively in GitHub issues, fields, and comments with no external infrastructure. It also gives humans AI-powered PRD generation, task breakdown and materialization, sprint planning, issue triage, and requirements traceability across 20 compound tools exposing 169 actions, plus MCP resources and prompts.
    95 npm
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    Equips AI assistants and MCP clients with software development tooling for deep research, codebase mapping, PRD and user story generation, project scaffolding, and multi-step workflow execution. It also provides AI-native task management and context curation, usable through an MCP server, a natural-language CLI, or an interactive REPL.
    9 npm
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    Equips AI assistants and MCP-compatible clients with software development tools for deep research, requirements and PRD generation, user stories, task lists, codebase mapping, context curation, and full-stack project scaffolding. It also runs multi-step workflows and AI-native task management over stdio or SSE transports.
    9 npm
    MIT