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.
Installation:
composer require laravel/agent-detector
Ensure your project uses PHP 8.2+.
First Use Case: Detect if your code is running inside an AI agent or automated environment:
use Laravel\AgentDetector\AgentDetector;
$result = AgentDetector::detect();
if ($result->isAgent) {
echo "Running inside: {$result->name}";
}
Check for Specific Agents:
use Laravel\AgentDetector\KnownAgent;
if ($result->knownAgent() === KnownAgent::Claude) {
echo "Hello from Claude!";
}
Standalone Function:
use function Laravel\AgentDetector\detectAgent;
$result = detectAgent();
KnownAgent Enum: Lists all detectable agents and their detection methods.AgentDetector Class: Core logic for detection.Middleware for Agent Detection: Create a middleware to detect agents early in the request lifecycle:
use Laravel\AgentDetector\AgentDetector;
use Closure;
class DetectAgentMiddleware
{
public function handle($request, Closure $next)
{
$result = AgentDetector::detect();
if ($result->isAgent) {
$request->merge(['is_agent' => true, 'agent_name' => $result->name]);
}
return $next($request);
}
}
Register in app/Http/Kernel.php:
protected $middleware = [
\App\Http\Middleware\DetectAgentMiddleware::class,
];
Service Provider Integration: Bind the detector to the container for easy access:
use Laravel\AgentDetector\AgentDetector;
public function register()
{
$this->app->singleton(AgentDetector::class, function () {
return new AgentDetector();
});
}
Use in controllers/services:
use Laravel\AgentDetector\AgentDetector;
public function __construct(private AgentDetector $detector) {}
public function someMethod()
{
$result = $this->detector->detect();
// Logic based on agent detection
}
Conditional Logic in Routes: Restrict routes or API endpoints for agents:
Route::middleware(['agent'])->group(function () {
Route::get('/agent-only', function () {
return "This is for agents only!";
});
});
Create a middleware:
public function handle($request, Closure $next)
{
$result = AgentDetector::detect();
if (!$result->isAgent) {
abort(403, 'Access denied. This endpoint is for agents only.');
}
return $next($request);
}
Environment-Specific Configuration: Load different configs or settings based on the detected agent:
$result = AgentDetector::detect();
if ($result->knownAgent() === KnownAgent::Copilot) {
config(['services.copilot.enabled' => true]);
}
Logging Agent Activity: Log agent interactions for debugging or analytics:
use Illuminate\Support\Facades\Log;
$result = AgentDetector::detect();
if ($result->isAgent) {
Log::info("Agent detected", [
'agent' => $result->name,
'ip' => request()->ip(),
]);
}
AI_AGENT environment variable to simulate agent environments in tests:
AI_AGENT=github-copilot php artisan test
AgentDetector class or extend its functionality:
class CustomAgentDetector extends AgentDetector
{
protected function detectCustomAgent(): ?string
{
if (file_exists('/custom/agent/path')) {
return 'custom-agent';
}
return null;
}
}
$result = cache()->remember('agent_detection', now()->addMinutes(5), function () {
return AgentDetector::detect();
});
False Positives:
COPILOT_*) might be set in non-agent contexts. Verify detection logic in edge cases.COPILOT_MODEL with AI_AGENT).Namespace Changes:
AgentDetector to Laravel\AgentDetector in v2.0.0. Update imports if migrating from older versions.Constructor Changes in AgentResult:
AgentResult constructor no longer accepts isAgent. It is now a readonly property set internally:
// Old (v1.x)
new AgentResult('copilot', true);
// New (v2.x)
new AgentResult('copilot'); // isAgent is inferred
File-Based Detection:
/opt/.devin might fail in containerized environments or CI/CD pipelines. Test thoroughly in your deployment setup.Environment Variable Conflicts:
Claude and Cowork) share environment variables (CLAUDECODE). Ensure logic handles overlaps correctly.Inspect Detection Logic:
The AgentDetector class exposes AGENT_ENV_VARS (visible since v2.0.1), which lists all checked environment variables:
dd(AgentDetector::AGENT_ENV_VARS);
Use this to debug why an agent isn’t detected.
Log Detection Steps: Add debug logs to trace detection:
$detector = new AgentDetector();
$envVars = $detector->getEnvironmentVariables();
Log::debug('Checked env vars:', $envVars);
Test Custom Agents:
For custom agents, verify the AI_AGENT variable is set correctly:
AI_AGENT=my-test-agent php artisan tinker
Then check detection:
use Laravel\AgentDetector\AgentDetector;
AgentDetector::detect(); // Should return `my-test-agent`
Extending Detection:
Add new agents by extending AgentDetector or contributing to the package. The detect() method checks environment variables and file paths in a modular way:
protected function detectCustomAgent(): ?string
{
if (getenv('MY_CUSTOM_AGENT_VAR')) {
return 'my-custom-agent';
}
return null;
}
Performance Optimization: If detection is called frequently (e.g., in loops), cache results or use a singleton pattern to avoid redundant checks.
CI/CD Integration: Use agent detection to skip or modify tests in CI pipelines:
if (AgentDetector::detect()->isAgent) {
$this->markTestSkipped('Skipping in agent environment.');
}
Human vs. Agent Logic: Implement feature flags or conditional logic to disable certain functionalities for agents:
if (!AgentDetector::detect()->isAgent) {
// Enable human-specific features
}
Document Agent Behavior: Clearly document in your codebase how agents interact with your application (e.g., "This endpoint is optimized for GitHub Copilot"). Example:
/**
* @return \Illuminate\Http\JsonResponse
* @note Returns simplified data for AI agents to improve response time.
*/
public function getData()
{
$result = AgentDetector::detect();
if ($result->knownAgent() === KnownAgent::Copilot) {
return response()->json(['simplified' => true]);
}
return response()->json($this->fullData());
}
Security Considerations: Avoid exposing sensitive data or logic paths when an agent is detected. Use agent detection to enforce security policies:
if (AgentDetector::detect()->isAgent) {
abort_if(
!$user->isTrusted(),
403,
'Agents require trusted user access.'
);
}
How can I help you explore Laravel packages today?