日本語
ドキュメント
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 インスタンスのライフタイム全体で 1 つのホストを保持してください。

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 設定、モデルリクエスト、Web 取得・検索、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],
})

プラグインのフック、変換、ツール、およびプラグインコンテキストの詳細については、プラグインの完全なドキュメントを参照してください。