中文
文档
基于 OpenCode 构建
SDK
Cloudflare

Cloudflare

使用 @opencode/sdk/workerd 在 Cloudflare Durable Object 中运行 OpenCode,由对象的内置 SQLite 存储提供持久化支持。

在 Cloudflare Durable Object 中请使用 @opencode/sdk/workerd。该运行时配置会自动接入 Durable Object 的 SQLite 存储,持久化事件以支持驱逐后恢复,并替换在边缘环境中不可用的本地文件系统与进程服务。

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

有关插件钩子、转换器、工具以及完整插件上下文的详细说明,请参阅完整插件文档。