! 本篇文章將會介紹 plugins 與 SDK,用事件 hook 操縱 opencode 的一舉一動,再用型別安全客戶端把它接進任何程式 :D
TL;DR: https://dev.benben.me/slides/s/ironman-17-plugins-sdk
讀完這篇你會學到:
Day 16 的 tool 是「給 AI 一個新能力」;plugin 是「在 opencode 的運作流程上掛 Hooks」。AI 每次跑工具前、session 結束時、檔案被編輯時——你都能插一腳。
.opencode/plugins/(專案)與 ~/.config/opencode/plugins/(全域),啟動自動載入{
"plugin": ["opencode-helicone-session", "opencode-wakatime"]
}
一個 plugin 就是一個 export 函式的模組:
// .opencode/plugins/example.ts
export const MyPlugin = async ({project, client, $, directory, worktree}) => {
return {
// hooks
}
}
收到的好東西:client(SDK 客戶端,等等講)、$(Bun shell API)、worktree。
export const NotificationPlugin = async ({$}) => {
return {
event: async ({event}) => {
if (event.type === 'session.idle') {
await $`osascript -e 'display notification "Session completed!" with title "opencode"'`
}
},
}
}
丟給 AI 一個大任務然後去泡咖啡,macOS 通知會叫你回來。遠端工作、多工必備。
export const EnvProtection = async () => {
return {
'tool.execute.before': async (input, output) => {
if (input.tool === 'read' && output.args.filePath.includes('.env')) {
throw new Error('Do not read .env files')
}
},
}
}
tool.execute.before 在每個工具執行前攔截——直接丟錯擋下。這是寫進團隊規則的安全網,比「希望 AI 別偷看」可靠多了。
常用清單:session.idle、session.error、tool.execute.before/after、permission.asked、file.edited、command.executed、tui.toast.show……另有 experimental.session.compacting 讓你自訂 compaction 時要保留的 context。完整列表見官方 plugins 文件。
opencode 的 TUI 其實只是個客戶端——本體是一個 HTTP server(OpenAPI 3.1 規格就掛在 /doc)。所以你能完全繞過 TUI,用程式驅動它。
npm install @opencode-ai/sdk
import {createOpencode} from '@opencode-ai/sdk'
const {client} = await createOpencode()
createOpencode() 會同時生一個 server 與 client(預設 127.0.0.1:4096,可帶 hostname / port / config 覆寫)。已經有 server 在跑的話,改用:
import {createOpencodeClient} from '@opencode-ai/sdk'
const client = createOpencodeClient({
baseUrl: 'http://localhost:4096',
})
const session = await client.session.create({body: {title: '研究任務'}})
const result = await client.session.prompt({
path: {id: session.id},
body: {
parts: [{type: 'text', text: 'Research Anthropic and provide company info'}],
format: {
type: 'json_schema',
schema: {
type: 'object',
properties: {
company: {type: 'string'},
founded: {type: 'number'},
},
required: ['company', 'founded'],
},
},
},
})
console.log(result.data.info.structured_output)
// { company: "Anthropic", founded: ..., ... }
format 帶 JSON Schema,模型會透過 StructuredOutput 工具回傳驗證過的 JSON——對「用 AI 產資料餵程式」的場景,這比解析自由文本可靠一百倍。驗證失敗會自動重試(預設 2 次),最後失敗會在 info.error 給你 StructuredOutputError。
SDK 是全 API 的型別安全映射:session.list / session.share / find.text / file.read / config.providers ... 還有 event.subscribe() 訂閱 SSE 事件流——plugin 監聽的事件,你的程式也全都聽得到。
小小測驗:還記得 Day 03 的
/share嗎?SDK 也有session.share—— 代表你可以寫個腳本,每晚自動把工作摘要 share 成連結寄給自己。CLI 的功能,SDK 全都有。
Q:plugin 和 tool 到底怎麼選?
A:給 AI 「呼叫」的用 tool;在事件流「旁邊」做事的用 plugin。也可以在 plugin 的 hooks 裡註冊 tool——plugin 是超集。
Q:npm plugin 裝在哪?
A:啟動時用 Bun 自動裝到 ~/.cache/opencode/node_modules/,不用自己 npm install。
Q:SDK 可以控制正在跑的 TUI 嗎?
A:可以,client.tui.* 有 appendPrompt、submitPrompt、showToast——IDE 外掛就是這樣把 TUI 當操縱對象的。
.opencode/plugins/ 或 npm 套件,攔工具、發通知、改行為createOpencode 起 server,session.prompt 拿 structured outputDay 18:Headless 與 server mode——把 opencode 塞進腳本與 CI,沒有畫面也能上戰場。
有任何疑問但沒有 iT 邦幫忙帳號,或是想匿名提問?
歡迎到 https://dev.benben.me/q/P3C5U6 提問或加油打氣,沒意外的話會在完賽之後一起回答 :D