SDK
opencode 服务器的类型安全 JS 客户端。
opencode JS/TS SDK 提供了一个类型安全的客户端,用于与服务器交互。使用它来构建集成并以编程方式控制 opencode。
了解更多关于服务器如何工作。有关示例,请查看社区构建的项目。
# 安装#
从 npm 安装 SDK:
bashnpm install @opencode-ai/sdk
# 创建客户端#
创建一个 opencode 实例:
typescriptimport { 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,但你可以内联覆盖或添加配置:
typescript1import { createOpencode } from "@opencode-ai/sdk" 2 3const opencode = await createOpencode({ 4 hostname: "127.0.0.1", 5 port: 4096, 6 config: { 7 model: "anthropic/claude-3-5-sonnet-20241022", 8 }, 9}) 10 11console.log(`Server running at ${opencode.server.url}`) 12 13opencode.server.close()
# 仅客户端#
如果你已经有一个正在运行的 opencode 实例,你可以创建一个客户端实例来连接它:
typescript1import { createOpencodeClient } from "@opencode-ai/sdk" 2 3const client = createOpencodeClient({ 4 baseUrl: "http://localhost:4096", 5})
## 选项#
| 选项 | 类型 | 描述 | 默认值 |
|---|---|---|---|
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 定义。直接导入它们:
typescriptimport type { Session, Message, Part } from "@opencode-ai/sdk"
所有类型都是从服务器的 OpenAPI 规范生成的,可在类型文件↗中找到。
# 错误#
SDK 可能会抛出你可以捕获和处理的错误:
typescript1try { 2 await client.session.get({ path: { id: "invalid-id" } }) 3} catch (error) { 4 console.error("Failed to get session:", (error as Error).message) 5}
# API#
SDK 通过类型安全的客户端暴露所有服务器 API。
## Global#
| 方法 | 描述 | 响应 |
|---|---|---|
global.health() | 检查服务器健康状态和版本 | { healthy: true, version: string } |
示例
typescriptconst health = await client.global.health() console.log(health.data.version)
## App#
| 方法 | 描述 | 响应 |
|---|---|---|
app.log() | 写入日志条目 | boolean |
app.agents() | 列出所有可用代理 | Agent[]↗ |
示例
typescript1// 写入日志条目 2await client.app.log({ 3 body: { 4 service: "my-app", 5 level: "info", 6 message: "Operation completed", 7 }, 8}) 9 10// 列出可用代理 11const agents = await client.app.agents()
## Project#
| 方法 | 描述 | 响应 |
|---|---|---|
project.list() | 列出所有项目 | Project[]↗ |
project.current() | 获取当前项目 | Project↗ |
示例
typescript1// 列出所有项目 2const projects = await client.project.list() 3 4// 获取当前项目 5const currentProject = await client.project.current()
## Path#
| 方法 | 描述 | 响应 |
|---|---|---|
path.get() | 获取当前路径 | Path↗ |
示例
typescript// 获取当前路径信息 const pathInfo = await client.path.get()
## Config#
| 方法 | 描述 | 响应 |
|---|---|---|
config.get() | 获取配置信息 | Config↗ |
config.providers() | 列出提供商和默认模型 | { providers: Provider[], default: { [key: string]: string } } |
示例
typescriptconst config = await client.config.get() const { providers, default: defaults } = await client.config.providers()
## 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 |
示例
typescript1// 创建和管理会话 2const session = await client.session.create({ 3 body: { title: "My session" }, 4}) 5 6const sessions = await client.session.list() 7 8// 发送提示消息 9const result = await client.session.prompt({ 10 path: { id: session.id }, 11 body: { 12 model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, 13 parts: [{ type: "text", text: "Hello!" }], 14 }, 15}) 16 17// 注入上下文而不触发 AI 响应(对插件有用) 18await client.session.prompt({ 19 path: { id: session.id }, 20 body: { 21 noReply: true, 22 parts: [{ type: "text", text: "You are a helpful assistant." }], 23 }, 24})
## 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)
示例
typescript1// 搜索和读取文件 2const textResults = await client.find.text({ 3 query: { pattern: "function.*opencode" }, 4}) 5 6const files = await client.find.files({ 7 query: { query: "*.ts", type: "file" }, 8}) 9 10const directories = await client.find.files({ 11 query: { query: "packages", type: "directory", limit: 20 }, 12}) 13 14const content = await client.file.read({ 15 query: { path: "src/index.ts" }, 16})
## 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 |
示例
typescript1// 控制 TUI 界面 2await client.tui.appendPrompt({ 3 body: { text: "Add this to prompt" }, 4}) 5 6await client.tui.showToast({ 7 body: { message: "Task completed", variant: "success" }, 8})
## Auth#
| 方法 | 描述 | 响应 |
|---|---|---|
auth.set({ ... }) | 设置认证凭证 | boolean |
示例
typescript1await client.auth.set({ 2 path: { id: "anthropic" }, 3 body: { type: "api", key: "your-api-key" }, 4})
## Events#
| 方法 | 描述 | 响应 |
|---|---|---|
event.subscribe() | 服务器发送事件流 | 服务器发送事件流 |
示例
typescript1// 监听实时事件 2const events = await client.event.subscribe() 3for await (const event of events.stream) { 4 console.log("Event:", event.type, event.properties) 5}