Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Agent Detector Laravel Package

ergebnis/agent-detector

Detect the presence of coding agents in your PHP app by checking environment variables. Supports Amp, Antigravity, Augment, Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, and more via a simple Detector::isAgentPresent() API.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ergebnis/agent-detector
    

    Add to composer.json under require if using Laravel’s composer.json.

  2. First Use Case: Detect if an agent is present in a Laravel middleware or controller:

    use Ergebnis\AgentDetector\Detector;
    
    public function handle(Request $request, Closure $next)
    {
        $detector = new Detector();
        $isAgent = $detector->isAgentPresent($_ENV); // or getenv()
    
        if ($isAgent) {
            // Block, log, or adapt behavior
            return response('Agent detected', 403);
        }
    
        return $next($request);
    }
    
  3. Where to Look First:

    • Detector class: Core logic in src/Detector.php.
    • Supported Agents: README table for env vars.
    • Laravel Integration: Use $_ENV (Laravel 8.79+) or getenv() for env arrays.

Implementation Patterns

Core Workflows

  1. Middleware for Bot Blocking:

    namespace App\Http\Middleware;
    
    use Closure;
    use Ergebnis\AgentDetector\Detector;
    
    class BlockAgents
    {
        public function handle($request, Closure $next)
        {
            $detector = new Detector();
            if ($detector->isAgentPresent($_ENV)) {
                return response('Access denied to agents', 403);
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\BlockAgents::class,
    ];
    
  2. Feature Gating:

    if (!$detector->isAgentPresent($_ENV)) {
        // Show premium content/APIs
        return view('premium');
    }
    return view('public');
    
  3. Logging/Telemetry:

    $isAgent = $detector->isAgentPresent($_ENV);
    Log::info('Agent detected', ['is_agent' => $isAgent]);
    
  4. CI/CD Awareness: Detect agents in GitHub Actions or Laravel Forge:

    if ($detector->isAgentPresent($_ENV)) {
        // Optimize for CI (e.g., skip tests, use mocks)
        $this->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);
    }
    

Integration Tips

  • Laravel Service Provider: Bind Detector to the container for DI:

    public function register()
    {
        $this->app->singleton(Detector::class);
    }
    

    Then inject via constructor:

    public function __construct(private Detector $detector) {}
    
  • Environment Variables: Use $_ENV (Laravel 8.79+) or getenv() for consistency. For custom env files:

    $customEnv = require __DIR__.'/custom-env.php';
    $detector->isAgentPresent($customEnv);
    
  • Testing: Mock Detector in PHPUnit:

    $this->mock(Detector::class)->shouldReceive('isAgentPresent')
        ->once()->andReturn(true);
    
  • Extending Detection: Override the Detector class to add custom env vars:

    class CustomDetector extends Detector
    {
        protected function getAgentEnvironmentVariables(): array
        {
            return array_merge(parent::getAgentEnvironmentVariables(), [
                'MY_CUSTOM_AGENT' => ['MY_CUSTOM_VAR'],
            ]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. False Positives/Negatives:

    • Gotcha: Some agents (e.g., GitHub Copilot) use multiple env vars. The package checks any matching var, but edge cases may exist.
    • Fix: Test with real agent environments (e.g., run locally with COPILOT_CLI=1).
  2. Environment Array Source:

    • Gotcha: $_ENV vs. getenv() may differ in Laravel. Use $_ENV for Laravel 8.79+.
    • Fix: Normalize input:
      $env = array_merge($_ENV, getenv());
      $detector->isAgentPresent($env);
      
  3. Performance:

    • Gotcha: getenv() is slow for large env arrays. Cache results if called frequently.
    • Fix: Cache the detector instance:
      $detector = app(Detector::class); // Laravel DI
      
  4. PHP Version:

    • Gotcha: PHP 8.6+ is required (as of v1.1.1). Older versions may fail.
    • Fix: Upgrade or use a lower version (e.g., 1.0.1 for PHP 7.4–8.2).
  5. Generic AI_AGENT:

    • Gotcha: Setting AI_AGENT=1 will trigger detection, but may not align with your use case.
    • Fix: Use specific agent vars (e.g., COPILOT_CLI) for precision.

Debugging

  • Log Environment Vars:
    dd($_ENV); // Check for agent-specific vars
    
  • Test Individually:
    $detector->isAgentPresent(['COPILOT_CLI' => '1']); // Should return true
    

Extension Points

  1. Custom Agents: Extend Detector to add new agents:

    class ExtendedDetector extends Detector
    {
        protected function getAgentEnvironmentVariables(): array
        {
            return array_merge(parent::getAgentEnvironmentVariables(), [
                'MY_AGENT' => ['MY_AGENT_VAR', 'MY_AGENT_TOKEN'],
            ]);
        }
    }
    
  2. Configuration: Inject config (e.g., disable certain agents):

    $detector = new Detector(['disabled_agents' => ['Cursor']]);
    
  3. Laravel Config: Store agent rules in config/agent-detector.php:

    return [
        'disabled_agents' => ['Gemini CLI'],
    ];
    

    Then pass to Detector:

    $detector = new Detector(config('agent-detector'));
    

Tips

  • Combine with Other Packages: Use with spatie/geoip for IP-based bot detection:

    if ($detector->isAgentPresent($_ENV) || $geoip->isTor()) {
        abort(403);
    }
    
  • Rate Limiting: Block agents at the router level:

    Route::middleware(['block.agents', 'throttle:60'])->group(...);
    
  • Telemetry: Track agent types:

    $agentType = $detector->getAgentType($_ENV);
    Log::info('Agent type detected', ['type' => $agentType]);
    

    (Note: Requires extending Detector to expose getAgentType.)

  • CI/CD Optimization: Use in phpunit.xml:

    <env name="COPILOT_CLI" value="1" />
    

    Then skip heavy tests in phpunit.xml or phpunit.php:

    if ($detector->isAgentPresent($_ENV)) {
        $this->markTestSkipped('Running in CI environment');
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor