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

Technical Evaluation

Architecture Fit

  • Lightweight & Non-Invasive: The package is designed as a utility library with minimal dependencies, making it easy to integrate into existing Laravel applications without requiring architectural changes. It operates at the application layer, detecting environment variables or filesystem markers without modifying core Laravel components.
  • Environment-Aware: Leverages PHP’s native environment variables and filesystem checks, which aligns well with Laravel’s configuration-driven and environment-aware architecture (e.g., .env files, service providers).
  • Extensible: Supports custom agent detection via the AI_AGENT environment variable, allowing teams to adapt the package to future or proprietary AI tools without forking the library.

Integration Feasibility

  • Laravel-Native: The package is officially maintained by the Laravel team, ensuring compatibility with Laravel’s ecosystem (e.g., service containers, middleware, and event systems). The namespace (Laravel\AgentDetector) and Laravel-style naming conventions reduce friction.
  • Standalone or Service Provider: Can be used as a standalone utility (e.g., in middleware, commands, or controllers) or wrapped in a Laravel service provider for centralized access.
  • Middleware Integration: Ideal for gating access to sensitive endpoints (e.g., admin panels, API keys) or modifying behavior dynamically (e.g., disabling rate limits for AI agents).

Technical Risk

  • False Positives/Negatives: Detection relies on environment variables or filesystem markers, which may not cover all AI agent scenarios (e.g., headless agents without standard env vars). Risk mitigated by:
    • Community-driven updates (e.g., new agents like v0 or Cowork are added via PRs).
    • Custom detection fallback (AI_AGENT env var).
  • PHP Version Dependency: Requires PHP 8.2+, which may exclude legacy Laravel applications (e.g., LTS versions on PHP 8.1). Mitigation: Evaluate compatibility with your PHP version or use a polyfill.
  • Performance Overhead: Minimal, as detection involves simple env var checks or filesystem operations. No database or external API calls.
  • Breaking Changes: v2.0.0 introduced namespace changes and constructor updates, but the API remains stable for most use cases. Mitigation: Test thoroughly if upgrading from v1.x.

Key Questions

  1. Use Case Clarity:
    • Will this be used for security (e.g., blocking AI access to sensitive data), analytics (e.g., tracking AI usage), or feature gating (e.g., enabling AI-specific workflows)?
    • Example: "Should we block Claude from accessing the /admin route?"
  2. Agent Coverage:
    • Are the supported agents (e.g., Copilot, Claude, Replit) relevant to your team’s workflow? If not, can custom detection suffice?
  3. Integration Points:
    • Where in the stack should detection occur? Options:
      • Middleware: Global detection for all requests (e.g., HandleAgentDetection).
      • Service Provider: Centralized access via the container (e.g., app()->make(AgentDetector::class)).
      • Commands/Artisans: Detect AI usage during CLI tasks (e.g., php artisan migrate).
  4. False Positive Tolerance:
    • How will you handle edge cases (e.g., a developer’s local env var accidentally triggering detection)?
  5. Future-Proofing:
    • Will you contribute to the package if new agents emerge (e.g., via GitHub PRs)?
  6. Testing Strategy:
    • How will you verify detection works in CI/CD pipelines (e.g., GitHub Actions) and production environments?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Perfect fit for Laravel applications due to:
    • Native PHP integration (no JavaScript/Node.js dependencies).
    • Compatibility with Laravel’s service container, middleware, and configuration systems.
    • Alignment with Laravel’s environment-based workflows (e.g., .env files).
  • Non-Laravel PHP: Can be used in any PHP 8.2+ application, though Laravel-specific features (e.g., service providers) won’t apply.

Migration Path

  1. Installation:
    composer require laravel/agent-detector
    
    • Risk: None. Composer handles dependencies automatically.
  2. Basic Usage:
    • Standalone: Use detectAgent() in any PHP file.
      $result = detectAgent();
      if ($result->isAgent) { ... }
      
    • Laravel Service Provider: Register the detector as a singleton for global access.
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(AgentDetector::class, function () {
              return new AgentDetector();
          });
      }
      
  3. Middleware Integration (Recommended for HTTP-based detection):
    // app/Http/Middleware/DetectAgentMiddleware.php
    public function handle(Request $request, Closure $next)
    {
        $result = detectAgent();
        if ($result->isAgent) {
            // Example: Block access or log the agent
            abort(403, 'AI agents not allowed.');
        }
        return $next($request);
    }
    
    Register in app/Http/Kernel.php:
    protected $middleware = [
        \App\Http\Middleware\DetectAgentMiddleware::class,
    ];
    
  4. Custom Detection:
    • Set AI_AGENT=my-custom-agent in your environment to test custom detection.

Compatibility

  • Laravel Versions: Works with Laravel 8+ (PHP 8.2+). Test with your specific Laravel version.
  • PHP Extensions: No additional extensions required beyond PHP core.
  • Environment Variables: Detection relies on env vars (e.g., CLAUDE_CODE), so ensure your deployment platform (e.g., Docker, Heroku, AWS) supports passing these variables.

Sequencing

  1. Phase 1: Proof of Concept
    • Integrate detectAgent() in a non-critical endpoint (e.g., a test route).
    • Verify detection works for known agents (e.g., Copilot, Claude) in your dev environment.
  2. Phase 2: Middleware Rollout
    • Implement DetectAgentMiddleware to gate sensitive routes.
    • Test with both AI and non-AI requests.
  3. Phase 3: Analytics/Logging
    • Log agent detections to monitor usage (e.g., Laravel’s logging system).
    • Example:
      if ($result->isAgent) {
          Log::info('AI Agent detected', ['agent' => $result->name]);
      }
      
  4. Phase 4: Customization
    • Extend detection for internal tools or add custom logic (e.g., rate limiting for AI agents).

Operational Impact

Maintenance

  • Low Effort:
    • No database migrations or schema changes required.
    • Updates can be handled via Composer (composer update laravel/agent-detector).
  • Dependency Updates:
    • Monitor the GitHub Releases for breaking changes (e.g., new PHP versions).
    • Test updates in a staging environment before production deployment.
  • Customization:
    • If extending detection (e.g., adding new agents), contribute upstream or fork the package.

Support

  • Troubleshooting:
    • Common issues:
      • False negatives: Ensure env vars (e.g., CLAUDE_CODE) are set correctly in your deployment environment.
      • False positives: Verify no local env vars are leaking into production.
    • Debugging tip: Use AgentDetector::AGENT_ENV_VARS to inspect detected variables.
  • Community:
    • Active GitHub repo with responsive maintainers (Laravel team).
    • Issues and PRs are addressed promptly (e.g., #17 merged in 2 days).

Scaling

  • Performance:
    • Detection is O(1) (environment variable checks), so no scaling concerns.
    • Even at high traffic (e.g., 10K+ RPS), the overhead is negligible.
  • Distributed Systems:
    • Works seamlessly in containerized environments (e.g., Docker, Kubernetes) as long as env vars are passed correctly.
    • Example Docker setup:
      ENV CLAUDE_CODE=your-value  # If using Claude
      
  • Multi-Region Deployments:
    • No regional dependencies; detection is local to the PHP process.

Failure Modes

Failure Scenario Impact Mitigation
Env var not set for known agent False negative (agent undetected) Use custom AI_AGENT fallback or log warnings.
Custom env var conflicts False positive (non-agent detected) Validate env vars against a whitelist (e.g., AgentDetector::AGENT_ENV_VARS).
PHP version incompatibility Package fails to load Pin to a compatible version in composer.json (e.g.,
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