SDK
面向 OpenCode Server 的类型安全 JS 客户端。
OpenCode JS/TS SDK 提供了一个类型安全的客户端,用来与 OpenCode Server 交互。 你可以基于它构建自己的集成,或以编程方式控制 OpenCode。
关于 Server 端 API 结构,见 Server 文档;示例项目可参考 生态系统。
安装
从 npm 安装 SDK:
npm install @opencode-ai/sdk创建客户端与服务端
创建并启动一个带有内置 Server 的 OpenCode 实例:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()这会在本地启动一个 Server,并返回对应的 client。
可选参数:
| 选项 | 类型 | 说明 | 默认值 |
|---|---|---|---|
hostname | string | Server 监听主机名 | 127.0.0.1 |
port | number | Server 监听端口 | 4096 |
signal | AbortSignal | 用于取消启动的 AbortSignal | undefined |
timeout | number | Server 启动超时时间(毫秒) | 5000 |
config | Config | 额外配置(会与本地配置合并) | {} |
示例:
import { createOpencode } from "@opencode-ai/sdk"
const opencode = await createOpencode({ hostname: "127.0.0.1", port: 4096, config: { model: "anthropic/claude-3-5-sonnet-20241022" }})
console.log(`Server running at ${opencode.server.url}`)
opencode.server.close()仅创建客户端
如果你已经有一个运行中的 Server,可以只创建一个客户端连接过去:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({ baseUrl: "http://localhost:4096"})可选参数:
| 选项 | 类型 | 说明 | 默认值 |
|---|---|---|---|
baseUrl | string | Server 地址 | http://localhost:4096 |
fetch | function | 自定义 fetch 实现 | globalThis.fetch |
parseAs | string | 响应解析方式(如 auto) | auto |
responseStyle | string | 返回形式:data 或 fields | fields |
throwOnError | boolean | 是否在错误时直接抛异常 | false |
类型定义
SDK 内置所有 API 的 TypeScript 类型,可以直接导入:
import type { Session, Message, Part } from "@opencode-ai/sdk"所有类型都由 Server 的 OpenAPI 规范自动生成,并可以在 类型文件 中查看。
错误处理
SDK 调用失败时会抛出异常,你可以 try/catch 捕获:
try { await client.session.get({ path: { id: "invalid-id" } })} catch (error) { console.error("Failed to get session:", (error as Error).message)}是否抛异常由 throwOnError 决定。
API 概览
SDK 为所有 Server API 提供类型安全封装,常用模块如下:
Global
| 方法 | 说明 | 返回值 |
|---|---|---|
global.health() | 检查 Server 健康与版本 | { healthy: true, version: string } |
示例:
const health = await client.global.health()console.log(health.data.version)App
| 方法 | 说明 | 返回值 |
|---|---|---|
app.log() | 写一条日志 | boolean |
app.agents() | 列出所有可用 Agents | Agent[] |
示例:
await client.app.log({ body: { service: "my-app", level: "info", message: "Operation completed" }})
const agents = await client.app.agents()Project / Path
| 模块 | 方法 | 说明 |
|---|---|---|
project | list() | 列出所有项目 |
current() | 获取当前项目 | |
path | get() | 获取当前路径 |
示例:
const projects = await client.project.list()const currentProject = await client.project.current()
const pathInfo = await client.path.get()Config
| 方法 | 说明 |
|---|---|
config.get() | 获取当前配置 |
config.providers() | 获取提供商及默认模型列表 |
const config = await client.config.get()const { providers, default: defaults } = await client.config.providers()Sessions(会话)
SDK 提供完整的会话管理 API:
- 创建/删除/更新会话
- 获取会话列表、子会话
- 发送 Prompt / 命令 / Shell
- 分享与取消分享
- 总结、撤销/恢复消息
示例:
// 创建会话const session = await client.session.create({ body: { title: "My session" }})
// 发送一条 Promptconst result = await client.session.prompt({ path: { id: session.id }, body: { model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, parts: [{ type: "text", text: "Hello!" }] }})
// 只注入上下文,不触发回复(插件中很常用)await client.session.prompt({ path: { id: session.id }, body: { noReply: true, parts: [{ type: "text", text: "You are a helpful assistant." }] }})Files(文件操作)
常用方法:
find.text({ query }):在文件中搜索文本find.files({ query }):按名称/模式查找文件或目录file.read({ query }):读取文件内容file.status({ query? }):获取被跟踪文件状态
示例:
const textResults = await client.find.text({ query: { pattern: "function.*opencode" }})
const files = await client.find.files({ query: { query: "*.ts", type: "file" }})
const content = await client.file.read({ query: { path: "src/index.ts" }})TUI 控制
可以远程控制 TUI:
tui.appendPrompt:向输入框追加文本tui.submitPrompt:提交当前 Prompttui.showToast:在 TUI 中弹出提示
await client.tui.appendPrompt({ body: { text: "Add this to prompt" }})
await client.tui.showToast({ body: { message: "Task completed", variant: "success" }})认证(Auth)
可以通过 SDK 设置 Server 端的 Provider 凭证:
await client.auth.set({ path: { id: "anthropic" }, body: { type: "api", key: "your-api-key" }})事件流(Events)
event.subscribe() 可以订阅 Server 端的事件流(SSE):
const events = await client.event.subscribe()for await (const event of events.stream) { console.log("Event:", event.type, event.properties)}适合做:
- 自定义 UI 的“流式输出”;
- 监控会话状态、工具调用等。