iT邦幫忙

2026 iThome 鐵人賽

DAY 17
0
AI Engineering

[ opencode ] 開源 AI coding agent系列 第 17

17-opencode | Plugins 與 SDK:程式化擴充

  • 分享至 

  • xImage
  •  

! 本篇文章將會介紹 plugins 與 SDK,用事件 hook 操縱 opencode 的一舉一動,再用型別安全客戶端把它接進任何程式 :D

TL;DR: https://dev.benben.me/slides/s/ironman-17-plugins-sdk

本篇目標

讀完這篇你會學到:

  • plugin 的結構、載入方式與事件 hook
  • 用 plugin 做「 session 結束通知」、「保護 .env」這類全場監控
  • 用 SDK 起 server、送 prompt、收 structured output

Plugin:全場監控的 Hooks

Day 16 的 tool 是「給 AI 一個新能力」;plugin 是「在 opencode 的運作流程上掛 Hooks」。AI 每次跑工具前、session 結束時、檔案被編輯時——你都能插一腳。

載入方式

  • 本地檔案:.opencode/plugins/(專案)與 ~/.config/opencode/plugins/(全域),啟動自動載入
  • npm 套件:設定檔列清單,啟動時自動用 Bun 安裝
{
  "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

實戰一:session 結束就通知

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 通知會叫你回來。遠端工作、多工必備。

實戰二:禁止 AI 讀 .env

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.idlesession.errortool.execute.before/afterpermission.askedfile.editedcommand.executedtui.toast.show……另有 experimental.session.compacting 讓你自訂 compaction 時要保留的 context。完整列表見官方 plugins 文件。

SDK:把 opencode 當圖書館用

架構先修課

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

送 prompt、拿結構化輸出

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 當操縱對象的。

小結

  • Plugin = 事件 Hooks:.opencode/plugins/ 或 npm 套件,攔工具、發通知、改行為
  • SDK = 型別安全客戶端:createOpencode 起 server,session.prompt 拿 structured output
  • TUI 只是客戶端,本體是 OpenAPI server——程式化整合的大門從這裡打開

明日預告

Day 18:Headless 與 server mode——把 opencode 塞進腳本與 CI,沒有畫面也能上戰場。


有任何疑問但沒有 iT 邦幫忙帳號,或是想匿名提問?
歡迎到 https://dev.benben.me/q/P3C5U6 提問或加油打氣,沒意外的話會在完賽之後一起回答 :D


上一篇
16-opencode | Custom tools:擴充 agent 的手腳
下一篇
18-opencode | Headless 與 server mode:CLI 自動化與 CI
系列文
[ opencode ] 開源 AI coding agent24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言