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/Laravel utility to detect when your code runs inside an AI agent or automated dev environment. Detect via AgentDetector::detect() or detectAgent(), identify known agents like Cursor, Gemini, Codex, Claude, or custom via env vars.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/agent-detector
    

    Requires PHP 8.2+.

  2. First Detection Check:

    use Laravel\AgentDetector\AgentDetector;
    
    $result = AgentDetector::detect();
    if ($result->isAgent) {
        echo "Detected agent: " . $result->name;
    }
    
  3. Quick Standalone Usage:

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

First Use Case

Conditional Logic for AI Agents:

if ($agent->knownAgent() === KnownAgent::Claude) {
    // Provide Claude-specific guidance or hints
    return "Claude-specific response";
}

Implementation Patterns

Core Workflows

1. Agent-Aware Feature Flags

// Disable heavy computations for AI agents
if ($agent->isAgent) {
    return response()->json(['warning' => 'AI agents may not support this feature']);
}

2. Agent-Specific Responses

switch ($agent->knownAgent()) {
    case KnownAgent::Copilot:
        return "Copilot: Use `php artisan make:model` for scaffolding";
    case KnownAgent::Replit:
        return "Replit: Run `composer install` first";
    default:
        return "General instructions...";
}

3. Environment Validation

// Block AI agents from sensitive operations
if ($agent->isAgent && $request->is('admin/*')) {
    abort(403, 'AI agents cannot access admin routes');
}

Integration Tips

Laravel Service Provider

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

Usage in Controllers:

use Illuminate\Support\Facades\App;

if (App::make('agent')->isAgent) {
    // Agent-specific logic
}

Middleware for Agent Detection

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

Route Middleware:

Route::middleware(['detect.agent'])->group(function () {
    // Agent-aware routes
});

Blade Directives

// app/Providers/BladeServiceProvider.php
Blade::directive('agentCheck', function ($expression) {
    return "<?php if (Laravel\\AgentDetector\\AgentDetector::detect()->{$expression}): ?>";
});

Usage in Views:

@agentCheck('isAgent')
    <p>This content is for AI agents only.</p>
@endagentCheck

Gotchas and Tips

Pitfalls

  1. False Positives:

    • Some CI/CD environments may trigger agent detection. Test in your deployment pipeline.
    • Example: GitHub Actions might set GITHUB_ACTIONS=true, which isn’t directly detected but could conflict with agent logic.
  2. Environment Variable Overrides:

    • Agents may set multiple env vars (e.g., COPILOT_MODEL and AI_AGENT). Prioritize checks based on your use case:
      if ($agent->knownAgent() === KnownAgent::Copilot) {
          // Handle Copilot specifically
      } elseif ($agent->isAgent) {
          // Fallback for other agents
      }
      
  3. Custom Agent Naming:

    • The AI_AGENT env var supports any value, but ensure consistency in your team’s naming conventions (e.g., my-team-agent).

Debugging

  1. Inspect All Detected Agents:

    $result = AgentDetector::detect();
    dd($result->name, $result->isAgent, $result->envVars);
    
    • Useful for diagnosing false positives/negatives.
  2. Check Environment Variables:

    env | grep -i "AI_AGENT\|COPILOT\|CLAUDE"
    
    • Verify which vars are set in your environment.
  3. Update Detection Logic:

    • If a new agent isn’t detected, check the supported agents list and contribute a PR to add its env vars.

Tips

  1. Performance:

    • Cache the detection result if called frequently (e.g., in middleware):
      $agent = Cache::remember('agent_detection', now()->addHours(1), fn() => AgentDetector::detect());
      
  2. Extending Detection:

    • Add custom agents by extending the KnownAgent enum or modifying AgentDetector::AGENT_ENV_VARS:
      AgentDetector::AGENT_ENV_VARS['MY_CUSTOM_AGENT'] = ['MY_CUSTOM_VAR'];
      
  3. Testing:

    • Mock agent detection in tests:
      $this->app->instance('agent', (new AgentResult('test-agent', true)));
      
  4. Human vs. Agent Logic:

    • Useful for:
      • Disabling interactive prompts for AI agents.
      • Serving lighter responses (e.g., no CSRF tokens for automated tests).
      • Logging agent interactions separately.
  5. Security:

    • Never expose agent detection results in production error pages or logs to avoid leaking sensitive info.

Pro Tip: Combine with laravel/ai packages for richer AI integration (e.g., laravel/ai + laravel/agent-detector for agent-aware AI responses).

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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony