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

# Telemetry

> Laravel Copilot SDK에서 OpenTelemetry를 활성화하고, 앱과 Copilot CLI의 Trace Context를 연동하는 방법을 설명합니다.

## OpenTelemetry

Copilot CLI에는 OpenTelemetry에 의한 트레이스 기능이 내장되어 있습니다. SDK 측에서 설정하기만 하면 CLI 프로세스의 트레이스 데이터를 수집할 수 있습니다.

## 기본 사용법

### CLI 프로세스의 트레이스 활성화

`config/copilot.php`에 telemetry 설정을 추가하거나 직접 옵션으로 지정합니다.

```php theme={null}
// config/copilot.php
'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',
    )
]);

$response = Copilot::run(prompt: 'Hello');
```

클라이언트를 직접 사용하는 경우:

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

$client = new Client([
    'telemetry' => new TelemetryConfig(
        otlpEndpoint: 'http://localhost:4318',
    ),
]);
```

### TelemetryConfig 옵션

| 옵션               | 설명                        |
| ---------------- | ------------------------- |
| `otlpEndpoint`   | OTLP HTTP 엔드포인트 URL       |
| `filePath`       | JSON-lines 트레이스 출력 파일 경로  |
| `exporterType`   | `"otlp-http"` 또는 `"file"` |
| `sourceName`     | 인스트루먼테이션 스코프 이름           |
| `captureContent` | 메시지 내용(프롬프트, 응답)을 캡처할지    |

## W3C Trace Context 프로파게이션

<Info>
  대부분의 사용자에게는 이 기능이 필요 없습니다. 위의 `TelemetryConfig`만으로 CLI의 트레이스를 수집할 수 있습니다. 아래는 애플리케이션 측에서 독자적인 OpenTelemetry 스팬을 작성하고, CLI 스팬과 같은 분산 트레이스에 표시하고 싶은 경우의 고급 기능입니다.
</Info>

SDK는 `session.create`, `session.resume`, `session.send`의 JSON-RPC 요청에 W3C Trace Context(`traceparent`/`tracestate`)를 자동으로 주입합니다.

### 자동 프로파게이션(권장)

`open-telemetry/api` 패키지를 설치하는 것만으로 트레이스 컨텍스트가 자동으로 전파됩니다.

```shell theme={null}
composer require open-telemetry/api open-telemetry/sdk
```

설치 후에는 특별한 설정 없이 애플리케이션의 스팬과 CLI의 스팬이 동일한 분산 트레이스에 링크됩니다.

### 커스텀 프로바이더

독자적인 트레이스 컨텍스트 취득 로직을 사용하려면:

```php theme={null}
use Revolution\Copilot\Support\TraceContext;

TraceContext::useProvider(function (): array {
    return [
        'traceparent' => '00-traceid-spanid-01',
        'tracestate' => 'vendor=value',
    ];
});
```

### SDK → CLI(아웃바운드)

다음 RPC 호출에 자동으로 `traceparent`/`tracestate`가 주입됩니다.

* `session.create` — 세션 작성 시
* `session.resume` — 세션 재개 시
* `session.send` — 메시지 송신 시

### CLI → SDK(인바운드)

CLI가 도구를 호출할 때 도구 핸들러의 `$invocation` 배열에 트레이스 컨텍스트가 포함됩니다.

```php theme={null}
$session->registerTools([
    [
        'name' => 'my-tool',
        'description' => 'My custom tool',
        'handler' => function (array $args, array $invocation) {
            // CLI 스팬으로부터의 트레이스 컨텍스트
            $traceparent = $invocation['traceparent'] ?? null;
            $tracestate = $invocation['tracestate'] ?? null;

            // open-telemetry/api가 설치되어 있으면
            // 컨텍스트는 자동으로 복원되고,
            // 여기서 작성하는 스팬은 CLI 스팬의 자식이 됩니다

            return 'result';
        },
    ],
]);
```

`open-telemetry/api`가 설치되어 있는 경우, 도구 핸들러 실행 중의 OpenTelemetry 컨텍스트는 CLI 스팬에 자동으로 링크됩니다. 명시적으로 `traceparent`를 사용할 필요는 없습니다.

## 의존 관계

| 패키지                  | 용도                               |
| -------------------- | -------------------------------- |
| `open-telemetry/api` | 자동 Trace Context 전파(suggest, 옵션) |
| `open-telemetry/sdk` | 트레이스 데이터의 익스포트                   |

`open-telemetry/api`는 `composer.json`의 `suggest`에 포함되어 있습니다. 설치되어 있지 않아도 SDK 자체는 정상 동작합니다.

<Info>
  최신 정보는 [GitHub 저장소](https://github.com/invokable/laravel-copilot-sdk)를 참고하세요.
</Info>


## Related topics

- [스트리밍 이벤트](/ko/packages/laravel-copilot-sdk/streaming-events.md)
