SDK
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 | 취소용 abort signal | undefined |
timeout | number | 서버 시작 타임아웃(밀리초) | 5000 |
config | Config | 설정 객체 | {} |
설정
동작을 사용자 정의하기 위해 설정 객체를 전달할 수 있습니다. 인스턴스는 여전히 opencode.json을 사용하지만, 인라인으로 설정을 재정의하거나 추가할 수 있습니다:
import { createOpencode } from "@opencode-ai/sdk"
const opencode = await createOpencode({
hostname: "127.0.0.1",
port: 4096,
config: {
model: "<provider>/<model>",
},
})
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 | 반환 대신 오류 발생 | false |
타입
SDK에는 모든 API 타입에 대한 TypeScript 정의가 포함되어 있습니다. 직접 가져오세요:
import type { Session, Message, Part } from "@opencode-ai/sdk"
모든 타입은 서버의 OpenAPI 사양에서 생성되며 types 파일에서 사용할 수 있습니다.
오류
SDK는 잡아서 처리할 수 있는 오류를 던질 수 있습니다:
try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("Failed to get session:", (error as Error).message)
}
구조화된 출력
JSON 스키마로 format을 지정하여 모델에서 구조화된 JSON 출력을 요청할 수 있습니다. 모델은 StructuredOutput 도구를 사용하여 스키마와 일치하는 검증된 JSON을 반환합니다.
기본 사용법
const result = await client.session.prompt({
path: { id: sessionId },
body: {
parts: [{ type: "text", text: "Research Anthropic and provide company info" }],
format: {
type: "json_schema",
schema: {
type: "object",
properties: {
company: { type: "string", description: "Company name" },
founded: { type: "number", description: "Year founded" },
products: {
type: "array",
items: { type: "string" },
description: "Main products",
},
},
required: ["company", "founded"],
},
},
},
})
// Access the structured output
console.log(result.data.info.structured_output)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
출력 형식 타입
| 타입 | 설명 |
|---|---|
text | 기본값. 일반 텍스트 응답(구조화 출력 없음) |
json_schema | 제공된 스키마에 맞는 검증된 JSON 반환 |
JSON Schema 형식
type: 'json_schema'를 사용할 때 다음을 제공하세요:
| 필드 | 타입 | 설명 |
|---|---|---|
type | 'json_schema' | 필수. JSON 스키마 모드 지정 |
schema | object | 필수. 출력 구조를 정의하는 JSON Schema 객체 |
retryCount | number | 선택. 검증 재시도 횟수(기본값: 2) |
오류 처리
모든 재시도 후에도 모델이 유효한 구조화된 출력을 생성하지 못하면 응답에 StructuredOutputError가 포함됩니다:
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
}
모범 사례
- 명확한 설명 제공 - 모델이 어떤 데이터를 추출해야 하는지 이해할 수 있도록 스키마 속성에 명확한 설명을 제공하세요
required사용 - 반드시 존재해야 하는 필드를 지정하세요- 스키마를 집중 - 복잡한 중첩 스키마는 모델이 올바르게 채우기 어려울 수 있습니다
- 적절한
retryCount설정 - 복잡한 스키마에는 늘리고, 단순한 스키마에는 줄이세요
APIs
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[] |
예제
// Write a log entry
await client.app.log({
body: {
service: "my-app",
level: "info",
message: "Operation completed",
},
})
// List available agents
const agents = await client.app.agents()
Project
| 메서드 | 설명 | 응답 |
|---|---|---|
project.list() | 모든 프로젝트 목록 조회 | Project[] |
project.current() | 현재 프로젝트 가져오기 | Project |
예제
// List all projects
const projects = await client.project.list()
// Get current project
const currentProject = await client.project.current()
Path
| 메서드 | 설명 | 응답 |
|---|---|---|
path.get() | 현재 경로 가져오기 | Path |
예제
// Get current path information
const pathInfo = await client.path.get()
Config
| 메서드 | 설명 | 응답 |
|---|---|---|
config.get() | 설정 정보 가져오기 | Config |
config.providers() | provider 및 기본 모델 목록 조회 | { providers: Provider[], default: { [key: string]: string } } |
예제
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()
Sessions
| Method | Description | Notes |
|---|---|---|
session.list() | List sessions | Returns Session[] |
session.get({ path }) | Get session | Returns Session |
session.children({ path }) | List child sessions | Returns Session[] |
session.create({ body }) | Create session | Returns Session |
session.delete({ path }) | Delete session | Returns boolean |
session.update({ path, body }) | Update session properties | Returns Session |
session.init({ path, body }) | Analyze app and create AGENTS.md | Returns boolean |
session.abort({ path }) | Abort a running session | Returns boolean |
session.share({ path }) | Share session | Returns Session |
session.unshare({ path }) | Unshare session | Returns Session |
session.summarize({ path, body }) | Summarize session | Returns boolean |
session.messages({ path }) | List messages in a session | Returns { info: Message, parts: Part[] }[] |
session.message({ path }) | Get message details | Returns { info: Message, parts: Part[] } |
session.prompt({ path, body }) | 프롬프트 메시지 전송 | body.noReply: true는 UserMessage(컨텍스트 전용)를 반환합니다. 기본값은 AI 응답이 포함된 AssistantMessage를 반환합니다. 구조화 출력을 위한 body.outputFormat을 지원합니다 |
session.command({ path, body }) | Send command to session | Returns { info: AssistantMessage, parts: Part[] } |
session.shell({ path, body }) | Run a shell command | Returns AssistantMessage |
session.revert({ path, body }) | Revert a message | Returns Session |
session.unrevert({ path }) | Restore reverted messages | Returns Session |
postSessionByIdPermissionsByPermissionId({ path, body }) | Respond to a permission request | Returns boolean |
예제
// Create and manage sessions
const session = await client.session.create({
body: { title: "My session" },
})
const sessions = await client.session.list()
// Send a prompt message
const result = await client.session.prompt({
path: { id: session.id },
body: {
model: { providerID: "anthropic", modelID: "<model>" },
parts: [{ type: "text", text: "Hello!" }],
},
})
// Inject context without triggering AI response (useful for plugins)
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[] |
file.read({ query }) | 파일 읽기 | { type: "raw" | "patch", content: string } |
file.status({ query? }) | 추적 중인 파일의 상태 가져오기 | File[] |
find.files는 몇 가지 선택적 쿼리 필드를 지원합니다:
type:"file"또는"directory"directory: 검색의 프로젝트 루트 재정의limit: 최대 결과 수 (1–200)
예제
// Search and read files
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 |
예제
// Control TUI interface
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() | 서버 전송 이벤트 스트림 | 서버 전송 이벤트 스트림 |
예제
// Listen to real-time events
const events = await client.event.subscribe()
for await (const event of events.stream) {
console.log("Event:", event.type, event.properties)
}