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

laravel/agent-detector

Lightweight PHP utility for detecting whether your Laravel/PHP app is running inside an AI agent or automated dev environment. Identifies known agents (e.g., Cursor, Gemini, Codex, Claude) via env vars, with a simple API and helper function.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation: Add the package via Composer:

    composer require laravel/agent-detector
    

    Requires PHP 8.2+.

  2. First Check: Import and use the detection in your entry point (e.g., bootstrap/app.php, routes/web.php, or a service provider):

    use Laravel\AgentDetector\AgentDetector;
    
    $result = AgentDetector::detect();
    
  3. Basic Use Case: Conditionally execute logic for AI agents:

    if ($result->isAgent) {
        // Disable heavy operations, mock data, or log AI activity
        info("Running in AI environment: {$result->name}");
    }
    
  4. Check for Specific Agents: Use the KnownAgent enum for precise targeting:

    if ($result->knownAgent() === KnownAgent::Claude) {
        // Custom logic for Claude
    }
    

Implementation Patterns

1. Middleware for Global Detection

Create middleware to detect AI agents across all requests:

// app/Http/Middleware/DetectAgent.php
public function handle(Request $request, Closure $next) {
    $result = AgentDetector::detect();
    $request->attributes->add(['is_agent' => $result->isAgent, 'agent_name' => $result->name]);
    return $next($request);
}

Register in app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\DetectAgent::class,
];

2. Service Provider Initialization

Initialize detection early in a service provider:

// app/Providers/AppServiceProvider.php
public function boot() {
    $this->app->singleton('agent-detector', function () {
        return AgentDetector::detect();
    });
}

Access via dependency injection:

public function __construct(private readonly AgentResult $detector) {}

3. Conditional Testing Logic

Skip slow tests or mock responses when running in an AI environment:

// tests/Feature/SomeTest.php
public function testSomething(): void {
    $detector = AgentDetector::detect();
    if ($detector->isAgent) {
        $this->mockHttpResponses();
    }
    // ...
}

4. Environment-Specific Configuration

Load AI-specific configs (e.g., .env.agent):

// config/agent.php
return [
    'enabled' => env('AGENT_ENABLED', $detector->isAgent),
    // ...
];

5. Custom Agent Detection

Extend detection for proprietary tools by setting AI_AGENT:

AI_AGENT=my-tool php artisan tinker

Or programmatically:

putenv('AI_AGENT=my-tool');

Gotchas and Tips

Pitfalls

  1. False Positives: Some CI/CD environments (e.g., GitHub Actions) may trigger detection unintentionally. Test in your target environments.
  2. Namespace Changes: v2.0.0 moved the namespace to Laravel\AgentDetector (previously AgentDetector). Update imports if upgrading.
  3. File-Based Detection: Checks like /opt/.devin may fail in containerized or cloud environments. Test thoroughly.

Debugging

  • Inspect Raw Detection: Use AgentDetector::AGENT_ENV_VARS to debug environment variables:
    dd(AgentDetector::AGENT_ENV_VARS);
    
  • Override Detection: Temporarily mock detection for testing:
    $detector = new AgentResult('test-agent');
    $this->app->instance('agent-detector', $detector);
    

Tips

  1. Performance: Detection is lightweight (~1ms). Cache results if called frequently:
    $detector = app()->bound('agent-detector') ?? AgentDetector::detect();
    app()->singleton('agent-detector', $detector);
    
  2. Extending Detection: Add custom agents by extending AgentDetector:
    class CustomAgentDetector extends AgentDetector {
        protected static function detectCustomAgent(): ?string {
            return getenv('MY_CUSTOM_AGENT') ? 'my-agent' : null;
        }
    }
    
  3. Label Method: Use KnownAgent::from($result->name)->label() for human-readable names:
    echo KnownAgent::from($result->name)->label(); // "GitHub Copilot"
    
  4. CI/CD Integration: Exclude AI-specific logic from CI pipelines by checking GITHUB_ACTIONS or similar:
    if ($detector->isAgent && !env('CI')) {
        // AI-only logic
    }
    
  5. Deprecation: Monitor the KnownAgent enum for breaking changes (e.g., renamed agents).
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.
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment