--- title: SDK description: opencode 伺服器的型別安全 JS 用戶端。 --- import config from "../../../../config.mjs" export const typesUrl = `${config.github}/blob/dev/packages/sdk/js/src/gen/types.gen.ts` opencode JS/TS SDK 提供了一個型別安全的用戶端,用於與伺服器進行互動。 您可以用它來建構整合方案,並以程式化方式控制 opencode。 [了解更多](/docs/server)關於伺服器的運作原理。如需範例,請查看社群建構的[專案](/docs/ecosystem#projects)。 --- ## 安裝 從 npm 安裝 SDK: ```bash npm install @opencode-ai/sdk ``` --- ## 建立用戶端 建立一個 opencode 實例: ```javascript import { createOpencode } from "@opencode-ai/sdk" const { client } = await createOpencode() ``` 這會同時啟動伺服器和用戶端。 #### 選項 | 選項 | 型別 | 描述 | 預設值 | | ---------- | ------------- | -------------------------- | ----------- | | `hostname` | `string` | 伺服器主機名稱 | `127.0.0.1` | | `port` | `number` | 伺服器連接埠 | `4096` | | `signal` | `AbortSignal` | 用於取消操作的中止訊號 | `undefined` | | `timeout` | `number` | 伺服器啟動逾時時間(毫秒) | `5000` | | `config` | `Config` | 設定物件 | `{}` | --- ## 設定 您可以傳入一個設定物件來自訂行為。實例仍然會讀取您的 `opencode.json`,但您可以透過內嵌方式覆寫或新增設定: ```javascript 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 實例,可以建立一個用戶端實例來連線: ```javascript import { createOpencodeClient } from "@opencode-ai/sdk" const client = createOpencodeClient({ baseUrl: "http://localhost:4096", }) ``` #### 選項 | 選項 | 型別 | 描述 | 預設值 | | --------------- | ---------- | ---------------------------- | ----------------------- | | `baseUrl` | `string` | 伺服器 URL | `http://localhost:4096` | | `fetch` | `function` | 自訂 fetch 實作 | `globalThis.fetch` | | `parseAs` | `string` | 回應解析方式 | `auto` | | `responseStyle` | `string` | 回傳風格:`data` 或 `fields` | `fields` | | `throwOnError` | `boolean` | 拋出錯誤而非回傳錯誤 | `false` | --- ## 型別 SDK 包含所有 API 型別的 TypeScript 定義。您可以直接匯入它們: ```typescript import type { Session, Message, Part } from "@opencode-ai/sdk" ``` 所有型別均根據伺服器的 OpenAPI 規範產生,可在型別檔案中查看。 --- ## 錯誤處理 SDK 可能會拋出錯誤,您可以捕捉並處理這些錯誤: ```typescript 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。 ### 基本用法 ```typescript 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"] } ``` ### 輸出格式型別 | 型別 | 描述 | | ------------- | --------------------------------------- | | `text` | 預設值。標準文字回應(無結構化輸出) | | `json_schema` | 回傳符合所提供 Schema 的經過驗證的 JSON | ### JSON Schema 格式 使用 `type: 'json_schema'` 時,需提供以下欄位: | 欄位 | 型別 | 描述 | | ------------ | --------------- | ------------------------------------- | | `type` | `'json_schema'` | 必填。指定 JSON Schema 模式 | | `schema` | `object` | 必填。定義輸出結構的 JSON Schema 物件 | | `retryCount` | `number` | 選填。驗證重試次數(預設值:2) | ### 錯誤處理 如果模型在所有重試後仍無法產生有效的結構化輸出,回應中會包含 `StructuredOutputError`: ```typescript 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 可增加重試次數,對於簡單 Schema 可減少 --- ## API SDK 透過型別安全的用戶端公開所有伺服器 API。 --- ### Global | 方法 | 描述 | 回應 | | ----------------- | ------------------------ | ------------------------------------ | | `global.health()` | 檢查伺服器健康狀態和版本 | `{ healthy: true, version: string }` | --- #### 範例 ```javascript const health = await client.global.health() console.log(health.data.version) ``` --- ### App | 方法 | 描述 | 回應 | | -------------- | ------------------ | ------------------------------------------- | | `app.log()` | 寫入一筆日誌 | `boolean` | | `app.agents()` | 列出所有可用的代理 | Agent[] | --- #### 範例 ```javascript // 寫入一筆日誌 await client.app.log({ body: { service: "my-app", level: "info", message: "Operation completed", }, }) // 列出可用的代理 const agents = await client.app.agents() ``` --- ### Project | 方法 | 描述 | 回應 | | ------------------- | ------------ | --------------------------------------------- | | `project.list()` | 列出所有專案 | Project[] | | `project.current()` | 取得當前專案 | Project | --- #### 範例 ```javascript // List all projects const projects = await client.project.list() // Get current project const currentProject = await client.project.current() ``` --- ### Path | 方法 | 描述 | 回應 | | ------------ | ------------ | ---------------------------------------- | | `path.get()` | 取得當前路徑 | Path | --- #### 範例 ```javascript // 取得當前路徑資訊 const pathInfo = await client.path.get() ``` --- ### Config | 方法 | 描述 | 回應 | | -------------------- | -------------------- | ----------------------------------------------------------------------------------------------------- | | `config.get()` | 取得設定資訊 | Config | | `config.providers()` | 列出供應商和預設模型 | `{ providers: `Provider[]`, default: { [key: string]: string } }` | --- #### 範例 ```javascript 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(僅注入上下文)。預設回傳帶有 AI 回應的 AssistantMessage。支援透過 `body.outputFormat` 使用[結構化輸出](#結構化輸出) | | `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` | --- #### 範例 ```javascript // 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 | 方法 | 描述 | 回應 | | ------------------------- | -------------------- | ----------------------------------------------------------------------------------- | | `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) --- #### 範例 ```javascript // 搜尋和讀取檔案 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` | --- #### 範例 ```javascript // 控制 TUI 介面 await client.tui.appendPrompt({ body: { text: "Add this to prompt" }, }) await client.tui.showToast({ body: { message: "Task completed", variant: "success" }, }) ``` --- ### Auth | 方法 | 描述 | 回應 | | ------------------- | ------------ | --------- | | `auth.set({ ... })` | 設定驗證憑證 | `boolean` | --- #### 範例 ```javascript await client.auth.set({ path: { id: "anthropic" }, body: { type: "api", key: "your-api-key" }, }) ``` --- ### Events | 方法 | 描述 | 回應 | | ------------------- | -------------------- | -------------------- | | `event.subscribe()` | 伺服器傳送的事件串流 | 伺服器傳送的事件串流 | --- #### 範例 ```javascript // 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) } ```