跳至主要内容

在 Copilot SDK 中使用绑定的 CLI

将 Copilot CLI 打包到您的应用程序中,使用户无需单独安装或配置任何内容。

谁可以使用此功能?

GitHub Copilot SDK 在所有 Copilot 计划中均可使用。

注意

Copilot SDK 当前处于技术预览阶段。功能和可用性可能会发生变化。

将 Copilot CLI 随您的应用程序一起发布,使用户无需额外设置即可开始使用。

最佳适用场景: 桌面应用、独立工具、Electron 应用以及可分发的 CLI 实用程序。

它是如何工作的

与依赖全局安装的 CLI 不同,您将在应用程序包中包含 CLI 二进制文件。SDK 通过 cliPath 选项指向您捆绑的副本。主要特性包括

  • CLI 二进制文件随您的应用一起发布——无需单独安装。
  • 您可以控制应用使用的确切 CLI 版本。
  • 用户通过您的应用、环境变量或自带密钥(BYOK)进行身份验证。
  • 会话在用户的机器上按用户管理。

设置

步骤 1:在项目中包含 CLI

CLI 作为 @github/copilot npm 包的一部分进行分发。

npm install @github/copilot

步骤 2:将 SDK 指向您捆绑的 CLI

Node.js / TypeScript

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

const client = new CopilotClient({
    // Point to the CLI binary in your app bundle
    cliPath: path.join(__dirname, "vendor", "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();

Python

from copilot import CopilotClient, PermissionHandler
from pathlib import Path

client = CopilotClient({
    "cli_path": str(Path(__file__).parent / "vendor" / "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({"prompt": "Hello!"})
print(response.data.content)

await client.stop()

Go

client := copilot.NewClient(&copilot.ClientOptions{
    CLIPath: "./vendor/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!"})
fmt.Println(*response.Data.Content)

.NET

var client = new CopilotClient(new CopilotClientOptions
{
    CliPath = Path.Combine(AppContext.BaseDirectory, "vendor", "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);

身份验证策略

在捆绑 CLI 时,您需要决定用户将如何进行身份验证。下图展示了常见的模式。

Diagram showing authentication strategy options for a bundled CLI deployment.

选项 A:用户已登录的凭据(最简)

用户只需登录一次 CLI,您的捆绑应用即可使用这些凭据。无需额外代码——这是默认行为。

const client = new CopilotClient({
    cliPath: path.join(__dirname, "vendor", "copilot"),
    // Default: uses signed-in user credentials
});

选项 B:通过环境变量提供令牌

以编程方式设置令牌,或指示用户在启动您的应用之前设置令牌

const client = new CopilotClient({
    cliPath: path.join(__dirname, "vendor", "copilot"),
    env: {
        COPILOT_GITHUB_TOKEN: getUserToken(),
    },
});

getUserToken() 替换为您应用中获取用户 GitHub OAuth 令牌的逻辑。

选项 C:自带密钥(无需 GitHub 身份验证)

如果您自行管理模型提供商密钥,则用户无需 GitHub 账户

const client = new CopilotClient({
    cliPath: path.join(__dirname, "vendor", "copilot"),
});

const session = await client.createSession({
    model: "gpt-4.1",
    provider: {
        type: "openai",
        baseUrl: "https://api.openai.com/v1",
        apiKey: process.env.OPENAI_API_KEY,
    },
});

会话管理

捆绑的应用通常希望使用命名会话,以便用户能够恢复对话

const client = new CopilotClient({
    cliPath: path.join(__dirname, "vendor", "copilot"),
});

// Create a session tied to the user's project
const sessionId = `project-${projectName}`;
const session = await client.createSession({
    sessionId,
    model: "gpt-4.1",
});

// Resume the session in a later run
const resumed = await client.resumeSession(sessionId);

会话状态存储于 ~/.copilot/session-state/SESSION-ID/,其中 SESSION-ID 为您提供的会话 ID。

分发模式

桌面应用(Electron、Tauri)

将 CLI 二进制文件放入您应用的资源目录中

import { app } from "electron";
import path from "path";

const cliPath = path.join(
    app.isPackaged ? process.resourcesPath : __dirname,
    "copilot"
);

const client = new CopilotClient({ cliPath });

CLI 工具

对于可分发的 CLI 工具,请相对于您的二进制文件解析路径

import { fileURLToPath } from "url";
import path from "path";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const cliPath = path.join(__dirname, "..", "vendor", "copilot");

const client = new CopilotClient({ cliPath });

平台特定的二进制文件

在面向多个平台分发时,针对每个目标包含相应的二进制文件

my-app/
├── vendor/
│   ├── copilot-darwin-arm64    # macOS Apple Silicon
│   ├── copilot-darwin-x64      # macOS Intel
│   ├── copilot-linux-x64       # Linux x64
│   └── copilot-win-x64.exe     # Windows x64
└── src/
    └── index.ts
import os from "os";

function getCLIPath(): string {
    const platform = process.platform;   // "darwin", "linux", "win32"
    const arch = os.arch();              // "arm64", "x64"
    const ext = platform === "win32" ? ".exe" : "";
    const name = `copilot-${platform}-${arch}${ext}`;
    return path.join(__dirname, "vendor", name);
}

const client = new CopilotClient({
    cliPath: getCLIPath(),
});

限制

限制详细信息
捆绑大小CLI 二进制文件会增加您的应用分发体积。
更新您在发布周期中管理 CLI 版本的更新。
平台构建每个操作系统/架构都需要单独的二进制文件。
单用户每个捆绑的 CLI 实例仅服务于一个用户。

后续步骤

© . This site is unofficial and not affiliated with GitHub, Inc.