SDK Client
用于 opencode 服务器的类型安全 JS 客户端。
opencode JS/TS SDK 提供了一个用于与服务器交互的类型安全客户端。 使用它来构建集成并以编程方式控制 opencode。
了解更多 关于服务器如何工作的信息。有关示例,请查看社区构建的 项目。
安装 Install
从 npm 安装 SDK:
npm install @opencode-ai/sdk创建客户端 Create client
创建一个 opencode 实例:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()这将同时启动服务器和客户端
选项 Options
| 选项 Option | 类型 Type | 描述 Description | 默认值 Default |
|---|---|---|---|
hostname | string | 服务器主机名 | 127.0.0.1 |
port | number | 服务器端口 | 4096 |
signal | AbortSignal | 用于取消的中止信号 | undefined |
timeout | number | 服务器启动超时(毫秒) | 5000 |
config | 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()仅客户端 Client only
如果你已经有一个正在运行的 opencode 实例,你可以创建一个客户端实例来连接它:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({ baseUrl: "http://localhost:4096",})选项 Options
| 选项 Option | 类型 Type | 描述 Description | 默认值 Default |
|---|---|---|---|
baseUrl | string | 服务器的 URL | http://localhost:4096 |
fetch | function | 自定义 fetch 实现 | globalThis.fetch |
parseAs | string | 响应解析方法 | auto |
responseStyle | string | 返回样式: data 或 fields | fields |
throwOnError | boolean | 抛出错误而不是返回 | false |
类型 Types
SDK 包含所有 API 类型的 TypeScript 定义。直接导入它们:
import type { Session, Message, Part } from "@opencode-ai/sdk"所有类型都是从服务器的 OpenAPI 规范生成的,可以在 类型文件 中找到。
错误 Errors
SDK 可能会抛出你可以捕获并处理的错误:
try { await client.session.get({ path: { id: "invalid-id" } })} catch (error) { console.error("Failed to get session:", (error as Error).message)}API APIs
SDK 通过类型安全的客户端公开所有服务器 API。
Global (全局)
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
global.health() | 检查服务器健康状况和版本 | { healthy: true, version: string } |
示例 Examples
const health = await client.global.health()console.log(health.data.version)App (应用)
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
app.log() | 写入日志条目 | boolean |
app.agents() | 列出所有可用智能体 | Agent[] |
示例 Examples
// Write a log entryawait client.app.log({ body: { service: "my-app", level: "info", message: "Operation completed", },})
// List available agentsconst agents = await client.app.agents()Project (项目)
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
project.list() | 列出所有项目 | Project[] |
project.current() | 获取当前项目 | Project |
示例 Examples
// List all projectsconst projects = await client.project.list()
// Get current projectconst currentProject = await client.project.current()Path (路径)
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
path.get() | 获取当前路径 | Path |
示例 Examples
// Get current path informationconst pathInfo = await client.path.get()Config (配置)
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
config.get() | 获取配置信息 | Config |
config.providers() | 列出提供商和默认模型 | { providers: Provider[], default: { [key: string]: string } } |
示例 Examples
const config = await client.config.get()
const { providers, default: defaults } = await client.config.providers()Sessions (会话)
| 方法 Method | 描述 Description | 备注 Notes |
|---|---|---|
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 |
示例 Examples
// Create and manage sessionsconst session = await client.session.create({ body: { title: "My session" },})
const sessions = await client.session.list()
// Send a prompt messageconst result = await client.session.prompt({ path: { id: session.id }, body: { model: { providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" }, parts: [{ type: "text", text: "Hello!" }], },})
// Inject context without triggering AI response (useful for plugins)await client.session.prompt({ path: { id: session.id }, body: { noReply: true, parts: [{ type: "text", text: "You are a helpful assistant." }], },})Files (文件)
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
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)
示例 Examples
// Search and read filesconst 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
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
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 |
示例 Examples
// Control TUI interfaceawait client.tui.appendPrompt({ body: { text: "Add this to prompt" },})
await client.tui.showToast({ body: { message: "Task completed", variant: "success" },})Auth (认证)
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
auth.set({ ... }) | 设置认证凭据 | boolean |
示例 Examples
await client.auth.set({ path: { id: "anthropic" }, body: { type: "api", key: "your-api-key" },})Events (事件)
| 方法 Method | 描述 Description | 响应 Response |
|---|---|---|
event.subscribe() | 服务器发送事件流 | Server-sent events stream |
示例 Examples
// Listen to real-time eventsconst events = await client.event.subscribe()for await (const event of events.stream) { console.log("Event:", event.type, event.properties)}