copilot-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GitHub Copilot SDK

GitHub Copilot SDK

Multi-platform SDK for embedding GitHub Copilot's agentic runtime into applications and services. Available for Node.js/TypeScript, Python, Go, and .NET. Communicates with the Copilot CLI in server mode via JSON-RPC.
Status: Technical Preview — breaking changes possible between releases.
一款多平台SDK,用于将GitHub Copilot的智能代理运行时嵌入到应用程序和服务中。支持Node.js/TypeScript、Python、Go和.NET。通过JSON-RPC与服务器模式下的Copilot CLI通信。
状态:技术预览版 — 版本间可能存在破坏性变更。

Architecture

架构

Your Application
      |
  SDK Client   (manages CLI process lifecycle + JSON-RPC transport)
      |
  Copilot CLI  (server mode — planning, tool invocation, file edits)
The SDK spawns and manages the CLI automatically. Applications define agent behavior; the CLI handles orchestration.
Your Application
      |
  SDK Client   (manages CLI process lifecycle + JSON-RPC transport)
      |
  Copilot CLI  (server mode — planning, tool invocation, file edits)
SDK会自动启动并管理CLI。应用程序定义代理行为;CLI负责编排工作流。

Prerequisites

前置条件

  1. Install the GitHub Copilot CLI and authenticate:
    bash
    # Follow: https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli
    copilot --version   # verify
  2. A GitHub Copilot subscription (or BYOK — see
    references/authentication.md
    )
  1. 安装GitHub Copilot CLI并完成身份验证:
    bash
    # 参考:https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli
    copilot --version   # 验证安装
  2. 拥有GitHub Copilot订阅(或使用BYOK — 详见
    references/authentication.md

Installation

安装

LanguagePackageInstall
Node.js / TypeScript
@github/copilot-sdk
npm install @github/copilot-sdk
Python
github-copilot-sdk
pip install github-copilot-sdk
Go
github.com/github/copilot-sdk/go
go get github.com/github/copilot-sdk/go
.NET
GitHub.Copilot.SDK
dotnet add package GitHub.Copilot.SDK
语言包名称安装命令
Node.js / TypeScript
@github/copilot-sdk
npm install @github/copilot-sdk
Python
github-copilot-sdk
pip install github-copilot-sdk
Go
github.com/github/copilot-sdk/go
go get github.com/github/copilot-sdk/go
.NET
GitHub.Copilot.SDK
dotnet add package GitHub.Copilot.SDK

Core Workflow

核心工作流

Every SDK integration follows this pattern:
  1. Create a
    CopilotClient
  2. Call
    client.start()
    (auto-starts the CLI server)
  3. Create a session with
    client.createSession(config)
  4. Send messages; handle events
  5. Call
    client.stop()
    on shutdown
所有SDK集成都遵循以下模式:
  1. 创建
    CopilotClient
    实例
  2. 调用
    client.start()
    (自动启动CLI服务器)
  3. 使用
    client.createSession(config)
    创建一个会话
  4. 发送消息;处理事件
  5. 关闭时调用
    client.stop()

Minimal Example

最小示例

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

const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" });

const response = await session.sendAndWait({ prompt: "What is 2 + 2?" });
console.log(response?.data.content);

await client.stop();
process.exit(0);
Python:
python
import asyncio
from copilot import CopilotClient

async def main():
    client = CopilotClient()
    await client.start()
    session = await client.create_session({"model": "gpt-4.1"})
    response = await session.send_and_wait({"prompt": "What is 2 + 2?"})
    print(response.data.content)
    await client.stop()

asyncio.run(main())
TypeScript:
typescript
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" });

const response = await session.sendAndWait({ prompt: "What is 2 + 2?" });
console.log(response?.data.content);

await client.stop();
process.exit(0);
Python:
python
import asyncio
from copilot import CopilotClient

async def main():
    client = CopilotClient()
    await client.start()
    session = await client.create_session({"model": "gpt-4.1"})
    response = await session.send_and_wait({"prompt": "What is 2 + 2?"})
    print(response.data.content)
    await client.stop()

asyncio.run(main())

Sessions

会话

Sessions represent a single conversation thread.
createSession
/
create_session
accepts a
SessionConfig
:
OptionTypeDescription
model
stringModel ID — required with BYOK. E.g.
"gpt-4.1"
,
"claude-sonnet-4.5"
streaming
boolEmit
assistant.message_delta
chunks in real time
tools
Tool[]Custom tools the agent can invoke
systemMessage
objectInject or replace the system prompt
infiniteSessions
objectContext compaction config (enabled by default)
provider
objectBYOK — custom LLM provider config
hooks
objectLifecycle hook handlers
onUserInputRequest
callableEnable
ask_user
tool; handler returns user's answer
sessionId
stringDeterministic / resumable session ID
会话代表单个对话线程。
createSession
/
create_session
接受
SessionConfig
配置项:
选项类型描述
model
string模型ID — 使用BYOK时必填。例如
"gpt-4.1"
"claude-sonnet-4.5"
streaming
bool实时发送
assistant.message_delta
分片
tools
Tool[]代理可以调用的自定义工具
systemMessage
object注入或替换系统提示词
infiniteSessions
object上下文压缩配置(默认启用)
provider
objectBYOK — 自定义大语言模型提供商配置
hooks
object生命周期钩子处理器
onUserInputRequest
callable启用
ask_user
工具;处理器返回用户的回答
sessionId
string可确定/可恢复的会话ID

Sending Messages

发送消息

typescript
// Fire-and-forget (returns message ID)
await session.send({ prompt: "Generate a README" });

// Send and await idle state (returns final AssistantMessageEvent)
const result = await session.sendAndWait({ prompt: "Explain this code" });
python
undefined
typescript
// 发送后无需等待(返回消息ID)
await session.send({ prompt: "Generate a README" });

// 发送并等待空闲状态(返回最终的AssistantMessageEvent)
const result = await session.sendAndWait({ prompt: "Explain this code" });
python
undefined

Python equivalent

Python 等效代码

await session.send({"prompt": "Generate a README"}) result = await session.send_and_wait({"prompt": "Explain this code"})
undefined
await session.send({"prompt": "Generate a README"}) result = await session.send_and_wait({"prompt": "Explain this code"})
undefined

Streaming Events

流式事件

Enable
streaming: true
and subscribe to incremental chunks:
typescript
const session = await client.createSession({ model: "gpt-4.1", streaming: true });

session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});
session.on("session.idle", () => console.log("\nDone."));

