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

shipfastlabs/agent-detector

Lightweight PHP/Laravel utility to detect when your code runs inside an AI agent or automated dev environment. Checks common agent-specific environment variables (e.g., Cursor, Gemini, Codex, or custom) and returns agent status and name.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laravel/agent-detector
    

    Ensure your project uses PHP 8.2+.

  2. First Use Case: Detect if your code is running inside an AI agent or automated environment:

    use Laravel\AgentDetector\AgentDetector;
    
    $result = AgentDetector::detect();
    
    if ($result->isAgent) {
        echo "Running inside: {$result->name}";
    }
    
  3. Check for Specific Agents:

    use Laravel\AgentDetector\KnownAgent;
    
    if ($result->knownAgent() === KnownAgent::Claude) {
        echo "Hello from Claude!";
    }
    
  4. Standalone Function:

    use function Laravel\AgentDetector\detectAgent;
    
    $result = detectAgent();
    

Where to Look First

  • README.md: For installation, usage, and supported agents.
  • KnownAgent Enum: Lists all detectable agents and their detection methods.
  • AgentDetector Class: Core logic for detection.

Implementation Patterns

Core Workflows

  1. Middleware for Agent Detection: Create a middleware to detect agents early in the request lifecycle:

    use Laravel\AgentDetector\AgentDetector;
    use Closure;
    
    class DetectAgentMiddleware
    {
        public function handle($request, Closure $next)
        {
            $result = AgentDetector::detect();
    
            if ($result->isAgent) {
                $request->merge(['is_agent' => true, 'agent_name' => $result->name]);
            }
    
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\DetectAgentMiddleware::class,
    ];
    
  2. Service Provider Integration: Bind the detector to the container for easy access:

    use Laravel\AgentDetector\AgentDetector;
    
    public function register()
    {
        $this->app->singleton(AgentDetector::class, function () {
            return new AgentDetector();
        });
    }
    

    Use in controllers/services:

    use Laravel\AgentDetector\AgentDetector;
    
    public function __construct(private AgentDetector $detector) {}
    
    public function someMethod()
    {
        $result = $this->detector->detect();
        // Logic based on agent detection
    }
    
  3. Conditional Logic in Routes: Restrict routes or API endpoints for agents:

    Route::middleware(['agent'])->group(function () {
        Route::get('/agent-only', function () {
            return "This is for agents only!";
        });
    });
    

    Create a middleware:

    public function handle($request, Closure $next)
    {
        $result = AgentDetector::detect();
    
        if (!$result->isAgent) {
            abort(403, 'Access denied. This endpoint is for agents only.');
        }
    
        return $next($request);
    }
    
  4. Environment-Specific Configuration: Load different configs or settings based on the detected agent:

    $result = AgentDetector::detect();
    
    if ($result->knownAgent() === KnownAgent::Copilot) {
        config(['services.copilot.enabled' => true]);
    }
    
  5. Logging Agent Activity: Log agent interactions for debugging or analytics:

    use Illuminate\Support\Facades\Log;
    
    $result = AgentDetector::detect();
    
    if ($result->isAgent) {
        Log::info("Agent detected", [
            'agent' => $result->name,
            'ip' => request()->ip(),
        ]);
    }
    

Integration Tips

  • Testing: Use the AI_AGENT environment variable to simulate agent environments in tests:
    AI_AGENT=github-copilot php artisan test
    
  • Custom Agents: Extend detection by adding custom environment variables or file checks. Override the AgentDetector class or extend its functionality:
    class CustomAgentDetector extends AgentDetector
    {
        protected function detectCustomAgent(): ?string
        {
            if (file_exists('/custom/agent/path')) {
                return 'custom-agent';
            }
    
            return null;
        }
    }
    
  • Performance: Cache detection results if the agent environment is unlikely to change during a request:
    $result = cache()->remember('agent_detection', now()->addMinutes(5), function () {
        return AgentDetector::detect();
    });
    

Gotchas and Tips

Pitfalls

  1. False Positives:

    • Some environment variables (e.g., COPILOT_*) might be set in non-agent contexts. Verify detection logic in edge cases.
    • Tip: Use multiple checks for critical agents (e.g., combine COPILOT_MODEL with AI_AGENT).
  2. Namespace Changes:

    • The package moved from AgentDetector to Laravel\AgentDetector in v2.0.0. Update imports if migrating from older versions.
  3. Constructor Changes in AgentResult:

    • In v2.0.0, the AgentResult constructor no longer accepts isAgent. It is now a readonly property set internally:
      // Old (v1.x)
      new AgentResult('copilot', true);
      
      // New (v2.x)
      new AgentResult('copilot'); // isAgent is inferred
      
  4. File-Based Detection:

    • Checks like /opt/.devin might fail in containerized environments or CI/CD pipelines. Test thoroughly in your deployment setup.
  5. Environment Variable Conflicts:

    • Some agents (e.g., Claude and Cowork) share environment variables (CLAUDECODE). Ensure logic handles overlaps correctly.

Debugging

  • Inspect Detection Logic: The AgentDetector class exposes AGENT_ENV_VARS (visible since v2.0.1), which lists all checked environment variables:

    dd(AgentDetector::AGENT_ENV_VARS);
    

    Use this to debug why an agent isn’t detected.

  • Log Detection Steps: Add debug logs to trace detection:

    $detector = new AgentDetector();
    $envVars = $detector->getEnvironmentVariables();
    Log::debug('Checked env vars:', $envVars);
    
  • Test Custom Agents: For custom agents, verify the AI_AGENT variable is set correctly:

    AI_AGENT=my-test-agent php artisan tinker
    

    Then check detection:

    use Laravel\AgentDetector\AgentDetector;
    AgentDetector::detect(); // Should return `my-test-agent`
    

Tips

  1. Extending Detection: Add new agents by extending AgentDetector or contributing to the package. The detect() method checks environment variables and file paths in a modular way:

    protected function detectCustomAgent(): ?string
    {
        if (getenv('MY_CUSTOM_AGENT_VAR')) {
            return 'my-custom-agent';
        }
        return null;
    }
    
  2. Performance Optimization: If detection is called frequently (e.g., in loops), cache results or use a singleton pattern to avoid redundant checks.

  3. CI/CD Integration: Use agent detection to skip or modify tests in CI pipelines:

    if (AgentDetector::detect()->isAgent) {
        $this->markTestSkipped('Skipping in agent environment.');
    }
    
  4. Human vs. Agent Logic: Implement feature flags or conditional logic to disable certain functionalities for agents:

    if (!AgentDetector::detect()->isAgent) {
        // Enable human-specific features
    }
    
  5. Document Agent Behavior: Clearly document in your codebase how agents interact with your application (e.g., "This endpoint is optimized for GitHub Copilot"). Example:

    /**
     * @return \Illuminate\Http\JsonResponse
     * @note Returns simplified data for AI agents to improve response time.
     */
    public function getData()
    {
        $result = AgentDetector::detect();
        if ($result->knownAgent() === KnownAgent::Copilot) {
            return response()->json(['simplified' => true]);
        }
        return response()->json($this->fullData());
    }
    
  6. Security Considerations: Avoid exposing sensitive data or logic paths when an agent is detected. Use agent detection to enforce security policies:

    if (AgentDetector::detect()->isAgent) {
        abort_if(
            !$user->isTrusted(),
            403,
            'Agents require trusted user access.'
        );
    }
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope