SDK
opencode 서버용 타입 안전 JS 클라이언트.
opencode JS/TS SDK는 서버와 상호작용하기 위한 타입 안전 클라이언트를 제공합니다. 통합을 구축하고 opencode를 프로그래밍 방식으로 제어하는 데 사용하세요.
서버 작동 방식에 대해 자세히 알아보세요. 커뮤니티가 구축한 프로젝트를 확인하세요.
설치
npm에서 SDK를 설치하세요:
npm install @opencode-ai/sdk클라이언트 생성
opencode 인스턴스를 생성하세요:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()이것은 서버와 클라이언트를 모두 시작합니다.
옵션
| 옵션 | 타입 | 설명 | 기본값 |
|---|---|---|---|
hostname | string | 서버 호스트명 | 127.0.0.1 |
port | number | 서버 포트 | 4096 |
signal | AbortSignal | 취소를 위한 중단 신호 | undefined |
timeout | number | 서버 시작 타임아웃 (ms) | 5000 |
config | Config | 설정 객체 | {} |
설정
동작을 커스터마이즈하기 위해 설정 객체를 전달할 수 있습니다. 인스턴스는 여전히 opencode.json을 읽지만, 인라인으로 설정을 재정의하거나 추가할 수 있습니다:
import { createOpencode } from "@opencode-ai/sdk"
const opencode = await createOpencode({
hostname: "127.0.0.1",
port: 4096,
config: {
model: "anthropic/claude-3-5-sonnet-20241022",
},
})
console.log(`Server running at ${opencode.server.url}`)
opencode.server.close()클라이언트만
이미 실행 중인 opencode 인스턴스가 있다면, 연결할 클라이언트 인스턴스를 생성할 수 있습니다:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({
baseUrl: "http://localhost:4096",
})옵션
| 옵션 | 타입 | 설명 | 기본값 |
|---|---|---|---|
baseUrl | string | 서버 URL | http://localhost:4096 |
fetch | function | 커스텀 fetch 구현 | globalThis.fetch |
parseAs | string | 응답 파싱 방법 | auto |
responseStyle | string | 반환 스타일: data 또는 fields | fields |
throwOnError | boolean | 반환 대신 에러 throw | false |
타입
SDK에는 모든 API 타입에 대한 TypeScript 정의가 포함되어 있습니다. 직접 import하세요:
import type { Session, Message, Part } from "@opencode-ai/sdk"모든 타입은 서버의 OpenAPI 사양에서 생성되며 타입 파일 (opens in a new tab)에서 사용할 수 있습니다.
에러
SDK는 catch하고 처리할 수 있는 에러를 throw할 수 있습니다:
try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("Failed to get session:", (error as Error).message)
}API
SDK는 타입 안전 클라이언트를 통해 모든 서버 API를 노출합니다.
Global
| 메서드 | 설명 | 응답 |
|---|---|---|
global.health() | 서버 상태 및 버전 확인 | { healthy: true, version: string } |
예제
const health = await client.global.health()
console.log(health.data.version)App
| 메서드 | 설명 | 응답 |
|---|---|---|
app.log() | 로그 항목 작성 | boolean |
app.agents() | 사용 가능한 모든 에이전트 목록 | Agent[] (opens in a new tab) |
예제
// 로그 항목 작성
await client.app.log({
body: {
service: "my-app",
level: "info",
message: "Operation completed",
},
})
// 사용 가능한 에이전트 목록
const agents = await client.app.agents()Project
| 메서드 | 설명 | 응답 |
|---|---|---|
project.list() | 모든 프로젝트 목록 | Project[] (opens in a new tab) |
project.current() | 현재 프로젝트 가져오기 | Project (opens in a new tab) |
예제
// 모든 프로젝트 목록
const projects = await client.project.list()
// 현재 프로젝트 가져오기
const currentProject = await client.project.current()Path
| 메서드 | 설명 | 응답 |
|---|---|---|
path.get() | 현재 경로 가져오기 | Path (opens in a new tab) |
예제
// 현재 경로 정보 가져오기
const pathInfo = await client.path.get()Config
| 메서드 | 설명 | 응답 |
|---|---|---|
config.get() | 설정 정보 가져오기 | Config (opens in a new tab) |
config.providers() | 프로바이더 및 기본 모델 목록 | { providers: Provider[] (opens in a new tab), default: { [key: string]: string } } |
예제
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()Sessions
| 메서드 | 설명 | 참고 |
|---|---|---|
session.list() | 세션 목록 | Session[] (opens in a new tab) 반환 |
session.get({ path }) | 세션 가져오기 | Session (opens in a new tab) 반환 |
session.children({ path }) | 하위 세션 목록 | Session[] (opens in a new tab) 반환 |
session.create({ body }) | 세션 생성 | Session (opens in a new tab) 반환 |
session.delete({ path }) | 세션 삭제 | boolean 반환 |
session.update({ path, body }) | 세션 속성 업데이트 | Session (opens in a new tab) 반환 |
session.init({ path, body }) | 앱 분석 및 AGENTS.md 생성 | boolean 반환 |
session.abort({ path }) | 실행 중인 세션 중단 | boolean 반환 |
session.share({ path }) | 세션 공유 | Session (opens in a new tab) 반환 |
session.unshare({ path }) | 세션 공유 해제 | Session (opens in a new tab) 반환 |
session.summarize({ path, body }) | 세션 요약 | boolean 반환 |
session.messages({ path }) | 세션의 메시지 목록 | { info: Message (opens in a new tab), parts: Part[] (opens in a new tab)}[] 반환 |
session.message({ path }) | 메시지 상세 정보 가져오기 | { info: Message (opens in a new tab), parts: Part[] (opens in a new tab)} 반환 |
session.prompt({ path, body }) | 프롬프트 메시지 전송 | body.noReply: true는 UserMessage 반환 (컨텍스트만). 기본값은 AI 응답이 포함된 AssistantMessage (opens in a new tab) 반환 |
session.command({ path, body }) | 세션에 명령 전송 | { info: AssistantMessage (opens in a new tab), parts: Part[] (opens in a new tab)} 반환 |
session.shell({ path, body }) | 셸 명령 실행 | AssistantMessage (opens in a new tab) 반환 |
session.revert({ path, body }) | 메시지 되돌리기 | Session (opens in a new tab) 반환 |
session.unrevert({ path }) | 되돌린 메시지 복원 | Session (opens in a new tab) 반환 |
postSessionByIdPermissionsByPermissionId({ path, body }) | 권한 요청에 응답 | boolean 반환 |
예제
// 세션 생성 및 관리
const session = await client.session.create({
body: { title: "My session" },
})
const sessions = await client.session.list()
// 프롬프트 메시지 전송
const result = await client.session.prompt({
path: { id: session.id },
body: {
model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" },
parts: [{ type: "text", text: "Hello!" }],
},
})
// AI 응답을 트리거하지 않고 컨텍스트 주입 (플러그인에 유용)
await client.session.prompt({
path: { id: session.id },
body: {
noReply: true,
parts: [{ type: "text", text: "You are a helpful assistant." }],
},
})Files
| 메서드 | 설명 | 응답 |
|---|---|---|
find.text({ query }) | 파일에서 텍스트 검색 | path, lines, line_number, absolute_offset, submatches가 포함된 매치 객체 배열 |
find.files({ query }) | 이름으로 파일 및 디렉토리 찾기 | string[] (경로) |
find.symbols({ query }) | 워크스페이스 심볼 찾기 | Symbol[] (opens in a new tab) |
file.read({ query }) | 파일 읽기 | { type: "raw" | "patch", content: string } |
file.status({ query? }) | 추적된 파일의 상태 가져오기 | File[] (opens in a new tab) |
find.files는 몇 가지 선택적 쿼리 필드를 지원합니다:
type:"file"또는"directory"directory: 검색을 위한 프로젝트 루트 재정의limit: 최대 결과 수 (1-200)
예제
// 파일 검색 및 읽기
const textResults = await client.find.text({
query: { pattern: "function.*opencode" },
})
const files = await client.find.files({
query: { query: "*.ts", type: "file" },
})
const directories = await client.find.files({
query: { query: "packages", type: "directory", limit: 20 },
})
const content = await client.file.read({
query: { path: "src/index.ts" },
})TUI
| 메서드 | 설명 | 응답 |
|---|---|---|
tui.appendPrompt({ body }) | 프롬프트에 텍스트 추가 | boolean |
tui.openHelp() | 도움말 대화상자 열기 | boolean |
tui.openSessions() | 세션 선택기 열기 | boolean |
tui.openThemes() | 테마 선택기 열기 | boolean |
tui.openModels() | 모델 선택기 열기 | boolean |
tui.submitPrompt() | 현재 프롬프트 제출 | boolean |
tui.clearPrompt() | 프롬프트 지우기 | boolean |
tui.executeCommand({ body }) | 명령 실행 | boolean |
tui.showToast({ body }) | 토스트 알림 표시 | boolean |
예제
// TUI 인터페이스 제어
await client.tui.appendPrompt({
body: { text: "Add this to prompt" },
})
await client.tui.showToast({
body: { message: "Task completed", variant: "success" },
})Auth
| 메서드 | 설명 | 응답 |
|---|---|---|
auth.set({ ... }) | 인증 자격 증명 설정 | boolean |
예제
await client.auth.set({
path: { id: "anthropic" },
body: { type: "api", key: "your-api-key" },
})Events
| 메서드 | 설명 | 응답 |
|---|---|---|
event.subscribe() | 서버 전송 이벤트 스트림 | 서버 전송 이벤트 스트림 |
예제
// 실시간 이벤트 수신
const events = await client.event.subscribe()
for await (const event of events.stream) {
console.log("Event:", event.type, event.properties)
}