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

# 自訂 Agent

> 說明如何以 SessionConfig 的 customAgents 定義依用途區分的 sub-agent。

## 自訂 Agent

定義自訂 agent 後，即可依用途劃分角色的 sub-agent 架構。
Laravel 版可透過 `SessionConfig` 的 `customAgents` 進行設定。

關於將多個 sub-agent 並行執行的協作，請參考 [Fleet Mode](/zh-TW/packages/laravel-copilot-sdk/fleet-mode)。

## 基本用法

```php theme={null}
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionConfig;

Copilot::start(function (CopilotSession $session) {
    $response = $session->sendAndWait(prompt: '請調查認證相關的設計並提出改進方案');

    dump($response->content());
}, config: new SessionConfig(
    customAgents: [
        [
            'name' => 'researcher',
            'displayName' => 'Research Agent',
            'description' => '調查程式碼並整理重點',
            'tools' => ['grep', 'glob', 'view'],
            'prompt' => 'You are a research assistant. Analyze code and summarize findings.',
        ],
        [
            'name' => 'editor',
            'displayName' => 'Editor Agent',
            'description' => '進行最小必要的程式碼變更',
            'tools' => ['view', 'edit', 'bash'],
            'prompt' => 'You are a code editor. Make minimal, surgical changes only.',
        ],
    ],
));
```

也可以陣列形式指定。

```php theme={null}
Copilot::run(
    prompt: '請改善 README',
    config: [
        'customAgents' => [
            [
                'name' => 'docs-writer',
                'description' => '負責撰寫文件',
                'prompt' => 'Write clear technical documentation.',
            ],
        ],
    ],
);
```

## 設定項目

| 屬性            | 型別       | 必填 | 說明                     |
| ------------- | -------- | -- | ---------------------- |
| `name`        | `string` | ✅  | Agent 的識別子             |
| `displayName` | `string` |    | 顯示名稱                   |
| `description` | `string` |    | 執行期間選擇委派對象時的說明         |
| `tools`       | `?array` |    | 可用工具。`null` / 省略時可使用全部 |
| `prompt`      | `string` | ✅  | 該 agent 專屬的系統 prompt   |
| `mcpServers`  | `array`  |    | 該 agent 專屬的 MCP 伺服器設定  |
| `infer`       | `bool`   |    | 是否作為自動選擇對象（預設：`true`）  |
| `skills`      | `array`  |    | 啟動時要載入的 skill 名稱清單     |

> `description` 描述越具體，自動選擇的精準度越高。

## Session 開始時選擇特定 agent

指定 `agent` 後，可從第一個 turn 就啟用特定的自訂 agent。

```php theme={null}
use Revolution\Copilot\Types\SessionConfig;

$config = new SessionConfig(
    customAgents: [
        [
            'name' => 'researcher',
            'prompt' => 'You analyze code and answer questions.',
        ],
        [
            'name' => 'editor',
            'prompt' => 'You edit code with minimal changes.',
        ],
    ],
    agent: 'researcher',
);
```

## 停用自動選擇（`infer: false`）

執行風險較高操作的 agent，將自動選擇停用並明確使用會較為安全。

```php theme={null}
$config = new SessionConfig(
    customAgents: [
        [
            'name' => 'dangerous-cleanup',
            'description' => '刪除不必要的檔案',
            'tools' => ['bash', 'edit', 'view'],
            'prompt' => 'Remove dead code and unused files carefully.',
            'infer' => false,
        ],
    ],
);
```

## 對預設 agent 隱藏工具

使用 `defaultAgent.excludedTools` 可只針對主 agent 隱藏特定工具。
如此更容易委派給能使用該工具的自訂 agent。

```php theme={null}
$config = new SessionConfig(
    tools: [...],
    defaultAgent: [
        'excludedTools' => ['analyze-codebase'],
    ],
    customAgents: [
        [
            'name' => 'researcher',
            'tools' => ['analyze-codebase'],
            'prompt' => 'You perform deep codebase analysis.',
        ],
    ],
);
```

## 監控 sub-agent 事件

Sub-agent 執行過程中會流出 `subagent.*` 事件。
可透過 `onEvent` 或 `$session->on()` 監控。

```php theme={null}
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Enums\SessionEventType;
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionEvent;

Copilot::start(function (CopilotSession $session) {
    $session->on(function (SessionEvent $event): void {
        if ($event->is(SessionEventType::SUBAGENT_STARTED)) {
            info('Sub-agent started', $event->toArray());
        }

        if ($event->is(SessionEventType::SUBAGENT_COMPLETED)) {
            info('Sub-agent completed', $event->toArray());
        }

        if ($event->is(SessionEventType::SUBAGENT_FAILED)) {
            info('Sub-agent failed', $event->toArray());
        }
    });

    $session->sendAndWait(prompt: '請調查這個儲存庫的認證實作');
});
```

## 最佳實踐

* 將 `researcher`（以讀取為主）與 `editor`（負責變更）分開
* `tools` 保持最小必要範圍，收斂權限
* `description` 寫得越具體，自動委派精準度越高
* 捕捉 `subagent.failed` 以準備重試或降級方案

## 參考

* [SessionConfig](/zh-TW/packages/laravel-copilot-sdk/session-config)
* [SessionEvent](/zh-TW/packages/laravel-copilot-sdk/session-event)
* [Fleet Mode](/zh-TW/packages/laravel-copilot-sdk/fleet-mode)
* [MCP](/zh-TW/packages/laravel-copilot-sdk/mcp)
* [Tools](/zh-TW/packages/laravel-copilot-sdk/tools)


## Related topics

- [Laravel Agent Detector — AI Agent 偵測套件](/zh-TW/blog/agent-detector-introduction.md)
- [進階主題](/zh-TW/advanced/index.md)
- [我的套件](/zh-TW/packages/index.md)
- [BlueskyManager 與 HasShortHand](/zh-TW/packages/laravel-bluesky/bluesky-manager.md)
- [Fleet Mode](/zh-TW/packages/laravel-copilot-sdk/fleet-mode.md)
