@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 opencode.close()。
嵌入式宿主使用与 @opencode/client 相同的 Promise 值、声明的错误、请求选项和 AsyncIterable 流。它暴露完整的生成客户端,并为会话与事件分组添加了便捷别名 sessions 和 events。

工作树

工作树操作需要 projectID。create 与 refresh 会从项目已保存的规范检出中加载配置与插件。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 会使用所有可用策略,在已知检出根目录中发现工作树。可通过插件的 worktree 转换注册自定义策略。

流式接收事件

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) 注册另一个插件。
有关插件钩子、转换、工具以及完整的插件上下文,请参阅完整插件文档。