> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Agent Detector — AI Agent 偵測套件

> laravel/agent-detector 的使用方式。解說偵測 Claude、Copilot、Cursor 等主要 AI Agent 執行環境的 Laravel 官方套件。

## 前言

[laravel/agent-detector](https://github.com/laravel/agent-detector) 是一個輕量工具，用於偵測 PHP 程式碼是否在 AI Agent 或自動化開發環境中執行。2026 年 4 月作為 Laravel 官方套件公開。

在 AI Agent 深入開發現場的今日，掌握程式碼本身在哪個環境運作變得重要。實際開發中會出現「依 AI Agent 請求或人類請求改變日誌詳細度與速率限制」、「回傳 Agent 專用回應」等情境。

```mermaid theme={null}
graph TD
    A["AgentDetector::detect()"] --> B{"有 AI_AGENT<br>環境變數?"}
    B -->|Yes| C["回傳自訂或已知 Agent"]
    B -->|No| D{"有已知的<br>環境變數?"}
    D -->|Yes| E["回傳對應的<br>KnownAgent"]
    D -->|No| F{"是否存在<br>/opt/.devin 檔?"}
    F -->|Yes| G["回傳 KnownAgent::Devin"]
    F -->|No| H["isAgent: false<br>（無 Agent）"]
```

## 安裝

```bash theme={null}
composer require laravel/agent-detector
```

需要 PHP 8.2 以上。

## 基本使用

呼叫 `AgentDetector::detect()` 會回傳 `AgentResult` 物件。

```php theme={null}
use Laravel\AgentDetector\AgentDetector;
use Laravel\AgentDetector\KnownAgent;

$result = AgentDetector::detect();

if ($result->isAgent) {
    echo "Running inside: {$result->name}";
}

// 確認是否為特定 Agent
if ($result->knownAgent() === KnownAgent::Claude) {
    echo "Hello from Claude!";
}
```

也可以使用獨立函式的寫法。

```php theme={null}
use function Laravel\AgentDetector\detectAgent;

$result = detectAgent();
```

### AgentResult 的屬性

| 屬性 / 方法                 | 型別            | 說明                                       |
| ----------------------- | ------------- | ---------------------------------------- |
| `$result->isAgent`      | `bool`        | 若在 AI Agent 中執行則為 `true`                 |
| `$result->name`         | `?string`     | Agent 名稱（例：`"claude"`）。非 Agent 時為 `null` |
| `$result->knownAgent()` | `?KnownAgent` | 回傳 `KnownAgent` enum。未知 Agent 為 `null`   |

## 支援的 Agent 一覽

| Agent          | 偵測方式（環境變數 / 檔案）                                                                                                                  |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Custom         | `AI_AGENT` 環境變數（任意值）                                                                                                             |
| GitHub Copilot | `AI_AGENT=github-copilot`、`AI_AGENT=github-copilot-cli`、`COPILOT_MODEL`、`COPILOT_ALLOW_ALL`、`COPILOT_GITHUB_TOKEN`、`COPILOT_CLI` |
| Cursor         | `CURSOR_AGENT`                                                                                                                   |
| Claude         | `CLAUDECODE` 或 `CLAUDE_CODE`                                                                                                     |
| Cowork         | `CLAUDE_CODE_IS_COWORK`（與 `CLAUDECODE` 或 `CLAUDE_CODE` 同時設定）                                                                     |
| Gemini         | `GEMINI_CLI`                                                                                                                     |
| Codex          | `CODEX_SANDBOX`、`CODEX_CI`、`CODEX_THREAD_ID`                                                                                     |
| Augment CLI    | `AUGMENT_AGENT`                                                                                                                  |
| AMP            | `AMP_CURRENT_THREAD_ID`                                                                                                          |
| Opencode       | `OPENCODE_CLIENT` 或 `OPENCODE`                                                                                                   |
| Replit         | `REPL_ID`                                                                                                                        |
| Devin          | 存在 `/opt/.devin` 檔案                                                                                                              |
| Antigravity    | `ANTIGRAVITY_AGENT`                                                                                                              |
| Pi             | `PI_CODING_AGENT`                                                                                                                |
| Kiro CLI       | `KIRO_AGENT_PATH`                                                                                                                |
| v0             | `AI_AGENT=v0`                                                                                                                    |

偵測優先序為 `AI_AGENT` 環境變數 → 已知環境變數 → 檔案系統。

## 自訂 Agent 設定

只要將 `AI_AGENT` 環境變數設為任意值，就能作為自訂 Agent 被偵測到。

```bash theme={null}
AI_AGENT=my-custom-agent php your-script.php
```

```php theme={null}
$result = AgentDetector::detect();

// $result->isAgent === true
// $result->name    === 'my-custom-agent'
// $result->knownAgent() === null（未知 Agent）
```

## 實用案例

### 在 Middleware 偵測 AI Agent

在 Laravel middleware 中判斷執行環境，將對 Agent 的處理進行分流。

```php theme={null}
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Laravel\AgentDetector\AgentDetector;

class DetectAiAgent
{
    public function handle(Request $request, Closure $next): mixed
    {
        $agent = AgentDetector::detect();

        if ($agent->isAgent) {
            // 將 Agent 名稱設為 request 屬性
            $request->attributes->set('ai_agent', $agent->name);
        }

        return $next($request);
    }
}
```

### 在 AI Agent 環境輸出更詳細的日誌

```php theme={null}
use Laravel\AgentDetector\AgentDetector;
use Illuminate\Support\Facades\Log;

$agent = AgentDetector::detect();

if ($agent->isAgent) {
    Log::withContext(['ai_agent' => $agent->name])
        ->debug('Agent request received', $request->all());
} else {
    Log::info('User request received');
}
```

### 對來自 AI Agent 的請求套用速率限制

依 Agent 偵測結果改變 `ThrottleRequests` middleware 的 key，即可為 Agent 與人類設定不同的速率限制。

```php theme={null}
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Laravel\AgentDetector\AgentDetector;

class ThrottleByAiAgent
{
    public function handle(Request $request, Closure $next): mixed
    {
        $agent = AgentDetector::detect();

        // AI Agent 每分鐘 10 次請求，人類 60 次
        $maxAttempts = $agent->isAgent ? 10 : 60;

        return app(ThrottleRequests::class)->handle(
            $request,
            $next,
            $maxAttempts,
        );
    }
}
```

### 在 Console 指令切換行為

在 Artisan 指令由 Agent 執行時輸出詳細進度的例子。

```php theme={null}
use Laravel\AgentDetector\AgentDetector;

public function handle(): void
{
    $agent = AgentDetector::detect();

    if ($agent->isAgent) {
        $this->info("Running in {$agent->name} environment — verbose mode enabled.");
    }

    // 處理...
}
```

## 總結

`laravel/agent-detector` 是一個把簡易環境變數檢查與檔案系統檢查整合起來的套件。不需要複雜設定，只要呼叫 `AgentDetector::detect()` 就能使用。

在 AI Agent 逐漸成為開發流程一環的今日，掌握「程式碼是被誰（或什麼）驅動」正變得越來越重要。無論是日誌、速率限制、回應客製化等各種場合，這個套件都能派上用場。

<Card title="laravel/agent-detector 儲存庫" icon="github" href="https://github.com/laravel/agent-detector">
  原始碼與最新的支援 Agent 清單請見此處。
</Card>


## Related topics

- [部落格](/zh-TW/blog/index.md)
- [Laravel Doctor — 應用診斷工具](/zh-TW/blog/laravel-doctor-introduction.md)
- [Laravel PAO — 針對 AI Agent 的輸出最佳化工具](/zh-TW/blog/pao-introduction.md)
- [cpx 2.0 — Composer Package Executor 全面重寫](/zh-TW/blog/cpx-introduction.md)
- [Laravel 與 AI 開發](/zh-TW/ai.md)
