SDK
opencode JS/TS SDK 提供了一个类型安全的客户端,用于与 server 交互。 你可以使用它来构建集成并以编程方式控制 opencode。
了解更多关于 server 的工作机制。示例请参阅社区构建的项目。
安装
从 npm 安装 SDK:
npm install @opencode-ai/sdk
创建客户端
创建一个 opencode 实例:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()
这会同时启动一个 server 和一个客户端
选项
| Option | Type | Description | Default |
|---|---|---|---|
hostname | string | Server 主机名 | 127.0.0.1 |
port | number | Server 端口 | 4096 |
signal | AbortSignal | 用于取消的 abort signal | undefined |
timeout | number | Server 启动超时(毫秒) | 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()
仅客户端
如果你已经有一个正在运行的 opencode 实例,可以创建一个 client 实例来连接它:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({
baseUrl: "http://localhost:4096",
})
选项
| Option | Type | Description | Default |
|---|---|---|---|
baseUrl | string | Server 的 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"
所有类型都根据 server 的 OpenAPI 规范自动生成,详见 types file。
Errors
SDK 可能抛出错误,你可以捕获并处理它们:
try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("Failed to get session:", (error as Error).message)
}
Structured Output
你可以通过指定一个带有 JSON schema 的 format 来向模型请求结构化的 JSON 输出。模型会使用 StructuredOutput 工具来返回与你提供的 schema 一致、经过校验的 JSON。
Basic Usage
const result = await client.session.prompt({
path: { id: sessionId },
body: {
parts: [{ type: "text", text: "Research Anthropic and provide company info" }],
format: {
type: "json_schema",
schema: {
type: "object",
properties: {
company: { type: "string", description: "Company name" },
founded: { type: "number", description: "Year founded" },
products: {
type: "array",
items: { type: "string" },
description: "Main products",
},
},
required: ["company", "founded"],
},
},
},
})
// Access the structured output
console.log(result.data.info.structured_output)
// { company: "Anthropic", founded: 2021, products: ["Claude", "Claude API"] }
Output Format Types
| Type | Description |
|---|---|
text | 默认值。标准的文本响应(无结构化输出) |
json_schema | 返回与你提供的 schema 一致、经过校验的 JSON |
JSON Schema Format
当使用 type: 'json_schema' 时,需要提供:
| Field | Type | Description |
|---|---|---|
type | 'json_schema' | 必填。指定 JSON schema 模式 |
schema | object | 必填。用于定义输出结构的 JSON Schema 对象 |
retryCount | number | 可选。验证重试次数(默认为 2) |
Error Handling
如果模型在所有重试之后仍无法生成有效的结构化输出,响应中将包含一个 StructuredOutputError:
if (result.data.info.error?.name === "StructuredOutputError") {
console.error("Failed to produce structured output:", result.data.info.error.message)
console.error("Attempts:", result.data.info.error.retries)
}
Best Practices
- 在 schema 属性中提供清晰的描述,以帮助模型理解需要提取哪些数据
- 使用
required来指定必须存在的字段 - 保持 schema 的聚焦——复杂的嵌套 schema 可能更难被模型正确填充
- 设置合适的
retryCount——复杂的 schema 可以调大,简单的可以调小
APIs
SDK 通过一个类型安全的客户端暴露了所有的 server API。
Global
| Method | Description | Response |
|---|---|---|
global.health() | 检查 server 的健康状态和版本 | { 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() | 列出所有可用的 agents | Agent[] |
Examples
// Write a log entry
await client.app.log({
body: {
service: "my-app",
level: "info",
message: "Operation completed",
},
})
// List available agents
const agents = await client.app.agents()
Project
| Method | Description | Response |
|---|---|---|
project.list() | 列出所有项目 | Project[] |
project.current() | 获取当前项目 | Project |
Examples
// List all projects
const projects = await client.project.list()
// Get current project
const currentProject = await client.project.current()
Path
| Method | Description | Response |
|---|---|---|
path.get() | 获取当前路径 | Path |
Examples
// Get current path information
const pathInfo = await client.path.get()
Config
| Method | Description | Response |
|---|---|---|
config.get() | 获取配置信息 | Config |
config.providers() | 列出 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() | 列出 sessions | 返回 Session[] |
session.get({ path }) | 获取 session | 返回 Session |
session.children({ path }) | 列出子 sessions | 返回 Session[] |
session.create({ body }) | 创建 session | 返回 Session |
session.delete({ path }) | 删除 session | 返回 boolean |
session.update({ path, body }) | 更新 session 属性 | 返回 Session |
session.init({ path, body }) | 分析应用并创建 AGENTS.md | 返回 boolean |
session.abort({ path }) | 中止正在运行的 session | 返回 boolean |
session.share({ path }) | 分享 session | 返回 Session |
session.unshare({ path }) | 取消分享 session | 返回 Session |
session.summarize({ path, body }) | 摘要 session | 返回 boolean |
session.messages({ path }) | 列出会话中的 messages | 返回 { info: Message, parts: Part[] }[] |
session.message({ path }) | 获取 message 详情 | 返回 { info: Message, parts: Part[] } |
session.prompt({ path, body }) | 发送 prompt 消息 | body.noReply: true 返回 UserMessage(仅作为上下文)。默认返回带有 AI 响应的 AssistantMessage。支持 body.outputFormat 用于 structured output |
session.command({ path, body }) | 向 session 发送 command | 返回 { info: AssistantMessage, parts: Part[] } |
session.shell({ path, body }) | 运行 shell 命令 | 返回 AssistantMessage |
session.revert({ path, body }) | 回滚一条 message | 返回 Session |
session.unrevert({ path }) | 恢复已回滚的 messages | 返回 Session |
postSessionByIdPermissionsByPermissionId({ path, body }) | 响应一个权限请求 | 返回 boolean |
Examples
// Create and manage sessions
const session = await client.session.create({
body: { title: "My session" },
})
const sessions = await client.session.list()
// Send a prompt message
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!" }],
},
})
// 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 支持一些可选的 query 字段:
type:"file"或"directory"directory:覆盖搜索的项目根目录limit:最大结果数(1–200)
Examples
// Search and read files
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
| Method | Description | Response |
|---|---|---|
tui.appendPrompt({ body }) | 追加文本到 prompt | boolean |
tui.openHelp() | 打开帮助对话框 | boolean |
tui.openSessions() | 打开 session 选择器 | boolean |
tui.openThemes() | 打开主题选择器 | boolean |
tui.openModels() | 打开模型选择器 | boolean |
tui.submitPrompt() | 提交当前 prompt | boolean |
tui.clearPrompt() | 清除 prompt | boolean |
tui.executeCommand({ body }) | 执行一条命令 | boolean |
tui.showToast({ body }) | 显示 toast 通知 | boolean |
Examples
// Control TUI interface
await 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 | Server-sent events stream |
Examples
// Listen to real-time events
const events = await client.event.subscribe()
for await (const event of events.stream) {
console.log("Event:", event.type, event.properties)
}