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

Technical Evaluation

Architecture Fit

  • Lightweight & Modular: The package is a standalone utility with minimal dependencies, making it easy to integrate into existing Laravel or PHP applications without architectural overhead.
  • Environment-Based Detection: Relies on environment variables and filesystem checks, which aligns well with Laravel’s configuration-driven approach (e.g., .env files).
  • Extensible: Supports custom agent detection via AI_AGENT env var, allowing future-proofing for new tools.
  • Laravel-Native: Designed for Laravel (namespace Laravel\AgentDetector), but works in vanilla PHP due to its simplicity.

Integration Feasibility

  • Zero-Blocking: Detection is non-intrusive; can be called anywhere in the application lifecycle (e.g., middleware, service providers, or business logic).
  • Dependency-Free: Only requires PHP 8.2+, no external services or databases.
  • Laravel Service Provider: Can be bootstrapped in AppServiceProvider for global access via a facade or singleton.
  • Middleware Integration: Ideal for gating agent-specific logic (e.g., disabling features or logging agent interactions).

Technical Risk

  • False Positives/Negatives: Detection relies on env vars/filesystem checks, which may not cover all edge cases (e.g., custom agents without AI_AGENT). Mitigation: Use alongside other heuristics (e.g., request headers, user-agent parsing).
  • Namespace Changes: Breaking change in v2.0.0 (old AgentDetectorLaravel\AgentDetector). Ensure all references are updated.
  • Performance: Minimal overhead, but repeated calls in hot paths (e.g., per-request middleware) could be optimized via caching.
  • Maintenance: Actively maintained (recent releases, CI/CD), but community-driven. Monitor for new agent additions.

Key Questions

  1. Use Case Clarity:
    • Is detection for security (e.g., blocking agent access), analytics (tracking agent usage), or feature gating (e.g., disabling agent-specific tools)?
    • Example: Should agents trigger rate-limiting or logging?
  2. False Positive Tolerance:
    • How critical is accuracy? For example, misclassifying a dev’s local setup as an agent could break workflows.
  3. Integration Points:
    • Where in the app should detection occur? (e.g., global middleware vs. per-route).
    • Should results be cached (e.g., per-request or session-wide)?
  4. Custom Agent Support:
    • Will the team need to extend detection for internal tools? If so, plan for custom env vars or filesystem markers.
  5. Version Alignment:
    • Is the app using Laravel 10+ (which may have built-in agent detection in future)? Avoid duplication.

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Provider: Register a singleton or facade for global access:
      // app/Providers/AppServiceProvider.php
      public function boot(): void {
          $this->app->singleton(AgentDetector::class);
      }
      
    • Middleware: Create middleware to attach agent metadata to requests:
      public function handle(Request $request, Closure $next) {
          $request->merge(['is_agent' => detectAgent()->isAgent]);
          return $next($request);
      }
      
    • Service Container: Bind AgentDetector to an interface for testability.
  • Vanilla PHP:
    • Use the standalone detectAgent() function in CLI scripts or non-Laravel apps.
  • Testing:
    • Mock AgentDetector in unit tests using PHP’s getenv() overrides or filesystem stubs.

Migration Path

  1. Assessment Phase:
    • Audit existing agent detection logic (if any) for overlap or gaps.
    • Test false positives/negatives with your dev/prod environments.
  2. Pilot Integration:
    • Start with a single use case (e.g., logging agent interactions) before scaling.
    • Example: Log agent detections to a separate table in the database.
  3. Full Rollout:
    • Replace custom detection logic with AgentDetector.
    • Update CI/CD pipelines to set AI_AGENT for testing (e.g., AI_AGENT=github-copilot).
  4. Deprecation:
    • Phase out legacy detection methods post-migration.

Compatibility

  • PHP 8.2+: Ensure your app meets this requirement (use composer require php:^8.2 if needed).
  • Laravel 10+: No conflicts; package is framework-agnostic.
  • Environment Variables:
    • Ensure .env files are loaded early (Laravel handles this by default).
    • For CLI scripts, set env vars explicitly:
      AI_AGENT=my-agent php artisan my:command
      
  • Filesystem Checks:
    • Agents like Devin rely on /opt/.devin; ensure your deployment has read access.

Sequencing

  1. Dependency Installation:
    composer require laravel/agent-detector
    
  2. Namespace Update:
    • Replace use AgentDetector\... with use Laravel\AgentDetector\... (if upgrading from v1.x).
  3. Integration:
    • Add detection to AppServiceProvider or a dedicated service class.
    • Example:
      // app/Services/AgentService.php
      public function isAgent(): bool {
          return detectAgent()->isAgent;
      }
      
  4. Testing:
    • Write tests for edge cases (e.g., missing env vars, custom agents).
    • Example test:
      public function test_agent_detection() {
          putenv('AI_AGENT=github-copilot');
          $this->assertTrue(detectAgent()->isAgent);
      }
      
  5. Monitoring:
    • Log detection results to track accuracy and coverage.

Operational Impact

Maintenance

  • Low Effort:
    • No database migrations or schema changes required.
    • Updates are minimal (Composer updates + potential env var additions).
  • Dependency Updates:
    • Monitor for breaking changes (e.g., new KnownAgent values).
    • Example: If a new agent (e.g., "LocalAI") is added, update your logic to handle it.
  • Documentation:
    • Add internal docs for:
      • How to set AI_AGENT for testing.
      • List of supported agents and their env vars.
      • False positive/negative scenarios.

Support

  • Troubleshooting:
    • Common issues:
      • False negatives: Verify env vars are set in the correct environment (e.g., .env.testing for tests).
      • False positives: Check for conflicting env vars (e.g., AI_AGENT set accidentally in production).
    • Debugging tools:
      • Log all env vars during detection for diagnostics:
        dd(getenv(), detectAgent());
        
  • Support Matrix:
    Scenario Support Level Notes
    Basic detection High Core functionality.
    Custom agent support Medium Requires env var setup.
    False positives Low May need app-specific heuristics.
    Performance issues High Optimize caching if needed.

Scaling

  • Performance:
    • Per-Request Overhead: Negligible (~1ms for env var checks).
    • Caching: Cache results in memory (e.g., Laravel’s cache) or per-request if detection is expensive.
      // Cache for 1 minute
      $result = Cache::remember('agent_detection', 60, fn() => detectAgent());
      
    • Bulk Detection: For CLI scripts, batch detection if processing multiple files.
  • Distributed Systems:
    • Agent detection is stateless; works in microservices or serverless (e.g., AWS Lambda).
    • Ensure env vars are passed correctly in containerized environments (e.g., Docker).

Failure Modes

Failure Mode Impact Mitigation Strategy
Env var not set False negative (agent undetected) Fallback to isAgent = false or custom logic.
Filesystem permission error Devin/Antigravity undetected Graceful fallback (e.g., assume not an agent).
Package update breaks code Namespace/interface changes Pin version in composer.json temporarily.
Custom agent misconfigured False positive Validate AI_AGENT values against a whitelist.

Ramp-Up

  • Developer Onboarding:
    • Training: 15-minute session on:
      • How to use detectAgent() in code.
      • Setting AI_AGENT for local testing.
      • Common pitfalls (e.g., env var precedence).
    • Cheat Sheet:
      ## Agent Detection Quick Start
      - **Detect**: `detectAgent()->isAgent`
      - **Test Locally**: `AI_AG
      
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle