PHPackages                             impruthvi/agent-detector-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. impruthvi/agent-detector-laravel

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

impruthvi/agent-detector-laravel
================================

Laravel companion for agent-detector: CSRF bypass, agent log channel, and session headers for AI coding agents.

v1.0.0(3mo ago)01MITPHPPHP ^8.2|^8.5CI passing

Since Apr 26Pushed 3mo agoCompare

[ Source](https://github.com/impruthvi/agent-detector-laravel)[ Packagist](https://packagist.org/packages/impruthvi/agent-detector-laravel)[ Docs](https://github.com/impruthvi/agent-detector-laravel)[ RSS](/packages/impruthvi-agent-detector-laravel/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (6)Versions (2)Used By (0)

agent-detector-laravel
======================

[](#agent-detector-laravel)

Laravel companion for [shipfastlabs/agent-detector](https://github.com/shipfastlabs/agent-detector).

Install it, add two lines to `bootstrap/app.php`, and your Laravel app automatically:

- **Bypasses CSRF** for AI agent requests (no more 419s)
- **Logs every request** to a separate `agent.log` channel tagged with agent name + session ID
- **Adds `X-Agent-Session` header** to responses (visible in proxy/CDN logs)

```
[2026-04-23 14:32:01] agent.INFO: POST /api/users [] {"agent":"Claude Code","session":"none"}
[2026-04-23 14:32:03] agent.ERROR: Migration failed [] {"agent":"Codex","session":"thread-abc123"}

```

Grep by session ID. See exactly what your AI agent did.

---

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11, 12, or 13
- [shipfastlabs/agent-detector](https://packagist.org/packages/shipfastlabs/agent-detector) `^1.1`

Installation
------------

[](#installation)

```
composer require impruthvi/agent-detector-laravel
```

Publish the config (optional):

```
php artisan vendor:publish --provider="AgentDetector\Laravel\AgentDetectorServiceProvider"
```

Setup
-----

[](#setup)

Add the middleware to `bootstrap/app.php`:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->prepend(\AgentDetector\Laravel\DetectedAgentMiddleware::class);
})
```

That's it. CSRF bypass and the agent log channel are active automatically.

---

What you get
------------

[](#what-you-get)

### CSRF bypass

[](#csrf-bypass)

Agent requests skip CSRF verification. No more 419s when Claude Code, Codex, or Cursor hits your endpoints.

The package tries two approaches, in order:

**Approach 1 (automatic):** Decorates `VerifyCsrfToken` via the service container. Works on most Laravel 11+ installs.

**Approach 2 (manual fallback):** If Approach 1 doesn't work, you'll see a warning in your logs:

```
agent-detector: CSRF bypass unavailable via extend() (VerifyCsrfToken not container-bound).
Use AgentAwareCsrfMiddleware in bootstrap/app.php instead.

```

Fix it by replacing the middleware in `bootstrap/app.php`:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->replace(
        \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
        \AgentDetector\Laravel\Middleware\AgentAwareCsrfMiddleware::class,
    );
})
```

You can subclass `AgentAwareCsrfMiddleware` to add your own `$except` array:

```
class MyMiddleware extends AgentAwareCsrfMiddleware
{
    protected $except = ['webhooks/*'];
}
```

### Agent log channel

[](#agent-log-channel)

Every log line emitted during an agent session is tagged with the agent name and session ID.

The `agent` channel is auto-registered. Use it directly:

```
use Illuminate\Support\Facades\Log;

Log::channel('agent')->info('Migration started', ['table' => 'users']);
```

Logs write to `storage/logs/agent.log`.

### `X-Agent-Session` response header

[](#x-agent-session-response-header)

Every response to a detected agent request includes:

```
X-Agent-Session: Claude Code/no-session
X-Agent-Session: Codex/thread-abc123

```

Useful for debugging via proxy logs, CDN access logs, or browser devtools.

---

Configuration
-------------

[](#configuration)

`config/agent-detector.php` (after publishing):

```
return [
    // Skip CSRF for detected agent requests. Default: true.
    'disable_csrf' => true,

    // Auto-registered log channel name. Set to null to disable.
    'log_channel' => 'agent',

    // Middleware must be added manually — no auto-injection.
    'auto_register_middleware' => false,
];
```

---

Using AgentContext
------------------

[](#using-agentcontext)

Inject `AgentContext` anywhere in your app:

```
use AgentDetector\Laravel\AgentContext;

class MyController extends Controller
{
    public function __construct(private AgentContext $agent) {}

    public function store(Request $request)
    {
        if ($this->agent->isAgent()) {
            Log::channel('agent')->info('Agent creating resource', [
                'agent'   => $this->agent->displayName(),
                'session' => $this->agent->sessionId(),
            ]);
        }

        // ...
    }
}
```

MethodReturnsExample`isAgent()``bool``true``name()``?string``'claude'``displayName()``string``'Claude Code'``sessionId()``?string``'thread-abc123'` or `null``knownAgent()``?KnownAgent``KnownAgent::Claude`---

Session IDs
-----------

[](#session-ids)

Most agents do not expose a session ID. Only Codex (`CODEX_THREAD_ID`) and Amp (`AMP_CURRENT_THREAD_ID`) expose session env vars today. Log output shows `session:"none"` for all others — that's expected.

---

Known limitations
-----------------

[](#known-limitations)

**Octane / long-running processes:** `AgentContext` is resolved once when the application boots. Under Laravel Octane or long-running `queue:work`, detection reflects the environment at startup. Agents set env vars before the process starts, so this is rarely an issue in practice.

---

Detected agents
---------------

[](#detected-agents)

Inherits detection from `shipfastlabs/agent-detector`:

AgentDisplay nameSession IDClaude Code`Claude Code`—Cursor`Cursor`—Codex`Codex``CODEX_THREAD_ID`Amp`Amp``AMP_CURRENT_THREAD_ID`Devin`Devin`—Gemini CLI`Gemini CLI`—Augment CLI`Augment CLI`—OpenCode`OpenCode`—Replit`Replit`—GitHub Copilot`GitHub Copilot`—Antigravity`Antigravity`—Pi`Pi`—---

CI
--

[](#ci)

LaravelPHP11, 128.2, 8.3, 8.4, 8.5138.4, 8.5---

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance82

Actively maintained with recent releases

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

90d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e9ece05c34b1c140dfcc3e22d787f3d1a4d1f1c0b04248bcc734b6313eeede71?d=identicon)[impruthvi](/maintainers/impruthvi)

---

Top Contributors

[![impruthvi](https://avatars.githubusercontent.com/u/61496236?v=4)](https://github.com/impruthvi "impruthvi (5 commits)")

---

Tags

laravelaicodexAgentdetectioncursorclaude

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/impruthvi-agent-detector-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/impruthvi-agent-detector-laravel/health.svg)](https://phpackages.com/packages/impruthvi-agent-detector-laravel)
```

###  Alternatives

[laravel/agent-detector

Detect if code is running in an AI agent or automated development environment

773.8M19](/packages/laravel-agent-detector)[joshcirre/instruckt-laravel

Visual feedback for AI coding agents — Laravel MCP package

17323.5k2](/packages/joshcirre-instruckt-laravel)[markwalet/nova-modal-response

A Laravel Nova asset for Modal responses on an action.

17878.9k](/packages/markwalet-nova-modal-response)[mohamed-ashraf-elsaed/claude-agent-sdk-laravel

Anthropic Claude Agent SDK for PHP &amp; Laravel — build AI agents with tool use, sandboxing, MCP servers, subagents, hooks, and structured output via the Claude Code CLI

161.1k](/packages/mohamed-ashraf-elsaed-claude-agent-sdk-laravel)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

119.4k](/packages/tomshaw-electricgrid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
