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 8.2+ utility to detect if your app is running inside an AI agent or automated dev environment. Supports Claude, Cursor, Gemini, Codex, Replit, Devin, and more via env vars or file checks, with a simple API and helper function.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Lightweight and modular: The package is a single-purpose utility with no Laravel-specific dependencies, making it easy to integrate into existing Laravel applications without architectural disruption. It aligns well with Laravel’s service container and middleware patterns for runtime checks.
  • Environment-variable-based detection: Leverages well-known env vars (e.g., GITHUB_ACTIONS, CLAUDE_CODE) that are already used in Laravel’s .env and CI/CD pipelines, reducing friction for adoption.
  • Extensible design: Supports custom agents via AI_AGENT env var, allowing future-proofing for proprietary or niche tools. The knownAgent() method enables precise branching logic (e.g., "block Claude but allow Cursor").
  • PHP 8.2+ requirement: Compatible with Laravel 10+ (PHP 8.2+), ensuring no version conflicts with modern Laravel stacks.

Integration Feasibility

  • Minimal boilerplate: Installation is a single composer require command, and usage is as simple as a one-liner (AgentDetector::detect()). No database migrations, config changes, or complex setup are required.
  • Laravel-native integration points:
    • Middleware: Ideal for HTTP routes (e.g., block agent access to admin panels).
    • Console commands: Gate sensitive artisan commands (e.g., tinker, migrate).
    • Service providers: Inject agent context globally for telemetry or logging.
    • Event listeners: Adapt behavior in queues or scheduled tasks (though env vars may not propagate reliably here).
  • Standalone function: detectAgent() allows quick checks in one-off scripts or tests without instantiating a class.

