SDK
OpenCode 伺服器的型別安全 JavaScript/TypeScript 客戶端。安裝 SDK、建立客戶端、呼叫工作階段/檔案/TUI API 和結構化輸出支援。
本頁內文若連結到尚未提供繁體版本的頁面(例如 /ecosystem/plugins/、/news/),會開啟英文原頁;導覽與頁尾標有 EN 的項目即為這類頁面。
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: "<provider>/<model>",
},
})
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 |
型別
SDK 包含所有 API 型別的 TypeScript 定義。可以直接匯入:
import type { Session, Message, Part } from "@opencode-ai/sdk"
所有型別都根據 server 的 OpenAPI 規範自動生成,詳見 types file。
錯誤
SDK 可能丟擲錯誤,你可以捕獲並處理它們:
try {
await client.session.get({ path: { id: "invalid-id" } })
} catch (error) {
console.error("Failed to get session:", (error as Error).message)
}
結構化輸出
你可以透過指定一個帶有 JSON schema 的 format 來向模型請求結構化的 JSON 輸出。模型會使用 StructuredOutput 工具來返回與你提供的 schema 一致、經過驗證的 JSON。
基本用法
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"] }
輸出格式型別
| 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) |
錯誤處理
如果模型在所有重試之後仍無法生成有效的結構化輸出,回應中將包含一個 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)
}
最佳實踐
- 在 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() | 列出工作階段 | 返回 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 }) | 列出工作階段中的 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 }) | 向工作階段傳送 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: "<model>" },
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
| 方法 | 描述 | 回應 |
|---|---|---|
event.subscribe() | 伺服器傳送事件(SSE)流 | 伺服器傳送事件(SSE)流 |
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)
}