注意
Copilot SDK 当前处于技术预览阶段。功能和可用性可能会发生变化。
在实现应用程序时,请考虑 CLI 会话的不同隔离模式,以及您希望如何管理并发会话和资源。
适用场景:平台开发者、SaaS 构建者,以及任何服务超过少数并发用户的部署。
会话隔离模式
在选择模式之前,请考虑三个维度
- 隔离性:谁能看到哪些会话?
- 并发性:可以同时运行多少会话?
- 持久性:会话的存活时间多长?

模式 1:每个用户独立的 CLI
每个用户拥有自己的 CLI 服务器实例。这是最强的隔离——用户的会话、内存和进程完全分离。

何时使用
- 数据隔离至关重要的多租户 SaaS。
- 使用不同认证凭证的用户。
- 诸如 SOC 2 或 HIPAA 等合规性要求。
// CLI pool manager—one CLI per user
class CLIPool {
private instances = new Map<string, { client: CopilotClient; port: number }>();
private nextPort = 5000;
async getClientForUser(userId: string, token?: string): Promise<CopilotClient> {
if (this.instances.has(userId)) {
return this.instances.get(userId)!.client;
}
const port = this.nextPort++;
// Spawn a dedicated CLI for this user
await spawnCLI(port, token);
const client = new CopilotClient({
cliUrl: `localhost:${port}`,
});
this.instances.set(userId, { client, port });
return client;
}
async releaseUser(userId: string): Promise<void> {
const instance = this.instances.get(userId);
if (instance) {
await instance.client.stop();
this.instances.delete(userId);
}
}
}
模式 2:共享 CLI 并进行会话隔离
多个用户共享一个 CLI 服务器,但通过唯一的会话 ID 实现会话隔离。这在资源占用上更轻量,但隔离性较弱。

何时使用
- 面向受信任用户的内部工具。
- 资源受限的环境。
- 对隔离性要求较低。
const sharedClient = new CopilotClient({
cliUrl: "localhost:4321",
});
// Enforce session isolation through naming conventions
function getSessionId(userId: string, purpose: string): string {
return `${userId}-${purpose}-${Date.now()}`;
}
// Access control: ensure users can only access their own sessions
async function resumeSessionWithAuth(
sessionId: string,
currentUserId: string
): Promise<Session> {
const [sessionUserId] = sessionId.split("-");
if (sessionUserId !== currentUserId) {
throw new Error("Access denied: session belongs to another user");
}
return sharedClient.resumeSession(sessionId);
}
模式 3:共享会话(协作)
多个用户交互同一个会话——类似于与 Copilot 的共享聊天房间。此模式需要在应用层实现会话锁定。

何时使用
- 团队协作工具。
- 共享代码审查会话。
- 配对编程助手。
注意
SDK 未提供内置会话锁定。您必须实现序列化访问,以防止对同一会话的并发写入。
import Redis from "ioredis";
const redis = new Redis();
async function withSessionLock<T>(
sessionId: string,
fn: () => Promise<T>,
timeoutSec = 300
): Promise<T> {
const lockKey = `session-lock:${sessionId}`;
const lockId = crypto.randomUUID();
// Acquire lock
const acquired = await redis.set(lockKey, lockId, "NX", "EX", timeoutSec);
if (!acquired) {
throw new Error("Session is in use by another user");
}
try {
return await fn();
} finally {
// Release lock only if we still own it
const currentLock = await redis.get(lockKey);
if (currentLock === lockId) {
await redis.del(lockKey);
}
}
}
// Serialize access to a shared session
app.post("/team-chat", authMiddleware, async (req, res) => {
const result = await withSessionLock("team-project-review", async () => {
const session = await client.resumeSession("team-project-review");
return session.sendAndWait({ prompt: req.body.message });
});
res.json({ content: result?.data.content });
});
隔离模式比较
| 每用户独立 CLI | 共享 CLI + 会话隔离 | 共享会话 | |
|---|---|---|---|
| 隔离性 | 完整 | 逻辑 | 共享 |
| 资源使用 | 高(每用户一个 CLI) | 低(单个 CLI) | 低(单个 CLI 与会话) |
| 复杂度 | 中 | 低 | 高(需要锁定) |
| 认证灵活性 | 每用户令牌 | 服务令牌 | 服务令牌 |
| 适用场景 | 多租户 SaaS | 内部工具 | 协作 |
水平扩展
负载均衡器后面的多个 CLI 服务器
为了服务更多并发用户,请在负载均衡器后运行多个 CLI 服务器实例。会话状态必须存放在共享存储上,以便任何 CLI 服务器都能恢复任意会话。

// Route sessions across CLI servers
class CLILoadBalancer {
private servers: string[];
private currentIndex = 0;
constructor(servers: string[]) {
this.servers = servers;
}
// Round-robin selection
getNextServer(): string {
const server = this.servers[this.currentIndex];
this.currentIndex = (this.currentIndex + 1) % this.servers.length;
return server;
}
// Sticky sessions: same user always hits same server
getServerForUser(userId: string): string {
const hash = this.hashCode(userId);
return this.servers[hash % this.servers.length];
}
private hashCode(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) - hash + str.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash);
}
}
const lb = new CLILoadBalancer([
"cli-1:4321",
"cli-2:4321",
"cli-3:4321",
]);
app.post("/chat", async (req, res) => {
const server = lb.getServerForUser(req.user.id);
const client = new CopilotClient({ cliUrl: server });
const session = await client.createSession({
sessionId: `user-${req.user.id}-chat`,
model: "gpt-4.1",
});
const response = await session.sendAndWait({ prompt: req.body.message });
res.json({ content: response?.data.content });
});
粘性会话 vs. 共享存储

