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 Laravel/PHP utility to detect when your code is running inside an AI agent or automated dev environment. Supports multiple known agents (e.g., Cursor, Gemini, Codex, Claude) via environment-variable detection. Requires PHP 8.2+.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Lightweight & Non-Intrusive: The package is a standalone utility with minimal dependencies (PHP 8.2+ only), making it ideal for integration into existing Laravel or PHP applications without architectural overhead.
  • Environment-Based Detection: Relies on environment variables and filesystem checks, which are non-blocking and do not require runtime modifications to the application flow.
  • Extensible Design: Supports custom agent detection via AI_AGENT env var, allowing future-proofing for emerging AI tools.
  • Laravel-Native: Aligns with Laravel’s ecosystem (e.g., enum-based KnownAgent for type safety) but remains framework-agnostic.

Integration Feasibility

  • Zero Configuration: Installation via Composer (composer require laravel/agent-detector) and usage via a single function call (detectAgent()) or class (AgentDetector::detect()).
  • Minimal Boilerplate: No database migrations, service providers, or middleware required. Can be invoked anywhere in the codebase (e.g., middleware, controllers, CLI commands).
  • Standalone or Framework-Agnostic: Works in pure PHP apps, Laravel, or other frameworks. Laravel-specific features (e.g., KnownAgent enum) are optional.

Technical Risk

  • False Positives/Negatives: Detection relies on env vars or filesystem checks, which may not cover all edge cases (e.g., custom agents with non-standard configurations). Risk mitigated by:
    • Community-driven updates (e.g., new agents added via PRs).
    • Custom detection logic via AI_AGENT env var.
  • PHP Version Lock: Requires PHP 8.2+. Risk for legacy systems, but most modern Laravel apps (v9+) already meet this requirement.
  • Performance Impact: Negligible—env var checks are O(1) and executed once per request/CLI invocation.
  • Breaking Changes: v2.0.0 introduced namespace changes, but the package is otherwise backward-compatible. Risk is low for new integrations.

Key Questions

  1. Use Case Clarity:
    • Is detection needed for security (e.g., blocking AI-generated requests), analytics (tracking AI tool usage), or feature gating (e.g., disabling certain endpoints)?
    • Example: "Should we block Claude-generated requests from sensitive APIs?"
  2. Integration Scope:
    • Where will detection be used? (e.g., middleware for all requests, specific controllers, CLI commands).
    • Example: "Do we need to wrap this in a middleware for global detection?"
  3. Custom Agent Support:
    • Will the team need to extend detection for internal tools? If so, how will custom agents be registered/managed?
  4. False Positive Tolerance:
    • What’s the acceptable rate of false positives/negatives? (e.g., "We can tolerate 5% false negatives for Copilot.")
  5. Monitoring:
    • Should detection results be logged or exposed via metrics (e.g., Prometheus) for observability?
  6. Dependency Conflicts:
    • Could this conflict with existing packages (e.g., other env var-based tools)? Unlikely, but worth auditing.

Integration Approach

Stack Fit

  • Laravel Applications: Ideal for Laravel apps due to native enum support (KnownAgent) and Laravel’s env var ecosystem. Works seamlessly with:
    • Middleware (e.g., AgentDetectorMiddleware to block AI requests).
    • Service containers (bind AgentDetector as a singleton).
    • Artisan commands (detect AI usage in CLI tools).
  • Non-Laravel PHP: Fully functional with the standalone detectAgent() function. No framework-specific dependencies beyond PHP 8.2+.
  • Microservices/CLI Tools: Perfect for detecting AI usage in background workers (e.g., queues) or CLI scripts.

Migration Path

  1. Evaluation Phase:
    • Install the package in a staging environment: composer require laravel/agent-detector --dev.
    • Test detection in various contexts (e.g., local dev, CI/CD, production-like env vars).
    • Example: Simulate AI agents using env vars (e.g., AI_AGENT=github-copilot).
  2. Pilot Integration:
    • Start with a single use case (e.g., logging AI detections in a controller).
    • Example:
      use Laravel\AgentDetector\detectAgent;
      
      $result = detectAgent();
      logger()->info("AI Agent Detected", ["agent" => $result->name]);
      
  3. Scaled Rollout:
    • Option A (Middleware): Create a global middleware to attach AI detection to all requests.
      // app/Http/Middleware/DetectAgent.php
      public function handle(Request $request, Closure $next) {
          $result = detectAgent();
          $request->merge(['is_ai_agent' => $result->isAgent]);
          return $next($request);
      }
      
    • Option B (Service Provider): Bind AgentDetector to the container for dependency injection.
      // app/Providers/AppServiceProvider.php
      public function register() {
          $this->app->singleton(AgentDetector::class);
      }
      
    • Option C (Event Listeners): Trigger events when AI agents are detected (e.g., AiAgentDetected).

Compatibility

  • Laravel Versions: Compatible with Laravel 9+ (PHP 8.2+). For older versions, use v1.x of the package.
  • PHP Extensions: No extensions required. Works with any PHP runtime (CLI, Apache, Nginx, etc.).
  • Environment Variables: Detection relies on env vars (e.g., COPILOT_MODEL). Ensure these are set correctly in deployment pipelines (e.g., GitHub Actions, Docker).
  • Customization: Override detection logic by extending AgentDetector or using the AGENT_ENV_VARS constant to add custom env vars.

Sequencing

  1. Phase 1: Detection Only (1–2 days):
    • Install and test detection in isolation.
    • Verify all supported agents are detected correctly.
  2. Phase 2: Integration (2–3 days):
    • Choose integration method (middleware/service provider).
    • Implement use case (e.g., logging, blocking, or analytics).
  3. Phase 3: Validation (1 day):
    • Test with real AI agents (e.g., Copilot, Claude) in staging.
    • Mock edge cases (e.g., missing env vars, custom agents).
  4. Phase 4: Monitoring (Ongoing):
    • Add observability (e.g., log detections, alert on unexpected agents).
    • Plan for future agent additions (e.g., subscribe to package updates).

Operational Impact

Maintenance

  • Low Effort: Minimal maintenance required. Updates are backward-compatible (except major versions).
  • Dependency Updates: Monitor for new agent additions (e.g., monthly Composer updates).
  • Custom Logic: If extending detection, maintain custom env var mappings or logic separately.

Support

  • Troubleshooting:
    • Common issues: False negatives due to missing env vars or custom agent misconfiguration.
    • Debugging: Use AgentDetector::AGENT_ENV_VARS to inspect detected env vars.
  • Community: Active GitHub repo with responsive maintainers (Laravel team).
  • Documentation: Comprehensive README and changelog. Add internal docs for custom use cases.

Scaling

  • Performance: Negligible overhead. Env var checks are O(1) and cached per request.
  • Concurrency: Thread-safe (stateless design). No locks or shared resources.
  • Horizontal Scaling: No impact on distributed systems (e.g., Kubernetes, serverless).

Failure Modes

Failure Scenario Impact Mitigation
False positive detection Legitimate requests blocked Whitelist known good env vars; test thoroughly.
False negative detection AI requests slip through Monitor logs/metrics; extend detection rules.
Env var injection attack Malicious env vars trigger detection Validate env vars against a allowlist (e.g., KnownAgent enum).
Package update breaks compatibility New major version introduces issues Pin to a stable minor version (e.g., ^2.0).
Custom agent misconfiguration Undetected or misclassified agents Document custom agent setup; use AI_AGENT for clarity.

Ramp-Up

  • Developer Onboarding (1 hour):
    • Explain basic usage (detectAgent() vs. AgentDetector::detect()).
    • Show how to check for specific agents (e.g., KnownAgent::Claude).
  • Team Adoption (1 day):
    • Demo integration in a shared component (e.g., middleware).
    • Provide a template for custom detection logic.
  • CI/CD Integration (0.5 day):
    • Add env var checks to deployment pipelines (e.g., GitHub Actions).
    • Example:
      jobs:
        test:
          env:
            AI_AGENT:
      
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata