OpenCode SDK
OpenCode JS/TS SDK 提供了类型安全的客户端,用于与服务器交互。可借助它构建集成并以编程方式控制 OpenCode。
安装 (Installation)
通过 npm 安装 SDK,终端执行命令:
npm install @opencode-ai/sdk
创建客户端 (Creating a Client)
- 常规创建(同时启动服务器和客户端):
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()
- 配置选项
| 选项 | 类型 | 描述 | 默认值 |
|---|---|---|---|
hostname | string | 服务器主机名 | 127.0.0.1 |
port | number | 服务器端口 | 4096 |
signal | AbortSignal | 用于取消的中止信号 | undefined |
timeout | number | 服务器启动超时时间(毫秒) | 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(`服务器运行在 ${opencode.server.url}`)
opencode.server.close()
- 仅创建客户端(连接现有服务器):
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({
baseUrl: "http://localhost:4096",
})
- 仅客户端配置选项
| 选项 | 类型 | 描述 | 默认值 |
|---|---|---|---|
baseUrl | string | 服务器 URL | http://localhost:4096 |
fetch | function | 自定义 fetch 实现 | globalThis.fetch |
parseAs | string | 响应解析方式 | auto |
responseStyle | string | 返回样式:data 或 fields | fields |
throwOnError | boolean | 抛出错误而非返回错误 | false |
类型支持 (Type Support)
SDK 包含所有 API 类型的 TypeScript 定义,可直接导入:
import type { Session, Message, Part } from "@opencode-ai/sdk"
所有类型均基于服务器的 OpenAPI 规范生成,可在类型文件中查看。
错误处理 (Error Handling)
可捕获并处理 SDK 抛出的错误:
try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("获取会话失败:", (error as Error).message)
}
API 列表 (API Reference)
1. Global
| 方法 | 描述 | 响应 |
|---|---|---|
global.health() | 检查服务器健康状态和版本 | { healthy: true, version: string } |
示例:
const health = await client.global.health()
console.log(health.data.version)
2. App
| 方法 | 描述 | 响应 |
|---|---|---|
app.log() | 写入日志条目 | boolean |
app.agents() | 列出所有可用代理 | Agent[] |
示例:
// 写入日志条目
await client.app.log({
body: {
service: "my-app",
level: "info",
message: "操作完成",
},
})
// 列出可用代理
const agents = await client.app.agents()
3. Project
| 方法 | 描述 | 响应 |
|---|---|---|
project.list() | 列出所有项目 | Project[] |
project.current() | 获取当前项目 | Project |
示例:
// 列出所有项目
const projects = await client.project.list()
// 获取当前项目
const currentProject = await client.project.current()
4. Path
| 方法 | 描述 | 响应 |
|---|---|---|
path.get() | 获取当前路径 | Path |
示例:
// 获取当前路径信息
const pathInfo = await client.path.get()
5. Config
| 方法 | 描述 | 响应 |
|---|---|---|
config.get() | 获取配置信息 | Config |
config.providers() | 列出提供商和默认模型 | { providers: Provider[], default: { [key: string]: string } } |
示例:
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()
6. Sessions (会话管理)
| 方法 | 描述 | 说明 |
|---|---|---|
session.list() | 列出会话 | 返回 Session[] |
session.get({ path }) | 获取会话 | 返回 Session |
session.children({ path }) | 列出子会话 | 返回 Session[] |
session.create({ body }) | 创建会话 | 返回 Session |
session.delete({ path }) | 删除会话 | 返回 boolean |
session.update({ path, body }) | 更新会话属性 | 返回 Session |
session.init({ path, body }) | 分析应用并创建 AGENTS.md | 返回 boolean |
session.abort({ path }) | 中止运行中的会话 | 返回 boolean |
session.share({ path }) | 共享会话 | 返回 Session |
session.unshare({ path }) | 取消共享会话 | 返回 Session |
session.summarize({ path, body }) | 总结会话 | 返回 boolean |
session.messages({ path }) | 列出会话中的消息 | 返回 { info: Message, parts: Part[] }[] |
session.message({ path }) | 获取消息详情 | 返回 { info: Message, parts: Part[] } |
session.prompt({ path, body }) | 发送提示消息 | body.noReply: true 返回 UserMessage(仅上下文);默认返回带 AI 响应的 AssistantMessage |
session.command({ path, body }) | 向会话发送命令 | 返回 { info: AssistantMessage, parts: Part[] } |
session.shell({ path, body }) | 运行 shell 命令 | 返回 AssistantMessage |
session.revert({ path, body }) | 撤销消息 | 返回 Session |
session.unrevert({ path }) | 恢复已撤销消息 | 返回 Session |
postSessionByIdPermissionsByPermissionId({ path, body }) | 响应权限请求 | 返回 boolean |
示例:
// 创建和管理会话
const session = await client.session.create({
body: { title: "我的会话" },
})
const sessions = await client.session.list()
// 发送提示消息
const result = await client.session.prompt({
path: { id: session.id },
body: {
model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" },
parts: [{ type: "text", text: "你好!" }],
},
})
// 注入上下文但不触发 AI 响应(对插件有用)
await client.session.prompt({
path: { id: session.id },
body: {
noReply: true,
parts: [{ type: "text", text: "你是一个有帮助的助手。" }],
},
})
7. Files (文件操作)
| 方法 | 描述 | 响应 |
|---|---|---|
find.text({ query }) | 在文件中搜索文本 | 匹配对象数组,包含 path、lines、line_number、absolute_offset、submatches |
find.files({ query }) | 按名称查找文件和目录 | string[](路径数组) |
find.symbols({ query }) | 查找工作区符号 | Symbol[] |
file.read({ query }) | 读取文件 | { type: "raw" | "patch", content: string } |
file.status({ query? }) | 获取跟踪文件的状态 | File[] |
find.files 支持的可选查询字段:type:"file"或"directory"directory:覆盖搜索的项目根目录limit:最大结果数(1–200)
示例:
// 搜索和读取文件
const textResults = await client.find.text({
query: { pattern: "function.*opencode" },
})
const files = await client.find.files({
query: { query: "*.ts", type: "file" },
})
const directories = await client.find.files({
query: { query: "packages", type: "directory", limit: 20 },
})
const content = await client.file.read({
query: { path: "src/index.ts" },
})
8. TUI (界面控制)
| 方法 | 描述 | 响应 |
|---|---|---|
tui.appendPrompt({ body }) | 向提示框追加文本 | boolean |
tui.openHelp() | 打开帮助对话框 | boolean |
tui.openSessions() | 打开会话选择器 | boolean |
tui.openThemes() | 打开主题选择器 | boolean |
tui.openModels() | 打开模型选择器 | boolean |
tui.submitPrompt() | 提交当前提示 | boolean |
tui.clearPrompt() | 清空提示 | boolean |
tui.executeCommand({ body }) | 执行命令 | boolean |
tui.showToast({ body }) | 显示提示通知 | boolean |
示例:
// 控制 TUI 界面
await client.tui.appendPrompt({
body: { text: "添加到提示框" },
})
await client.tui.showToast({
body: { message: "任务完成", variant: "success" },
})
9. Auth (身份验证)
| 方法 | 描述 | 响应 |
|---|---|---|
auth.set({ ... }) | 设置身份验证凭据 | boolean |
示例:
await client.auth.set({
path: { id: "anthropic" },
body: { type: "api", key: "你的 API 密钥" },
})
10. Events (实时事件)
| 方法 | 描述 | 响应 |
|---|---|---|
event.subscribe() | 服务器发送事件流 | 服务器发送事件流 |
示例:
// 监听实时事件
const events = await client.event.subscribe()
for await (const event of events.stream) {
console.log("事件:", event.type, event.properties)
}