한국어
문서
SDK

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()

이것은 서버와 클라이언트를 모두 시작합니다.

옵션

옵션타입설명기본값
hostnamestring서버 호스트명127.0.0.1
portnumber서버 포트4096
signalAbortSignal취소를 위한 중단 신호undefined
timeoutnumber서버 시작 타임아웃 (ms)5000
configConfig설정 객체{}

설정

동작을 커스터마이즈하기 위해 설정 객체를 전달할 수 있습니다. 인스턴스는 여전히 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",
})

옵션

옵션타입설명기본값
baseUrlstring서버 URLhttp://localhost:4096
fetchfunction커스텀 fetch 구현globalThis.fetch
parseAsstring응답 파싱 방법auto
responseStylestring반환 스타일: data 또는 fieldsfields
throwOnErrorboolean반환 대신 에러 throwfalse

타입

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)
}

구조화된 출력 (SDK 1.18.31)

이 예제는 @opencode-ai/sdk/v2를 사용합니다. 이 페이지의 다른 예제는 기존 루트 내보내기와 path/body 인자 구조를 사용합니다.

실행 중인 로컬 v1 서버(opencode serve)에 연결합니다. 먼저 공급자와 모델을 설정하세요. 응답 생성 시 공급자의 요금이 발생할 수 있습니다.

import { createOpencodeClient } from "@opencode-ai/sdk/v2"
 
const client = createOpencodeClient({ baseUrl: "http://localhost:4096" })
const session = await client.session.create({ title: "Schema example" }, { throwOnError: true })
const result = await client.session.prompt({
  sessionID: session.data.id,
  parts: [{ type: "text", text: "Return the name and language of this project." }],
  format: {
    type: "json_schema",
    schema: {
      type: "object",
      properties: {
        name: { type: "string", description: "Project name" },
        language: { type: "string", description: "Primary programming language" },
      },
      required: ["name", "language"],
      additionalProperties: false,
    },
    retryCount: 2,
  },
}, { throwOnError: true })
 
const info = result.data.info
if (info.error) {
  if (info.error.name === "StructuredOutputError") {
    console.error(info.error.data.message, info.error.data.retries)
  } else {
    console.error(info.error)
  }
} else {
  console.log(info.structured)
}

format에는 text 또는 json_schema를 지정합니다. JSON 출력에는 schema에 JSON Schema를 전달합니다. retryCount는 검증 재시도 횟수이며 기본값은 2입니다. required와 명확한 필드 설명을 사용하고 스키마를 간결하게 유지하세요.

throwOnError가 꺼져 있으면 통신 또는 API 오류는 error로 반환됩니다. 모델 오류는 별도로 info.error에서 확인합니다. StructuredOutputError의 세부 정보는 error.data.message와 error.data.retries에 있고, 성공한 데이터는 info.structured에 있습니다.

이 예제는 @opencode-ai/sdk v1.18.31을 사용합니다. 인터페이스 정의는 SDK 소스 (opens in a new tab)를 참고하세요.


API

SDK는 타입 안전 클라이언트를 통해 모든 서버 API를 노출합니다.


전역

메서드설명응답
global.health()서버 상태 및 버전 확인{ healthy: true, version: string }

예제

const health = await client.global.health()
console.log(health.data.version)

앱

메서드설명응답
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.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.get()현재 경로 가져오기Path (opens in a new tab)

예제

// 현재 경로 정보 가져오기
const pathInfo = await client.path.get()

설정

메서드설명응답
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()

세션

메서드설명참고
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." }],
  },
})

파일

메서드설명응답
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.set({ ... })인증 자격 증명 설정boolean

예제

await client.auth.set({
  path: { id: "anthropic" },
  body: { type: "api", key: "your-api-key" },
})

이벤트

메서드설명응답
event.subscribe()서버 전송 이벤트 스트림서버 전송 이벤트 스트림

예제

// 실시간 이벤트 수신
const events = await client.event.subscribe()
for await (const event of events.stream) {
  console.log("Event:", event.type, event.properties)
}

문서 출처 (MIT)