SDK 개요
HTTP 리스너 없이 메모리 내에서 API를 제공하는 @opencode/sdk로 애플리케이션 내부에 OpenCode를 호스팅합니다.
@opencode/sdk는 애플리케이션 내부에 OpenCode를 직접 호스팅합니다. 네트워크 클라이언트와 달리 OpenCode 서버를 조립하고 HTTP 라우터를 통해 API 호출을 메모리 내에서 라우팅합니다. HTTP 리스너를 열지 않으며 클라이언트와 서버 사이에 네트워크 홉이 추가되지 않습니다.
Cloudflare Durable Objects에 대해서는 Cloudflare 가이드를 참고하세요.
SDK를 설치합니다.
bun add @opencode/sdk호스트 생성
OpenCode.create()는 명시적으로 소유되는 호스트를 반환합니다. await using을 사용하여 라우터, Location 서비스, 파이버(fiber) 및 범위가 지정된 플러그인 등록을 해제하세요.
import { OpenCode } from "@opencode/sdk"
await using opencode = await OpenCode.create()
const session = await opencode.sessions.create({
location: { directory: "/workspace" },
})
await opencode.sessions.prompt({
sessionID: session.id,
text: "Review the current changes",
})명시적 리소스 관리(await using)를 사용할 수 없는 환경에서는 await opencode.close()를 직접 호출하세요.
임베디드 호스트는 @opencode/client와 동일한 Promise 값, 선언된 오류, 요청 옵션 및 AsyncIterable 스트림을 사용합니다. 생성된 전체 클라이언트를 노출하며 session 및 event 그룹을 위한 편의 별칭 sessions와 events를 추가 제공합니다.
워크트리(Worktrees)
워크트리 작업에는 projectID가 필요합니다. 생성(create)과 새로 고침(refresh)은 프로젝트의 저장된 정규 체크아웃(canonical checkout)에서 설정과 플러그인을 로드합니다. 목록 조회(list)는 저장된 인벤토리만 읽으며, 제거(remove)는 정규 플러그인을 활성화하고 기록된 전략을 사용하며 해당 전략을 사용할 수 없는 경우 실패합니다.
const projectID = session.projectID
const worktree = await opencode.worktree.create({ projectID, name: "task" })
await opencode.worktree.refresh({ projectID })
await opencode.worktree.remove({ projectID, directory: worktree.directory, force: false })새로 고침(refresh)은 사용 가능한 모든 전략을 사용해 알려진 체크아웃 루트 전반에서 워크트리를 검색합니다. 사용자 지정 전략은 플러그인의 워크트리 변환을 통해 등록할 수 있습니다.
이벤트 스트리밍
for await (const event of opencode.events.subscribe()) {
console.log(event.type)
}생성된 요청 옵션을 통해 AbortSignal을 전달하거나 반복을 중단해 응답 본문을 취소할 수 있습니다.
사용자 지정
플러그인을 등록하여 OpenCode 인스턴스를 사용자 지정할 수 있습니다. 임베디드 호스트가 시작될 때 에이전트, 모델, 도구 및 기타 동작을 사용자 지정하려면 OpenCode.create()에 플러그인을 전달하세요.
import { Plugin } from "@opencode/plugin"
import { OpenCode } from "@opencode/sdk"
const plugin = Plugin.define({
id: "customize-agent",
async setup(ctx) {
await ctx.agent.transform((agents) => {
agents.update("build", (agent) => {
agent.description = "Builds features and fixes bugs for our team"
})
})
},
})
await using opencode = await OpenCode.create({ plugins: [plugin] })시작 후에 다른 플러그인을 등록하려면 await opencode.plugin(plugin)을 호출하세요.
플러그인 훅, 변환, 도구 및 전체 플러그인 컨텍스트에 대해서는 전체 플러그인 문서를 참고하세요.