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 和一個客戶端

選項

OptionTypeDescriptionDefault
hostnamestringServer 主機名127.0.0.1
portnumberServer 埠4096
signalAbortSignal用於取消的 abort signalundefined
timeoutnumberServer 啟動逾時(毫秒)5000
configConfig設定物件{}

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",
})

選項

OptionTypeDescriptionDefault
baseUrlstringServer 的 URLhttp://localhost:4096
fetchfunction自定義的 fetch 實作globalThis.fetch
parseAsstring回應解析方式auto
responseStylestring返回風格:data 或 fieldsfields
throwOnErrorboolean丟擲錯誤而不是返回值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"] }

輸出格式型別

TypeDescription
text預設值。標準的文字回應(無結構化輸出)
json_schema返回與你提供的 schema 一致、經過驗證的 JSON

JSON Schema Format

當使用 type: 'json_schema' 時,需要提供:

FieldTypeDescription
type'json_schema'必填。指定 JSON schema 模式
schemaobject必填。用於定義輸出結構的 JSON Schema 物件
retryCountnumber可選。驗證重試次數(預設為 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)
}

最佳實踐

  1. 在 schema 屬性中提供清晰的描述,以幫助模型理解需要提取哪些資料
  2. 使用 required 來指定必須存在的欄位
  3. 保持 schema 的聚焦——複雜的巢狀 schema 可能更難被模型正確填充
  4. 設定合適的 retryCount——複雜的 schema 可以調大,簡單的可以調小

APIs

SDK 透過一個型別安全的客戶端暴露了所有的 server API。


Global

MethodDescriptionResponse
global.health()檢查 server 的健康狀態和版本{ healthy: true, version: string }

Examples

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

App

MethodDescriptionResponse
app.log()寫入一條日誌boolean
app.agents()列出所有可用的 agentsAgent[]

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

MethodDescriptionResponse
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

MethodDescriptionResponse
path.get()取得當前路徑Path

Examples

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

Config

MethodDescriptionResponse
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

MethodDescriptionNotes
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

MethodDescriptionResponse
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

MethodDescriptionResponse
tui.appendPrompt({ body })追加文字到 promptboolean
tui.openHelp()開啟說明對話方塊boolean
tui.openSessions()開啟 session 選擇器boolean
tui.openThemes()開啟主題選擇器boolean
tui.openModels()開啟模型選擇器boolean
tui.submitPrompt()提交當前 promptboolean
tui.clearPrompt()清除 promptboolean
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

MethodDescriptionResponse
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)
}