粘性会话将每个用户固定到特定的 CLI 服务器。无需共享存储,但如果用户流量差异显著,负载分配可能不均。
共享存储使任意 CLI 能处理任意会话。负载分配更均衡,但需要网络存储用于~/.copilot/session-state/。
垂直扩展
调优单个 CLI 服务器
单个 CLI 服务器可以处理许多并发会话。关键是管理会话生命周期,以避免资源耗尽。

// Limit concurrent active sessions
class SessionManager {
private activeSessions = new Map<string, Session>();
private maxConcurrent: number;
constructor(maxConcurrent = 50) {
this.maxConcurrent = maxConcurrent;
}
async getSession(sessionId: string): Promise<Session> {
// Return existing active session
if (this.activeSessions.has(sessionId)) {
return this.activeSessions.get(sessionId)!;
}
// Enforce concurrency limit
if (this.activeSessions.size >= this.maxConcurrent) {
await this.evictOldestSession();
}
// Create or resume
const session = await client.createSession({
sessionId,
model: "gpt-4.1",
});
this.activeSessions.set(sessionId, session);
return session;
}
private async evictOldestSession(): Promise<void> {
const [oldestId] = this.activeSessions.keys();
const session = this.activeSessions.get(oldestId)!;
// Session state is persisted automatically—safe to disconnect
await session.disconnect();
this.activeSessions.delete(oldestId);
}
}
短暂会话 vs. 持久会话

短暂会话在每次请求时创建,使用后即销毁。它们非常适合一次性任务和无状态 API。
持久会话拥有名称,能够在重启后存活并可恢复。它们非常适合多轮对话和长期工作流。
短暂会话
app.post("/api/analyze", async (req, res) => {
const session = await client.createSession({
model: "gpt-4.1",
});
try {
const response = await session.sendAndWait({
prompt: req.body.prompt,
});
res.json({ result: response?.data.content });
} finally {
await session.disconnect();
}
});
持久会话
// Start a conversation
app.post("/api/chat/start", async (req, res) => {
const sessionId = `user-${req.user.id}-${Date.now()}`;
const session = await client.createSession({
sessionId,
model: "gpt-4.1",
infiniteSessions: {
enabled: true,
backgroundCompactionThreshold: 0.80,
},
});
res.json({ sessionId });
});
// Continue the conversation
app.post("/api/chat/message", async (req, res) => {
const session = await client.resumeSession(req.body.sessionId);
const response = await session.sendAndWait({ prompt: req.body.message });
res.json({ content: response?.data.content });
});
// Clean up when done
app.post("/api/chat/end", async (req, res) => {
await client.deleteSession(req.body.sessionId);
res.json({ success: true });
});
容器部署
带持久存储的 Kubernetes
下面的示例部署了三个共享 PersistentVolumeClaim 的 CLI 副本,以便任意副本都能恢复任意会话。
apiVersion: apps/v1
kind: Deployment
metadata:
name: copilot-cli
spec:
replicas: 3
selector:
matchLabels:
app: copilot-cli
template:
metadata:
labels:
app: copilot-cli
spec:
containers:
- name: copilot-cli
image: ghcr.io/github/copilot-cli:latest
args: ["--headless", "--port", "4321"]
env:
- name: COPILOT_GITHUB_TOKEN
valueFrom:
secretKeyRef:
name: copilot-secrets
key: github-token
ports:
- containerPort: 4321
volumeMounts:
- name: session-state
mountPath: /root/.copilot/session-state
volumes:
- name: session-state
persistentVolumeClaim:
claimName: copilot-sessions-pvc
---
apiVersion: v1
kind: Service
metadata:
name: copilot-cli
spec:
selector:
app: copilot-cli
ports:
- port: 4321
targetPort: 4321

生产检查清单
| 关注点 | 建议 |
|---|---|
| 会话清理 | 定期运行清理,删除超出 TTL 的会话。 |
| 健康检查 | 定期 ping CLI 服务器;若无响应则重启。 |
| 存储 | 为 ~/.copilot/session-state/ 挂载持久卷。 |
| 机密 | 使用平台的密钥管理器(Vault、Kubernetes Secrets 等)。 |
| 监控 | 跟踪活跃会话数、响应延迟和错误率。 |
| 锁定 | 使用 Redis 或类似方案实现共享会话访问。 |
| 关闭 | 在停止 CLI 服务器之前排空活跃会话。 |
限制
| 限制 | 详细信息 |
|---|---|
| 无内置会话锁定 | 实现应用层锁定以处理并发访问。 |
| 无内置负载均衡 | 使用外部负载均衡器或服务网格。 |
| 会话状态基于文件 | 多服务器设置需要共享文件系统。 |
| 30 分钟空闲超时 | CLI 会自动清理无活动的会话。 |
| CLI 为单进程 | 通过添加更多 CLI 服务器实例来扩展,而不是线程。 |
后续步骤
- 有关核心服务器端设置,请参阅后端服务的 Copilot SDK 设置。
- 有关多用户身份验证,请参阅使用 GitHub OAuth 与 Copilot SDK。
- 有关安装和首条消息的内容,请参阅 Copilot SDK 入门指南。