copilot-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGitHub 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
前置条件
- 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 - A GitHub Copilot subscription (or BYOK — see )
references/authentication.md
- 安装GitHub Copilot CLI并完成身份验证:
bash
# 参考:https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli copilot --version # 验证安装 - 拥有GitHub Copilot订阅(或使用BYOK — 详见)
references/authentication.md
Installation
安装
| Language | Package | Install |
|---|---|---|
| Node.js / TypeScript | | |
| Python | | |
| Go | | |
| .NET | | |
| 语言 | 包名称 | 安装命令 |
|---|---|---|
| Node.js / TypeScript | | |
| Python | | |
| Go | | |
| .NET | | |
Core Workflow
核心工作流
Every SDK integration follows this pattern:
- Create a
CopilotClient - Call (auto-starts the CLI server)
client.start() - Create a session with
client.createSession(config) - Send messages; handle events
- Call on shutdown
client.stop()
所有SDK集成都遵循以下模式:
- 创建实例
CopilotClient - 调用(自动启动CLI服务器)
client.start() - 使用创建一个会话
client.createSession(config) - 发送消息;处理事件
- 关闭时调用
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. / accepts a :
createSessioncreate_sessionSessionConfig| Option | Type | Description |
|---|---|---|
| string | Model ID — required with BYOK. E.g. |
| bool | Emit |
| Tool[] | Custom tools the agent can invoke |
| object | Inject or replace the system prompt |
| object | Context compaction config (enabled by default) |
| object | BYOK — custom LLM provider config |
| object | Lifecycle hook handlers |
| callable | Enable |
| string | Deterministic / resumable session ID |
会话代表单个对话线程。 / 接受配置项:
createSessioncreate_sessionSessionConfig| 选项 | 类型 | 描述 |
|---|---|---|
| string | 模型ID — 使用BYOK时必填。例如 |
| bool | 实时发送 |
| Tool[] | 代理可以调用的自定义工具 |
| object | 注入或替换系统提示词 |
| object | 上下文压缩配置(默认启用) |
| object | BYOK — 自定义大语言模型提供商配置 |
| object | 生命周期钩子处理器 |
| callable | 启用 |
| 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
undefinedtypescript
// 发送后无需等待(返回消息ID)
await session.send({ prompt: "Generate a README" });
// 发送并等待空闲状态(返回最终的AssistantMessageEvent)
const result = await session.sendAndWait({ prompt: "Explain this code" });python
undefinedPython equivalent
Python 等效代码
await session.send({"prompt": "Generate a README"})
result = await session.send_and_wait({"prompt": "Explain this code"})
undefinedawait session.send({"prompt": "Generate a README"})
result = await session.send_and_wait({"prompt": "Explain this code"})
undefinedStreaming Events
流式事件
Enable and subscribe to incremental chunks:
streaming: truetypescript
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:
| Event | Fires when |
|---|---|
| User message enqueued |
| Final full response available |
| Streaming chunk (requires |
| Chain-of-thought chunk (model-dependent) |
| Agent begins a tool call |
| Tool call finished |
| Processing complete, session ready |
| Infinite session compaction started |
| Compaction finished |
All calls return an unsubscribe function.
session.on()启用并订阅增量分片:
streaming: truetypescript
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" });主要的会话事件类型:
| 事件 | 触发时机 |
|---|---|
| 用户消息已入队 |
| 完整的最终响应已生成 |
| 流式分片到达(需启用 |
| 思维链分片到达(取决于模型) |
| 代理开始调用工具 |
| 工具调用完成 |
| 处理完成,会话就绪 |
| 无限会话压缩开始 |
| 压缩完成 |
所有调用都会返回一个取消订阅的函数。
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 to fully control the system prompt (removes all SDK-managed guardrails):
mode: "replace"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>`,
},
});使用可以完全控制系统提示词(移除所有SDK管理的防护规则):
mode: "replace"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 tool also reads files directly from the filesystem.
view可以在消息中附加文件或图片:
typescript
await session.send({
prompt: "Review this module",
attachments: [{ type: "file", path: "/src/auth.ts", displayName: "auth.ts" }],
});支持的图片格式:JPG、PNG、GIF及其他常见图片类型。代理的工具也可以直接从文件系统读取文件。
viewMCP 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 4321typescript
const client = new CopilotClient({ cliUrl: "localhost:4321" });When is set, the SDK does not spawn a CLI process.
cliUrl单独运行CLI并将SDK连接到它 — 适用于调试、资源共享或自定义标志:
bash
copilot --headless --port 4321typescript
const client = new CopilotClient({ cliUrl: "localhost:4321" });当设置后,SDK不会再启动CLI进程。
cliUrlError Handling
错误处理
Wrap client and session operations in try/catch. The method returns a list of errors from cleanup:
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);
}Use if graceful shutdown hangs.
client.forceStop()将客户端和会话操作包裹在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
其他资源
- — GitHub OAuth, environment variables, BYOK (Azure, OpenAI, Anthropic), and auth priority order
references/authentication.md - — Tool handler return types, raw JSON schema, session hooks (
references/tools-and-hooks.md,onPreToolUse,onPostToolUse,onUserPromptSubmitted,onSessionStart,onSessionEnd), and user input requestsonErrorOccurred
- — GitHub OAuth、环境变量、BYOK(Azure、OpenAI、Anthropic)以及身份验证优先级顺序
references/authentication.md - — 工具处理器返回类型、原始JSON schema、会话钩子(
references/tools-and-hooks.md、onPreToolUse、onPostToolUse、onUserPromptSubmitted、onSessionStart、onSessionEnd)以及用户输入请求onErrorOccurred