中文
文档
SDK

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()

这会同时启动服务器和客户端。

选项

选项类型描述默认值
hostnamestring服务器主机名127.0.0.1
portnumber服务器端口4096
signalAbortSignal用于取消的中止信号undefined
timeoutnumber服务器启动超时时间(毫秒)5000
configConfig配置对象{}

配置

你可以传递配置对象来自定义行为。实例仍会读取你的 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",
})

选项

选项类型描述默认值
baseUrlstring服务器 URLhttp://localhost:4096
fetchfunction自定义 fetch 实现globalThis.fetch
parseAsstring响应解析方法auto
responseStylestring返回风格:datafieldsfields
throwOnErrorboolean抛出错误而不是返回false

类型

SDK 包含所有 API 类型的 TypeScript 定义。直接导入它们:

import type { Session, Message, Part } from "@opencode-ai/sdk"

所有类型都是从服务器的 OpenAPI 规范生成的,可在类型文件 (opens in a new tab)中查看。


错误

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

方法描述响应
global.health()检查服务器健康状态和版本{ healthy: true, version: string }

示例

const health = await client.global.health()
console.log(health.data.version)

App

方法描述响应
app.log()写入日志条目boolean
app.agents()列出所有可用的代理Agent[] (opens in a new tab)

示例

// 写入日志条目
await client.app.log({
  body: {
    service: "my-app",
    level: "info",
    message: "Operation completed",
  },
})
 
// 列出可用的代理
const agents = await client.app.agents()

Project

方法描述响应
project.list()列出所有项目Project[] (opens in a new tab)
project.current()获取当前项目Project (opens in a new tab)

示例

// 列出所有项目
const projects = await client.project.list()
 
// 获取当前项目
const currentProject = await client.project.current()

Path

方法描述响应
path.get()获取当前路径Path (opens in a new tab)

示例

// 获取当前路径信息
const pathInfo = await client.path.get()

Config

方法描述响应
config.get()获取配置信息Config (opens in a new tab)
config.providers()列出提供商和默认模型{ providers: Provider[] (opens in a new tab), default: { [key: string]: string } }

示例

const config = await client.config.get()
 
const { providers, default: defaults } = await client.config.providers()

Sessions

方法描述备注
session.list()列出会话返回 Session[] (opens in a new tab)
session.get({ path })获取会话返回 Session (opens in a new tab)
session.children({ path })列出子会话返回 Session[] (opens in a new tab)
session.create({ body })创建会话返回 Session (opens in a new tab)
session.delete({ path })删除会话返回 boolean
session.update({ path, body })更新会话属性返回 Session (opens in a new tab)
session.init({ path, body })分析应用并创建 AGENTS.md返回 boolean
session.abort({ path })中止运行中的会话返回 boolean
session.share({ path })分享会话返回 Session (opens in a new tab)
session.unshare({ path })取消分享会话返回 Session (opens in a new tab)
session.summarize({ path, body })总结会话返回 boolean
session.messages({ path })列出会话中的消息返回 { info: Message (opens in a new tab), parts: Part[] (opens in a new tab)}[]
session.message({ path })获取消息详情返回 { info: Message (opens in a new tab), parts: Part[] (opens in a new tab)}
session.prompt({ path, body })发送提示消息body.noReply: true 返回 UserMessage(仅上下文)。默认返回带有 AI 响应的 AssistantMessage (opens in a new tab)
session.command({ path, body })向会话发送命令返回 { info: AssistantMessage (opens in a new tab), parts: Part[] (opens in a new tab)}
session.shell({ path, body })运行 shell 命令返回 AssistantMessage (opens in a new tab)
session.revert({ path, body })撤销消息返回 Session (opens in a new tab)
session.unrevert({ path })恢复已撤销的消息返回 Session (opens in a new tab)
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." }],
  },
})

Files

方法描述响应
find.text({ query })在文件中搜索文本包含 pathlinesline_numberabsolute_offsetsubmatches 的匹配对象数组
find.files({ query })按名称查找文件和目录string[](路径)
find.symbols({ query })查找工作区符号Symbol[] (opens in a new tab)
file.read({ query })读取文件{ type: "raw" | "patch", content: string }
file.status({ query? })获取已跟踪文件的状态File[] (opens in a new tab)

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

方法描述响应
auth.set({ ... })设置认证凭据boolean

示例

await client.auth.set({
  path: { id: "anthropic" },
  body: { type: "api", key: "your-api-key" },
})

Events

方法描述响应
event.subscribe()服务器发送事件流服务器发送事件流

示例

// 监听实时事件
const events = await client.event.subscribe()
for await (const event of events.stream) {
  console.log("Event:", event.type, event.properties)
}