참고
코필로트 SDK가 현재 기술 미리 보기에 있습니다. 기능 및 가용성은 변경될 수 있습니다.
CLI는 백 엔드 코드가 네트워크를 통해 연결하는 헤드리스 서버로 실행됩니다.
**최적 대상:** 웹앱 백 엔드, API 서비스, 내부 도구, CI/CD 통합, 모든 서버 쪽 워크로드.
작동 방식
SDK가 CLI 자식 프로세스를 생성하는 대신 헤드리스 서버 모드에서 독립적으로 CLI를 실행합니다. 백 엔드는 TCP를 통해 cliUrl 옵션을 사용하여 연결합니다. 헤드리스 서버 아키텍처에 대한 자세한 다이어그램과 기본 자동 관리 CLI와 비교하는 방법은 github/copilot-sdk를 참조하세요.
주요 특징:
- CLI는 요청당 생성되지 않고 영구 서버 프로세스로 실행됩니다.
- SDK는 TCP를 통해 연결됩니다. CLI 및 앱은 다른 컨테이너에서 실행할 수 있습니다.
- 여러 SDK 클라이언트는 하나의 CLI 서버를 공유할 수 있습니다.
- 모든 인증 방법(GitHub 토큰, 환경 변수, BYOK)에서 작동합니다.
1단계: CLI를 헤드리스 모드에서 시작
CLI를 백그라운드 서버로 실행합니다.
# Start with a specific port
copilot --headless --port 4321
# Or let it pick a random port (prints the URL)
copilot --headless
# Output: Listening on http://localhost:52431
프로덕션의 경우 시스템 서비스 또는 컨테이너에서 실행합니다.
# Docker
docker run -d --name copilot-cli \
-p 4321:4321 \
-e COPILOT_GITHUB_TOKEN="$TOKEN" \
ghcr.io/github/copilot-cli:latest \
--headless --port 4321
# systemd
[Service]
ExecStart=/usr/local/bin/copilot --headless --port 4321
Environment=COPILOT_GITHUB_TOKEN=YOUR-GITHUB-TOKEN
Restart=always
2단계: SDK 연결
Node.js/ TypeScript
import { CopilotClient } from "@github/copilot-sdk";
const client = new CopilotClient({
cliUrl: "localhost:4321",
});
const session = await client.createSession({
sessionId: `user-${userId}-${Date.now()}`,
model: "gpt-4.1",
});
const response = await session.sendAndWait({ prompt: req.body.message });
res.json({ content: response?.data.content });
파이썬
from copilot import CopilotClient
client = CopilotClient({
"cli_url": "localhost:4321",
})
await client.start()
session = await client.create_session({
"session_id": f"user-{user_id}-{int(time.time())}",
"model": "gpt-4.1",
})
response = await session.send_and_wait({"prompt": message})
이동
client := copilot.NewClient(&copilot.ClientOptions{
CLIUrl: "localhost:4321",
})
client.Start(ctx)
defer client.Stop()
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
SessionID: fmt.Sprintf("user-%s-%d", userID, time.Now().Unix()),
Model: "gpt-4.1",
})
response, _ := session.SendAndWait(ctx, copilot.MessageOptions{Prompt: message})
.NET
var client = new CopilotClient(new CopilotClientOptions
{
CliUrl = "localhost:4321",
UseStdio = false,
});
await using var session = await client.CreateSessionAsync(new SessionConfig
{
SessionId = $"user-{userId}-{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}",
Model = "gpt-4.1",
});
var response = await session.SendAndWaitAsync(
new MessageOptions { Prompt = message });
백 엔드 서비스에 대한 인증
환경 변수 토큰
가장 간단한 방법은 CLI 서버에서 토큰을 설정하는 것입니다.
# All requests use this token
export COPILOT_GITHUB_TOKEN="YOUR-SERVICE-ACCOUNT-TOKEN"
copilot --headless --port 4321
서비스 계정에 대해 YOUR-SERVICE-ACCOUNT-TOKENGitHub 또는 OAuth 토큰으로 personal access token을(를) 바꾸십시오.
사용자별 토큰(OAuth)
세션을 만들 때 개별 사용자 토큰을 전달합니다.
// Your API receives user tokens from your auth layer
app.post("/chat", authMiddleware, async (req, res) => {
const client = new CopilotClient({
cliUrl: "localhost:4321",
githubToken: req.user.githubToken,
useLoggedInUser: false,
});
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 });
});
BYOK(인증 없음 GitHub )
모델 공급자에 대해 사용자 고유의 API 키를 사용합니다.
const client = new CopilotClient({
cliUrl: "localhost:4321",
});
const session = await client.createSession({
model: "gpt-4.1",
provider: {
type: "openai",
baseUrl: "https://api.openai.com/v1",
apiKey: process.env.OPENAI_API_KEY,
},
});
일반적인 백 엔드 패턴
Express를 사용하는 Web API
import express from "express";
import { CopilotClient } from "@github/copilot-sdk";
const app = express();
app.use(express.json());
// Single shared CLI connection
const client = new CopilotClient({
cliUrl: process.env.CLI_URL || "localhost:4321",
});
app.post("/api/chat", async (req, res) => {
const { sessionId, message } = req.body;
// Create or resume session
let session;
try {
session = await client.resumeSession(sessionId);
} catch {
session = await client.createSession({
sessionId,
model: "gpt-4.1",
});
}
const response = await session.sendAndWait({ prompt: message });
res.json({
sessionId,
content: response?.data.content,
});
});
app.listen(3000);
백그라운드 작업자
import { CopilotClient } from "@github/copilot-sdk";
const client = new CopilotClient({
cliUrl: process.env.CLI_URL || "localhost:4321",
});
// Process jobs from a queue
async function processJob(job: Job) {
const session = await client.createSession({
sessionId: `job-${job.id}`,
model: "gpt-4.1",
});
const response = await session.sendAndWait({
prompt: job.prompt,
});
await saveResult(job.id, response?.data.content);
await session.disconnect(); // Clean up after job completes
}
Docker Compose 배포
version: "3.8"
services:
copilot-cli:
image: ghcr.io/github/copilot-cli:latest
command: ["--headless", "--port", "4321"]
environment:
- COPILOT_GITHUB_TOKEN=${COPILOT_GITHUB_TOKEN}
ports:
- "4321:4321"
restart: always
volumes:
- session-data:/root/.copilot/session-state
api:
build: .
environment:
- CLI_URL=copilot-cli:4321
depends_on:
- copilot-cli
ports:
- "3000:3000"
volumes:
session-data:
건강 상태 검사
CLI 서버의 상태를 모니터링합니다.
// Periodic health check
async function checkCLIHealth(): Promise<boolean> {
try {
const status = await client.getStatus();
return status !== undefined;
} catch {
return false;
}
}
세션 정리
백 엔드 서비스는 리소스 누출을 방지하기 위해 세션을 적극적으로 정리해야 합니다.
// Clean up expired sessions periodically
async function cleanupSessions(maxAgeMs: number) {
const sessions = await client.listSessions();
const now = Date.now();
for (const session of sessions) {
const age = now - new Date(session.createdAt).getTime();
if (age > maxAgeMs) {
await client.deleteSession(session.sessionId);
}
}
}
// Run every hour
setInterval(() => cleanupSessions(24 * 60 * 60 * 1000), 60 * 60 * 1000);
제한점
| Limitation | 세부 정보 |
|---|
**단일 CLI 서버 = 단일 실패 지점** | 프로덕션 배포에 대한 고가용성 패턴을 고려합니다. |
| SDK와 CLI 간에 기본 제공 인증 없음 | 네트워크 경로(동일한 호스트, VPC 등)를 보호합니다. | | 로컬 디스크의 세션 상태 | 컨테이너 다시 시작을 위해 영구 스토리지를 탑재합니다. | | 30분 유휴 시간 제한 | 활동이 없는 세션은 자동으로 정리됩니다. |
다음 단계
- 설치 및 첫 번째 메시지는 Copilot SDK 사용 시작하기을 참조하세요.
- 다시 시작 시 세션을 다시 시작하는 방법에 대한 자세한 내용은 리포지토리의
github/copilot-sdk참조하세요. - 사용자 인증을 추가하는 방법에 대한 자세한 내용은 리포지토리의 GitHub OAuth 를
github/copilot-sdk참조하세요.