한국어
문서
OpenCode에서 빌드하기
SDK
Cloudflare

Cloudflare

객체의 SQLite 스토리지를 기반으로 하는 @opencode/sdk/workerd를 사용해 Cloudflare Durable Object 내부에서 OpenCode를 실행합니다.

Cloudflare Durable Object 내부에서는 @opencode/sdk/workerd를 사용하세요. 이 프로필은 객체의 SQLite 스토리지를 사용하고, 축출(eviction) 복구를 위해 내구성 있는 이벤트를 영속화하며, 사용할 수 없는 로컬 파일 시스템과 프로세스 서비스를 대체합니다.

bun add @opencode/sdk

요청마다 새로 생성하지 말고 Durable Object 인스턴스의 수명 동안 하나의 호스트를 유지하세요.

import { OpenCodeWorkerd } from "@opencode/sdk/workerd"
import myPlugin from "./my-plugin"
 
export class OpenCodeDO {
  private readonly opencode: Promise<OpenCodeWorkerd.Interface>
 
  constructor(state: DurableObjectState) {
    this.opencode = state.blockConcurrencyWhile(() =>
      OpenCodeWorkerd.create({
        storage: state.storage,
        config: { default_agent: "build" },
        plugins: [myPlugin],
      }),
    )
  }
 
  async fetch() {
    const opencode = await this.opencode
    return Response.json(await opencode.server.info())
  }
}

blockConcurrencyWhile은 호스트가 준비될 때까지 모든 Durable Object 이벤트를 대기시키고, 초기화가 실패하면 객체를 재설정합니다. 유지된 Promise를 통해 시작 후 요청 핸들러가 동일한 호스트에 직접 액세스할 수 있습니다.

constructor(state: DurableObjectState) {
  this.opencode = state.blockConcurrencyWhile(() =>
    OpenCodeWorkerd.create({ storage: state.storage }),
  )
}

Wrangler는 workerd 패키지 조건을 통해 OpenCode의 Workerd 안전 구현을 선택합니다. Cloudflare는 정리 작업을 실행하지 않고 Durable Object를 축출할 수 있으므로 정확성은 close() 호출 여부에 의존하지 않습니다.

wrangler.jsonc
{
  "compatibility_flags": ["nodejs_compat"]
}

아웃바운드 요청 라우팅

fetch를 전달하면 OpenCode의 아웃바운드 HTTP 요청(OpenCode Console 설정, 모델 요청, 웹 페치 및 검색, well-known 설정, 원격 MCP 서버)을 Service Binding 같은 사용자 지정 핸들러를 통해 라우팅할 수 있습니다. Code Mode의 에이전트 코드는 계속 globalThis.fetch를 사용합니다.

OpenCodeWorkerd.create({
  storage: state.storage,
  fetch: (input, init) => {
    const request = new Request(input, init)
    return new URL(request.url).hostname === "console.example.com" ? env.CONSOLE.fetch(request) : fetch(request)
  },
})

사용자 지정

Worker와 함께 번들링된 플러그인을 등록하여 OpenCode 인스턴스를 사용자 지정할 수 있습니다. 에이전트, 모델, 도구 및 기타 동작을 사용자 지정하려면 OpenCodeWorkerd.create()에 플러그인을 전달하세요.

import { Plugin } from "@opencode/plugin"
import { OpenCodeWorkerd } from "@opencode/sdk/workerd"
 
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 OpenCodeWorkerd.create({
  storage: state.storage,
  config: { default_agent: "build" },
  plugins: [plugin],
})

플러그인 훅, 변환, 도구 및 전체 플러그인 컨텍스트에 대해서는 전체 플러그인 문서를 참고하세요.