~/content/sdk

SDK

用于 opencode 服务器的类型安全的 JS 客户端。

last_updated: "2026-01-20"

opencode JS/TS SDK 提供了一个类型安全的客户端,用于与服务器交互。 使用它可以构建集成并以编程方式控制 opencode。

了解更多关于服务器如何工作的信息。有关示例,请查看社区构建的项目。


安装

从 npm 安装 SDK:

bash
npm install @opencode-ai/sdk

创建客户端

创建 opencode 的一个实例:

bash
const { client } = await createOpencode()

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

选项

OptionTypeDescriptionDefault
hostnamestringServer hostname127.0.0.1
portnumberServer port4096
signalAbortSignalAbort signal for cancellationundefined
timeoutnumberTimeout in ms for server start5000
configConfigConfiguration object{}

配置

您可以传递一个配置对象来自定义行为。该实例仍然会获取您的 opencode.json,但您可以覆盖或以内联方式添加配置:

bash
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 实例,您可以创建一个客户端实例来连接到它:

bash
const client = createOpencodeClient({
  baseUrl: "http://localhost:4096",
})

选项

OptionTypeDescriptionDefault
baseUrlstringURL of the serverhttp://localhost:4096
fetchfunctionCustom fetch implementationglobalThis.fetch
parseAsstringResponse parsing methodauto
responseStylestringReturn style: data or fieldsfields
throwOnErrorbooleanThrow errors instead of returnfalse

类型

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

bash

所有类型都从服务器的 OpenAPI 规范生成,并且可以在 types file 中找到。


错误

SDK 可能会抛出您可以捕获和处理的错误:

bash
try {
  await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
  console.error("Failed to get session:", (error as Error).message)
}

APIs

SDK 通过类型安全的客户端公开所有服务器 API。


Global

MethodDescriptionResponse
global.health()Check server health and version{ healthy: true, version: string }

Examples

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

App

MethodDescriptionResponse
app.log()Write a log entryboolean
app.agents()List all available agentsAgent[]

Examples

bash
// 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

MethodDescriptionResponse
project.list()List all projectsProject[]
project.current()Get current projectProject

Examples

bash
// List all projects
const projects = await client.project.list()

// Get current project
const currentProject = await client.project.current()

Path

MethodDescriptionResponse
path.get()Get current pathPath

Examples

bash
// Get current path information
const pathInfo = await client.path.get()

Config

MethodDescriptionResponse
config.get()Get config infoConfig
config.providers()List providers and default models{ providers: Provider[], default: { [key: string]: string } }

Examples

bash
const 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 (仅上下文)。默认返回 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

示例

bash
// 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." }],
  },
})

文件

方法描述响应
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)

示例

bash
// 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

方法描述响应
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

示例

bash
// Control TUI interface
await client.tui.appendPrompt({
  body: { text: "Add this to prompt" },
})

await client.tui.showToast({
  body: { message: "Task completed", variant: "success" },
})

Auth

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

示例

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

Events

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

示例

bash
// 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)
}
Comments (Coming Soon)

Configure Giscus in environment variables to enable comments.