await session.sendAndWait({ prompt: "Write a haiku about testing" });
Key session event types:
EventFires when
user.message
User message enqueued
assistant.message
Final full response available
assistant.message_delta
Streaming chunk (requires
streaming: true
)
assistant.reasoning_delta
Chain-of-thought chunk (model-dependent)
tool.execution_start
Agent begins a tool call
tool.execution_complete
Tool call finished
session.idle
Processing complete, session ready
session.compaction_start
Infinite session compaction started
session.compaction_complete
Compaction finished
All
session.on()
calls return an unsubscribe function.
启用
streaming: true
并订阅增量分片:
typescript
const session = await client.createSession({ model: "gpt-4.1", streaming: true });

session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});
session.on("session.idle", () => console.log("\nDone."));

await session.sendAndWait({ prompt: "Write a haiku about testing" });
主要的会话事件类型:
事件触发时机
user.message
用户消息已入队
assistant.message
完整的最终响应已生成
assistant.message_delta
流式分片到达(需启用
streaming: true
assistant.reasoning_delta
思维链分片到达(取决于模型)
tool.execution_start
代理开始调用工具
tool.execution_complete
工具调用完成
session.idle
处理完成,会话就绪
session.compaction_start
无限会话压缩开始
session.compaction_complete
压缩完成
所有
session.on()
调用都会返回一个取消订阅的函数。

Custom Tools

自定义工具

Define functions the agent can call. The SDK handles invocation, serialization, and response automatically.
TypeScript (with Zod):
typescript
import { defineTool, CopilotClient } from "@github/copilot-sdk";
import { z } from "zod";

const lookupIssue = defineTool("lookup_issue", {
    description: "Fetch issue details from the tracker",
    parameters: z.object({
        id: z.string().describe("Issue identifier"),
    }),
    handler: async ({ id }) => {
        return await fetchIssue(id);  // any JSON-serializable value
    },
});

const session = await client.createSession({
    model: "gpt-4.1",
    tools: [lookupIssue],
});
Python (with Pydantic):
python
from pydantic import BaseModel, Field
from copilot import define_tool

class LookupIssueParams(BaseModel):
    id: str = Field(description="Issue identifier")

@define_tool(description="Fetch issue details from the tracker")
async def lookup_issue(params: LookupIssueParams) -> str:
    return await fetch_issue(params.id)

session = await client.create_session({
    "model": "gpt-4.1",
    "tools": [lookup_issue],
})
Raw JSON schemas are also accepted when Zod/Pydantic is not available.
定义代理可以调用的函数。SDK会自动处理调用、序列化和响应。
TypeScript(搭配Zod):
typescript
import { defineTool, CopilotClient } from "@github/copilot-sdk";
import { z } from "zod";

const lookupIssue = defineTool("lookup_issue", {
    description: "Fetch issue details from the tracker",
    parameters: z.object({
        id: z.string().describe("Issue identifier"),
    }),
    handler: async ({ id }) => {
        return await fetchIssue(id);  // 任何可JSON序列化的值
    },
});

const session = await client.createSession({
    model: "gpt-4.1",
    tools: [lookupIssue],
});
Python(搭配Pydantic):
python
from pydantic import BaseModel, Field
from copilot import define_tool

class LookupIssueParams(BaseModel):
    id: str = Field(description="Issue identifier")

@define_tool(description="Fetch issue details from the tracker")
async def lookup_issue(params: LookupIssueParams) -> str:
    return await fetch_issue(params.id)

session = await client.create_session({
    "model": "gpt-4.1",
    "tools": [lookup_issue],
})
当无法使用Zod/Pydantic时,也支持原始JSON schema。

System Message Customization

系统提示词自定义

Inject additional context into the system prompt without replacing the default persona:
typescript
const session = await client.createSession({
    model: "gpt-4.1",
    systemMessage: {
        content: `
<workflow_rules>
- Always check for security vulnerabilities
- Suggest performance improvements when applicable
</workflow_rules>`,
    },
});
Use
mode: "replace"
to fully control the system prompt (removes all SDK-managed guardrails):
typescript
systemMessage: { mode: "replace", content: "You are a terse code reviewer." }
在不替换默认角色的前提下,向系统提示词中注入额外上下文:
typescript
const session = await client.createSession({
    model: "gpt-4.1",
    systemMessage: {
        content: `
<workflow_rules>
- Always check for security vulnerabilities
- Suggest performance improvements when applicable
</workflow_rules>`,
    },
});
使用
mode: "replace"
可以完全控制系统提示词(移除所有SDK管理的防护规则):
typescript
systemMessage: { mode: "replace", content: "You are a terse code reviewer." }

Infinite Sessions

无限会话

Enabled by default. Manages the context window automatically through background compaction and persists state to
~/.copilot/session-state/{sessionId}/
.
typescript
// Custom thresholds
const session = await client.createSession({
    model: "gpt-4.1",
    infiniteSessions: {
        enabled: true,
        backgroundCompactionThreshold: 0.80,  // compact at 80% usage
        bufferExhaustionThreshold: 0.95,       // block at 95% until done
    },
});

// Disable (fixed context window)
const session = await client.createSession({
    model: "gpt-4.1",
    infiniteSessions: { enabled: false },
});
Resume a persisted session by ID:
typescript
const session = await client.resumeSession("my-session-id");
默认启用。通过后台压缩自动管理上下文窗口,并将会话状态持久化到
~/.copilot/session-state/{sessionId}/
typescript
// 自定义阈值
const session = await client.createSession({
    model: "gpt-4.1",
    infiniteSessions: {
        enabled: true,
        backgroundCompactionThreshold: 0.80,  // 使用率达80%时触发压缩
        bufferExhaustionThreshold: 0.95,       // 使用率达95%时阻塞直到压缩完成
    },
});

// 禁用(固定上下文窗口)
const session = await client.createSession({
    model: "gpt-4.1",
    infiniteSessions: { enabled: false },
});
通过ID恢复已持久化的会话:
typescript
const session = await client.resumeSession("my-session-id");

File Attachments

文件附件

Attach files or images to messages:
typescript
await session.send({
    prompt: "Review this module",
    attachments: [{ type: "file", path: "/src/auth.ts", displayName: "auth.ts" }],
});
Supported image formats: JPG, PNG, GIF, and common image types. The agent's
view
tool also reads files directly from the filesystem.
可以在消息中附加文件或图片:
typescript
await session.send({
    prompt: "Review this module",
    attachments: [{ type: "file", path: "/src/auth.ts", displayName: "auth.ts" }],
});
支持的图片格式:JPG、PNG、GIF及其他常见图片类型。代理的
view
工具也可以直接从文件系统读取文件。

MCP Servers

MCP服务器

Connect to Model Context Protocol servers to provide pre-built tools (e.g., GitHub repositories, issues, PRs):
typescript
const session = await client.createSession({
    model: "gpt-4.1",
    mcpServers: {
        github: {
            type: "http",
            url: "https://api.githubcopilot.com/mcp/",
        },
    },
});
连接到Model Context Protocol服务器以使用预构建工具(例如GitHub仓库、Issue、PR):
typescript
const session = await client.createSession({
    model: "gpt-4.1",
    mcpServers: {
        github: {
            type: "http",
            url: "https://api.githubcopilot.com/mcp/",
        },
    },
});

External CLI Server

外部CLI服务器

Run the CLI separately and connect the SDK to it — useful for debugging, resource sharing, or custom flags:
bash
copilot --headless --port 4321
typescript
const client = new CopilotClient({ cliUrl: "localhost:4321" });
When
cliUrl
is set, the SDK does not spawn a CLI process.
单独运行CLI并将SDK连接到它 — 适用于调试、资源共享或自定义标志:
bash
copilot --headless --port 4321
typescript
const client = new CopilotClient({ cliUrl: "localhost:4321" });
当设置
cliUrl
后,SDK不会再启动CLI进程。

Error Handling

错误处理

Wrap client and session operations in try/catch. The
stop()
method returns a list of errors from cleanup:
typescript
try {
    const session = await client.createSession({ model: "gpt-4.1" });
    await session.sendAndWait({ prompt: "Fix the bug" });
} catch (error) {
    console.error("SDK error:", error.message);
} finally {
    const errors = await client.stop();
    if (errors.length) console.error("Cleanup errors:", errors);
}
Use
client.forceStop()
if graceful shutdown hangs.
将客户端和会话操作包裹在try/catch块中。
stop()
方法会返回清理过程中出现的错误列表:
typescript
try {
    const session = await client.createSession({ model: "gpt-4.1" });
    await session.sendAndWait({ prompt: "Fix the bug" });
} catch (error) {
    console.error("SDK error:", error.message);
} finally {
    const errors = await client.stop();
    if (errors.length) console.error("Cleanup errors:", errors);
}
如果优雅关闭挂起,可使用
client.forceStop()

Session Lifecycle Methods

会话生命周期方法

typescript
// List sessions (optionally filter by working directory)
const sessions = await client.listSessions();

// Delete a session
await client.deleteSession("session-id");

// Get all messages from a session
const messages = await session.getMessages();

// Abort current processing
await session.abort();

// Destroy session and free resources
await session.destroy();
typescript
// 列出会话(可按工作目录过滤)
const sessions = await client.listSessions();

// 删除会话
await client.deleteSession("session-id");

// 获取会话中的所有消息
const messages = await session.getMessages();

// 中止当前处理
await session.abort();

// 销毁会话并释放资源
await session.destroy();

Multiple Sessions

多会话

Each session is independent. Multiple models can run simultaneously:
typescript
const session1 = await client.createSession({ model: "gpt-4.1" });
const session2 = await client.createSession({ model: "claude-sonnet-4.5" });

await Promise.all([
    session1.sendAndWait({ prompt: "Draft a PR description" }),
    session2.sendAndWait({ prompt: "Review the security implications" }),
]);
每个会话都是独立的。可以同时运行多个模型:
typescript
const session1 = await client.createSession({ model: "gpt-4.1" });
const session2 = await client.createSession({ model: "claude-sonnet-4.5" });

await Promise.all([
    session1.sendAndWait({ prompt: "Draft a PR description" }),
    session2.sendAndWait({ prompt: "Review the security implications" }),
]);

Quick Reference

快速参考

CopilotClient options:  cliPath, cliUrl, port, useStdio, logLevel,
                        autoStart, autoRestart, githubToken, useLoggedInUser

SessionConfig:          model, streaming, tools, systemMessage,
                        infiniteSessions, provider, hooks,
                        onUserInputRequest, sessionId

session.send()          → Promise<string>  (message ID)
session.sendAndWait()   → Promise<AssistantMessageEvent | undefined>
session.on()            → () => void  (unsubscribe fn)
session.abort()         → Promise<void>
session.destroy()       → Promise<void>
session.getMessages()   → Promise<SessionEvent[]>
CopilotClient options:  cliPath, cliUrl, port, useStdio, logLevel,
                        autoStart, autoRestart, githubToken, useLoggedInUser

SessionConfig:          model, streaming, tools, systemMessage,
                        infiniteSessions, provider, hooks,
                        onUserInputRequest, sessionId

session.send()          → Promise<string>  (message ID)
session.sendAndWait()   → Promise<AssistantMessageEvent | undefined>
session.on()            → () => void  (unsubscribe fn)
session.abort()         → Promise<void>
session.destroy()       → Promise<void>
session.getMessages()   → Promise<SessionEvent[]>

Additional Resources

其他资源

  • references/authentication.md
    — GitHub OAuth, environment variables, BYOK (Azure, OpenAI, Anthropic), and auth priority order
  • references/tools-and-hooks.md
    — Tool handler return types, raw JSON schema, session hooks (
    onPreToolUse
    ,
    onPostToolUse
    ,
    onUserPromptSubmitted
    ,
    onSessionStart
    ,
    onSessionEnd
    ,
    onErrorOccurred
    ), and user input requests
  • references/authentication.md
    — GitHub OAuth、环境变量、BYOK(Azure、OpenAI、Anthropic)以及身份验证优先级顺序
  • references/tools-and-hooks.md
    — 工具处理器返回类型、原始JSON schema、会话钩子(
    onPreToolUse
    onPostToolUse
    onUserPromptSubmitted
    onSessionStart
    onSessionEnd
    onErrorOccurred
    )以及用户输入请求