> ## 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 的 tracing 功能。只需在 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');
```

直接使用 client 时：

```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`     | instrumentation scope 名称  |
| `captureContent` | 是否捕获消息内容（prompt、response） |

## W3C Trace Context 传播

<Info>
  对大多数用户来说不需要该功能。仅通过上面的 `TelemetryConfig` 即可收集 CLI 的追踪。以下是当你在应用侧创建自己的 OpenTelemetry span，并希望与 CLI 的 span 在同一分布式追踪中显示时的高级功能。
</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
```

安装之后无需特殊设置，应用的 span 与 CLI 的 span 就会被关联到同一个分布式追踪。

### 自定义提供程序

如果想使用自己的追踪上下文获取逻辑：

```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 span 的追踪上下文
            $traceparent = $invocation['traceparent'] ?? null;
            $tracestate = $invocation['tracestate'] ?? null;

            // 如果安装了 open-telemetry/api
            // 上下文会自动恢复，
            // 这里创建的 span 会成为 CLI span 的子级

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

当安装了 `open-telemetry/api` 时，工具处理器执行期间的 OpenTelemetry 上下文会自动关联到 CLI 的 span。无需显式使用 `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

- [流式事件](/zh/packages/laravel-copilot-sdk/streaming-events.md)