Technical Risk

  • False positives/negatives:
    • Risk: Env vars may not propagate in all Laravel contexts (e.g., queues, scheduled tasks, or serverless environments). Detection reliability depends on the consistency of env var injection (e.g., REPL_ID may not exist in Docker).
    • Mitigation: Combine with Laravel’s existing signals (e.g., APP_ENV === 'local', APP_DEBUG === false) for defense in depth. Test in all execution environments (CLI, HTTP, queues).
  • Limited adoption: 0 dependents and 33 stars suggest unproven real-world usage. The package may lack edge-case handling (e.g., nested agents, custom CI setups).
    • Mitigation: Implement fallback heuristics (e.g., check for php://input or $_SERVER['REMOTE_ADDR'] patterns in CI/CD IPs).
  • Future maintenance: Last release in 2026-03-11 may indicate stagnation or versioning risks. No Laravel-specific tests exist.
    • Mitigation: Fork or extend the package if critical updates are needed. Monitor GitHub for activity.
  • Performance overhead: Minimal, but runtime checks add microseconds to request/CLI execution. Negligible for most use cases but worth profiling in high-throughput systems.

Key Questions

  1. Execution context coverage:
    • Which Laravel execution paths require agent detection? (e.g., CLI commands, HTTP routes, queues, events).
    • Are env vars reliably set in all target contexts? (Test with php artisan tinker, php artisan queue:work, and HTTP requests.)
  2. False positive tolerance:
    • What are the consequences of a false negative (e.g., allowing an agent to run sensitive commands) vs. a false positive (e.g., blocking a legitimate CI pipeline)?
  3. Integration strategy:
    • Should detection be centralized (e.g., middleware) or decentralized (e.g., per-command guards)?
    • How will agent context be surfaced to other parts of the app (e.g., via a service container binding)?
  4. Fallback mechanisms:
    • What heuristics can supplement env var detection (e.g., IP ranges for known CI providers, APP_ENV checks)?
  5. Long-term maintenance:
    • Is the package’s MIT license and open-source nature acceptable for your use case?
    • Are there plans to contribute Laravel-specific tests or integrations (e.g., laravel/agent-detector wrapper)?

Integration Approach

Stack Fit

  • Laravel 10+ (PHP 8.2+): Native compatibility with no conflicts. The package’s simplicity avoids Laravel’s dependency injection system, but it can still be integrated via:
    • Service container: Bind AgentDetector as a singleton for global access.
    • Facade pattern: Create a AgentDetectorFacade for cleaner syntax (e.g., AgentDetector::detect()Agent::detect()).
  • CI/CD pipelines: Directly compatible with env vars set by GitHub Actions, GitLab CI, or other providers (e.g., GITHUB_ACTIONS, CI).
  • CLI tools: Works seamlessly with artisan commands, tinker, and custom scripts.
  • HTTP routes: Middleware integration enables agent-aware access control (e.g., block agents from sensitive endpoints).

Migration Path

  1. Pilot phase (low risk):
    • Install the package and test detection in a non-production environment:
      composer require shipfastlabs/agent-detector --dev
      
    • Add a test command to verify detection:
      // app/Console/Commands/TestAgentDetection.php
      use AgentDetector\AgentDetector;
      
      public function handle() {
          $result = AgentDetector::detect();
          $this->line("Agent detected: " . ($result->isAgent ? $result->name : 'None'));
          $this->line("Known agent: " . ($result->knownAgent() ? $result->knownAgent()->value : 'No'));
      }
      
    • Run in various contexts:
      php artisan test:agent-detection  # CLI
      curl -X GET /test-agent           # HTTP (if middleware is added)
      
  2. Core integration:
    • Middleware: Create a CheckAgentMiddleware to block agent access to routes:
      // app/Http/Middleware/CheckAgent.php
      public function handle(Request $request, Closure $next) {
          if (AgentDetector::detect()->isAgent) {
              abort(403, 'Agents are not allowed to access this resource.');
          }
          return $next($request);
      }
      
      Register in app/Http/Kernel.php:
      protected $middleware = [
          \App\Http\Middleware\CheckAgent::class,
      ];
      
    • Console commands: Add guards to sensitive commands:
      // app/Console/Commands/SensitiveCommand.php
      public function handle() {
          if (AgentDetector::detect()->isAgent) {
              $this->error('This command is blocked in automated environments.');
              return;
          }
          // Proceed with command logic...
      }
      
    • Service provider: Bind the detector to the container for global access:
      // app/Providers/AppServiceProvider.php
      public function register() {
          $this->app->singleton('agentDetector', function () {
              return new \AgentDetector\AgentDetector();
          });
      }
      
  3. Advanced use cases:
    • Dynamic configuration: Adapt Laravel’s APP_DEBUG or APP_ENV based on agent context.
    • Telemetry: Log agent-driven operations to a custom table or external service.
    • Custom agents: Set AI_AGENT env vars in CI/CD pipelines for granular control.

Compatibility

  • Laravel-specific considerations:
    • Env vars: Laravel’s .env system already supports env var injection, but ensure CI/CD pipelines propagate agent-specific vars (e.g., CLAUDE_CODE).
    • Execution contexts: Test detection in:
      • CLI (artisan, tinker, custom scripts).
      • HTTP routes (middleware).
      • Queues/jobs (env vars may not propagate; consider fallback logic).
      • Scheduled tasks (same as queues).
    • Caching: If using Laravel’s cache, ensure agent detection isn’t cached (e.g., wrap in Cache::forget() or use Cache::rememberForever() with a unique key).
  • Third-party conflicts: No known conflicts with popular Laravel packages (e.g., laravel/framework, spatie/laravel-permission). The package has no dependencies.

Sequencing

  1. Phase 1: Detection validation (1–2 days):
    • Install and test detection in all target execution contexts.
    • Document false positives/negatives and edge cases.
  2. Phase 2: Core integration (3–5 days):
    • Implement middleware for HTTP routes.
    • Add guards to critical artisan commands.
    • Bind to service container if global access is needed.
  3. Phase 3: Advanced features (optional, 1–2 weeks):
    • Dynamic configuration (e.g., APP_DEBUG adaptation).
    • Telemetry/logging for agent operations.
    • Custom agent support in CI/CD pipelines.
  4. Phase 4: Monitoring and iteration:
    • Log detection results in Sentry or a custom table to track false positives/negatives.
    • Update fallback heuristics based on real-world data.

Operational Impact

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests