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

# 開始使用 - GitHub Copilot SDK for Laravel

> 建立第一個使用 Copilot 的 Laravel 指令，並學習 Laravel Copilot SDK 的基本工作流程。

## 建立第一個支援 Copilot 的 Laravel 應用程式

本指南將透過 Laravel Copilot SDK 建立一個命令列助理。
從送出單一 prompt 開始，接著進入 session、事件、工具。

## 前置條件

開始前請確認以下事項。

* 已安裝 GitHub Copilot CLI，並已完成認證
* PHP `8.4+`
* Laravel `13.x`

確認 CLI 是否可用。

```bash theme={null}
copilot --version
```

## 安裝 SDK

以 Composer 安裝套件。

```bash theme={null}
composer require revolution/laravel-copilot-sdk
```

如有需要可公開設定。

```bash theme={null}
php artisan vendor:publish --tag=copilot-config
```

需要時可於 `.env` 設定 CLI 路徑。

```dotenv theme={null}
COPILOT_CLI_PATH=copilot
```

## 送出第一個訊息

建立指令並呼叫 `Copilot::run()`。

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

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Revolution\Copilot\Facades\Copilot;

class CopilotDemo extends Command
{
    protected $signature = 'copilot:demo';
    protected $description = 'Demo Copilot SDK';

    public function handle()
    {
        $response = Copilot::run(prompt: 'What is 2 + 2?');

        $this->info($response->content());
    }
}
```

執行指令。

```bash theme={null}
php artisan copilot:demo
```

## 在 session 中保持脈絡

若要於單一對話中使用多個 prompt，可使用 `Copilot::start()`。

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

Copilot::start(function (CopilotSession $session) {
    $response = $session->sendAndWait(prompt: 'What is 2 + 2?');
    $this->info('Answer: '.$response->content());

    $response = $session->sendAndWait(prompt: 'Now multiply that by 3');
    $this->info('Answer: '.$response->content());
});
```

## 處理 session 事件

透過 `on()` 註冊事件 handler，可確認助理的訊息或失敗狀態。

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

Copilot::start(function (CopilotSession $session) {
    $session->on(function (SessionEvent $event): void {
        if ($event->isAssistantMessage()) {
            $this->info($event->content());
        } elseif ($event->failed()) {
            $this->error($event->errorMessage() ?? 'Unknown error');
        }
    });

    $session->sendAndWait(prompt: 'Tell me a short Laravel joke');
});
```

## 加入自訂工具

以 JSON schema 與 handler 定義工具。

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

$parameters = JsonSchema::object([
    'topic' => JsonSchema::string()
        ->description('Topic to look up')
        ->required(),
])->toArray();

$config = new SessionConfig(
    tools: [
        Tool::define(
            name: 'lookup_fact',
            description: 'Returns a fact for a topic.',
            parameters: $parameters,
            handler: function (array $params): array {
                $topic = $params['topic'] ?? '';

                return [
                    'textResultForLlm' => "Fact for {$topic}",
                    'resultType' => 'success',
                    'sessionLog' => "lookup_fact: {$topic}",
                    'toolTelemetry' => [],
                ];
            },
        ),
    ],
);

Copilot::start(function (CopilotSession $session) {
    $response = $session->sendAndWait(
        prompt: 'Use lookup_fact to tell me something about Laravel.'
    );

    $this->info($response->content());
}, config: $config);
```

## 建立互動式助理

結合 session、事件、工具，即可建立互動式的 Artisan 指令。

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

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\JsonSchema\JsonSchema;
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionConfig;
use Revolution\Copilot\Types\SessionEvent;
use Revolution\Copilot\Types\Tool;
use Revolution\Copilot\Types\ToolResultObject;

use function Laravel\Prompts\error;
use function Laravel\Prompts\info;
use function Laravel\Prompts\note;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\text;

class CopilotAssistant extends Command
{
    protected $signature = 'copilot:assistant';
    protected $description = 'Interactive Copilot assistant';

    public function handle()
    {
        $facts = [
            'PHP' => 'A popular general-purpose scripting language for web development.',
            'Laravel' => 'A web application framework with expressive, elegant syntax.',
            'Composer' => 'Dependency manager for PHP.',
        ];

        $parameters = JsonSchema::object([
            'topic' => JsonSchema::string()
                ->description('Topic to look up')
                ->required(),
        ])->toArray();

        $config = new SessionConfig(
            tools: [
                Tool::define(
                    name: 'lookup_fact',
                    description: 'Returns a fun fact about a given topic.',
                    parameters: $parameters,
                    handler: function (array $params) use ($facts) {
                        $topic = $params['topic'] ?? '';
                        $fact = $facts[$topic] ?? "No fact available for {$topic}.";

                        return new ToolResultObject(
                            textResultForLlm: $fact,
                            resultType: 'success',
                            sessionLog: "lookup_fact: {$topic}",
                            toolTelemetry: [],
                        );
                    },
                ),
            ],
        );

        Copilot::start(function (CopilotSession $session) {
            info('Copilot assistant');
            info("Session: {$session->id()}");
            info("Try: Use lookup_fact to tell me about Laravel");

            $session->on(function (SessionEvent $event): void {
                if ($event->isAssistantMessage()) {
                    note($event->content());
                } elseif ($event->failed()) {
                    error($event->errorMessage() ?? 'Unknown error');
                }
            });

            while (true) {
                $prompt = text(
                    label: 'You',
                    placeholder: 'Ask me anything...',
                    required: true,
                    hint: 'Ctrl+C to exit',
                );

                spin(
                    callback: fn () => $session->sendAndWait($prompt),
                    message: 'Thinking...',
                );

                echo "\n";
            }
        }, config: $config);
    }
}
```

執行指令。

```bash theme={null}
php artisan copilot:assistant
```

## 工具的運作原理

定義工具時需指定以下 3 點。

1. 工具的功能。
2. 接受哪些參數。
3. 執行哪段 handler 程式。

Copilot 會依使用者輸入判斷是否呼叫工具，並由 SDK 執行 handler 回傳結果。

## 接下來可嘗試的功能

### 連接 MCP 伺服器

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

$config = new SessionConfig(
    mcpServers: [
        'github' => [
            'type' => 'http',
            'url' => 'https://api.githubcopilot.com/mcp/',
        ],
    ],
);
```

### 建立自訂 agent

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

$config = new SessionConfig(
    customAgents: [
        [
            'name' => 'pr-reviewer',
            'displayName' => 'PR Reviewer',
            'description' => 'Reviews pull requests for best practices',
            'prompt' => 'You are an expert code reviewer. Focus on security, performance, and maintainability.',
        ],
    ],
);
```

### 自訂系統訊息

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

$config = new SessionConfig(
    systemMessage: new SystemMessageConfig(
        content: 'You are a helpful assistant for our engineering team. Always be concise.',
    ),
);
```

## 連接至外部 CLI 伺服器

以伺服器模式啟動 Copilot CLI。

```bash theme={null}
copilot --headless --port 4321
```

接著於 `.env` 設定連線的 URL。

```dotenv theme={null}
COPILOT_URL=tcp://127.0.0.1:4321
```

設定 `COPILOT_URL` 後，SDK 不會啟動新的 CLI 程序，而會連接至既有伺服器。

## 遙測與可觀測性

於 `config/copilot.php` 設定遙測。

```php theme={null}
'telemetry' => [
    'otlpEndpoint' => 'http://localhost:4318',
],
```

或直接設定。

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

Copilot::useStdio([
    'telemetry' => new TelemetryConfig(
        otlpEndpoint: 'http://localhost:4318',
    ),
]);
```

## 進一步學習

* [認證](/zh-TW/packages/laravel-copilot-sdk/auth)
* [MCP](/zh-TW/packages/laravel-copilot-sdk/mcp)
* [自訂 provider](/zh-TW/packages/laravel-copilot-sdk/custom-providers)
* [遙測](/zh-TW/packages/laravel-copilot-sdk/telemetry)
* [SessionConfig](/zh-TW/packages/laravel-copilot-sdk/session-config)
* [SessionEvent](/zh-TW/packages/laravel-copilot-sdk/session-event)
* [Laravel Copilot SDK 概觀](/zh-TW/packages/laravel-copilot-sdk)
* [官方 SDK 儲存庫](https://github.com/github/copilot-sdk)

## 下一步

<Columns cols={2}>
  <Card title="認證" href="/zh-TW/packages/laravel-copilot-sdk/auth">
    選擇適合本機環境與 CI 的認證方式。
  </Card>

  <Card title="SessionConfig" href="/zh-TW/packages/laravel-copilot-sdk/session-config">
    設定模型、hook、MCP 伺服器與執行時行為。
  </Card>

  <Card title="SessionEvent" href="/zh-TW/packages/laravel-copilot-sdk/session-event">
    了解 Laravel 專屬的事件輔助工具與生命週期處理。
  </Card>

  <Card title="權限請求" href="/zh-TW/packages/laravel-copilot-sdk/permission-request">
    確認以明確授權執行工具的權限流程。
  </Card>

  <Card title="工具" href="/zh-TW/packages/laravel-copilot-sdk/tools">
    從 Copilot 呼叫應用程式程式碼。
  </Card>

  <Card title="MCP" href="/zh-TW/packages/laravel-copilot-sdk/mcp">
    連接 MCP 伺服器的既有工具。
  </Card>
</Columns>

至此已完整走過 Laravel Copilot SDK 從單次 prompt 到工具整合 session 的核心流程。

<Info>
  參考：[Laravel Copilot SDK README](https://github.com/invokable/laravel-copilot-sdk/blob/main/README.md)、[Laravel Copilot SDK Getting Started](https://github.com/invokable/laravel-copilot-sdk/blob/main/docs/getting-started.md)、[GitHub Copilot SDK](https://github.com/github/copilot-sdk)
</Info>


## Related topics

- [GitHub Copilot SDK for Laravel](/zh-TW/packages/laravel-copilot-sdk/index.md)
- [GitHub Actions - GitHub Copilot SDK for Laravel](/zh-TW/packages/laravel-copilot-sdk/github-actions.md)
- [認證 - GitHub Copilot SDK for Laravel](/zh-TW/packages/laravel-copilot-sdk/auth.md)
- [測試 - GitHub Copilot SDK for Laravel](/zh-TW/packages/laravel-copilot-sdk/fake.md)
- [Laravel Cloud - GitHub Copilot SDK for Laravel](/zh-TW/packages/laravel-copilot-sdk/laravel-cloud.md)
