SDK
用于 opencode 服务器的类型安全 JS 客户端。
opencode JS/TS SDK 提供了一个类型安全的客户端,用于与服务器交互。 您可以使用它来构建集成并通过编程方式控制 opencode。
了解更多 关于服务器的工作原理。如需查看示例,请查看社区构建的项目。
安装
从 npm 安装 SDK:
npm install @opencode-ai/sdk创建客户端
创建 opencode 的实例:
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 | 配置对象 | {} |
配置
您可以传递一个配置对象来自定义行为。实例仍然会读取您的 opencode.json,但您可以内联覆盖或添加配置:
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()仅客户端
如果您已经有一个正在运行的 opencode 实例,您可以创建一个客户端实例来连接到它:
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 |
类型
SDK 包含了所有 API 类型的 TypeScript 定义。可以直接导入:
import type { Session, Message, Part } from "@opencode-ai/sdk"所有类型都从服务器的 OpenAPI 规范生成,可在类型文件中找到。
错误
SDK 可能会抛出错误,你可以捕获并处理:
try { await client.session.get({ path: { id: "invalid-id" } })} catch (error) { console.error("Failed to get session:", (error as Error).message)}API
SDK 通过一个类型安全的客户端暴露所有服务器 API。
全局
| 方法 | 描述 | 响应 |
|---|---|---|
global.health() | 检查服务器健康和版本 | { healthy: true, version: string } |
示例
const health = await client.global.health()console.log(health.data.version)应用
| 方法 | 描述 | 响应 |
|---|---|---|
app.log() | 写入日志条目 | boolean |
app.agents() | 列出所有可用代理 | Agent[] |
示例
// 写入日志条目await client.app.log({ body: { service: "my-app", level: "info", message: "操作已完成", },})
// 列出可用代理const agents = await client.app.agents()项目
| 方法 | 描述 | 响应 |
|---|---|---|
project.list() | 列出所有项目 | Project[] |
project.current() | 获取当前项目 | Project |
示例
// 列出所有项目const projects = await client.project.list()
// 获取当前项目const currentProject = await client.project.current()路径
| 方法 | 描述 | 响应 |
|---|---|---|
path.get() | 获取当前路径 | Path |
示例
// 获取当前路径信息const pathInfo = await client.path.get()配置
| 方法 | 描述 | 响应 |
|---|---|---|
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()会话
| 方法 | 描述 | 备注 |
|---|---|---|
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(仅上下文)。默认返回 AssistantMessage 并附带 AI 响应 |
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: "My session" },})
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: "Hello!" }], },})
// 注入上下文而不触发 AI 响应(适用于插件)await client.session.prompt({ path: { id: session.id }, body: { noReply: true, parts: [{ type: "text", text: "You are a helpful assistant." }], },})文件
| 方法 | 描述 | 响应 |
|---|---|---|
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" },})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 }) | 显示 toast 通知 | boolean |
示例
// 控制 TUI 界面await client.tui.appendPrompt({ body: { text: "Add this to prompt" },})
await client.tui.showToast({ body: { message: "Task completed", variant: "success" },})认证
| 方法 | 描述 | 响应 |
|---|---|---|
auth.set({ ... }) | 设置认证凭据 | boolean |
示例
await client.auth.set({ path: { id: "anthropic" }, body: { type: "api", key: "your-api-key" },})事件
| 方法 | 描述 | 响应 |
|---|---|---|
event.subscribe() | 服务器发送事件流 | 服务器发送事件流 |
示例
// 监听实时事件const events = await client.event.subscribe()for await (const event of events.stream) { console.log("Event:", event.type, event.properties)}