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

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

选项

| Option | Type | Description | Default | | ---------- | ------------- | ------------------------------ | ----------- | | hostname | string | Server hostname | 127.0.0.1 | | port | number | Server port | 4096 | | signal | AbortSignal | Abort signal for cancellation | undefined | | timeout | number | Timeout in ms for server start | 5000 | | config | Config | Configuration 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",
})

选项

| Option | Type | Description | Default | | --------------- | ---------- | -------------------------------- | ----------------------- | | baseUrl | string | URL of the server | http://localhost:4096 | | fetch | function | Custom fetch implementation | globalThis.fetch | | parseAs | string | Response parsing method | auto | | responseStyle | string | Return style: data or fields | fields | | throwOnError | boolean | Throw errors instead of return | false |


##类型

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

| Method | Description | Response | | ----------------- | ------------------------------- | ------------------------------------ | | 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

| Method | Description | Response | | -------------- | ------------------------- | ------------------------------------------- | | app.log() | Write a log entry | boolean | | app.agents() | List all available agents | Agent[] |


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

| Method | Description | Response | | ------------------- | ------------------- | --------------------------------------------- | | project.list() | List all projects | Project[] | | project.current() | Get current project | Project |


Examples

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

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

###Path

| Method | Description | Response | | ------------ | ---------------- | ---------------------------------------- | | path.get() | Get current path | Path |


Examples

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

###Config

| Method | Description | Response | | -------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------- | | config.get() | Get config info | Config | | 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.