# 本地 CLI 设置

使用特定的 CLI 可执行文件，而不是 SDK 自带的 CLI。 这是一个高级选项-你显式提供 CLI 路径，你负责确保与 SDK 的版本兼容性。

<!-- markdownlint-disable GHD046 GHD005 -->

<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->

**在以下情况下使用：** 需要固定特定的 CLI 版本，或者使用 Go SDK（它不捆绑 CLI）。

## 工作原理

默认情况下，Node.js、Python和.NET SDK 包含自己的 CLI 依赖项（请参阅 [默认设置（随附的 CLI）](/zh/copilot/how-tos/copilot-sdk/setup/bundled-cli)）。 如果您需要覆盖此设置（例如，使用系统中已安装的 CLI），可以使用 `Connection` 选项。

![图示：显示所述过程的流程图。](/assets/images/help/copilot/copilot-sdk/setup-local-cli-diagram-0.png)

**主要特征：**

* 你明确提供 CLI 二进制文件的路径
* 你负责 CLI 版本与 SDK 的兼容性
* 身份验证使用系统钥匙串（或环境变量）中已登录用户的凭据。
* 通信通过 stdio 进行

## 配置

### 使用本地 CLI 二进制文件

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient({
    cliPath: "/usr/local/bin/copilot",
});

const session = await client.createSession({ model: "gpt-4.1" });
const response = await session.sendAndWait({ prompt: "Hello!" });
console.log(response?.data.content);

await client.stop();
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
from copilot import CopilotClient
from copilot.generated.session_events import AssistantMessageData
from copilot.session import PermissionHandler

client = CopilotClient({
    "cli_path": "/usr/local/bin/copilot",
})
await client.start()

session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model="gpt-4.1")
response = await session.send_and_wait("Hello!")
if response:
    match response.data:
        case AssistantMessageData() as data:
            print(data.content)

await client.stop()
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

> \[!NOTE]
> Go SDK 不捆绑 CLI，因此必须始终提供 `Connection`。

```golang
package main

import (
    "context"
    "fmt"
    "log"
    copilot "github.com/github/copilot-sdk/go"
)

func main() {
    ctx := context.Background()

    client := copilot.NewClient(&copilot.ClientOptions{
        Connection: copilot.StdioConnection{Path: "/usr/local/bin/copilot"},
    })
    if err := client.Start(ctx); err != nil {
        log.Fatal(err)
    }
    defer client.Stop()

    session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"})
    response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"})
    if response != nil {
        if d, ok := response.Data.(*copilot.AssistantMessageData); ok {
            fmt.Println(d.Content)
        }
    }
}
```

```golang
client := copilot.NewClient(&copilot.ClientOptions{
    Connection: copilot.StdioConnection{Path: "/usr/local/bin/copilot"},
})
if err := client.Start(ctx); err != nil {
    log.Fatal(err)
}
defer client.Stop()

session, _ := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-4.1"})
response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "Hello!"})
if response != nil {
    if d, ok := response.Data.(*copilot.AssistantMessageData); ok {
        fmt.Println(d.Content)
    }
}
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
var client = new CopilotClient(new CopilotClientOptions
{
    Connection = RuntimeConnection.ForStdio(path: "/usr/local/bin/copilot"),
});

await using var session = await client.CreateSessionAsync(
    new SessionConfig { Model = "gpt-4.1" });

var response = await session.SendAndWaitAsync(
    new MessageOptions { Prompt = "Hello!" });
Console.WriteLine(response?.Data.Content);
```

</div>

</div>

## 其他选项

```typescript
const client = new CopilotClient({
    cliPath: "/usr/local/bin/copilot",

    // Set log level for debugging
    logLevel: "debug",

    // Pass extra CLI arguments
    cliArgs: ["--log-dir=/tmp/copilot-logs"],

    // Set working directory
    cwd: "/path/to/project",
});
```

## 使用环境变量

你可以通过环境变量进行身份验证，而不是密钥链。 这对于 CI 或不需要交互式登录时非常有用。

```bash
# Set one of these (in priority order):
export COPILOT_GITHUB_TOKEN="gho_xxxx"   # Recommended
export GH_TOKEN="gho_xxxx"               # GitHub CLI compatible
export GITHUB_TOKEN="gho_xxxx"           # GitHub Actions compatible
```

SDK 会自动选取这些内容， 无需更改代码。

## 管理会话

会话默认为临时会话。 若要创建可恢复会话，请提供自己的会话 ID：

```typescript
// Create a named session
const session = await client.createSession({
    sessionId: "my-project-analysis",
    model: "gpt-4.1",
});

// Later, resume it
const resumed = await client.resumeSession("my-project-analysis");
```

会话状态存储在本地 。`~/.copilot/session-state/{sessionId}/`

## 局限性

| 限度        | 详细信息                  |
| --------- | --------------------- |
| **版本兼容性** | 必须确保 CLI 版本与 SDK 兼容   |
| **单个用户**  | 凭据与登录到 CLI 的人员相关联     |
| **仅限本地**  | CLI 在应用所在的同一台计算机上运行   |
| **无多租户**  | 无法从一个 CLI 实例为多个用户提供服务 |

## 后续步骤

* **[默认设置（随附的 CLI）](/zh/copilot/how-tos/copilot-sdk/setup/bundled-cli)**：使用 SDK 的内置 CLI（建议用于大多数用例）
* **[构建你的第一个由 Copilot 提供支持的应用](/zh/copilot/how-tos/copilot-sdk/getting-started)**：生成完整的交互式应用
* **[Authentication](/zh/copilot/how-tos/copilot-sdk/auth/authenticate)**：所有身份验证方法的详细信息