V1에서 플러그인 마이그레이션
V1 플러그인의 도구와 훅을 V2 플러그인 API로 이식합니다.
플러그인 설정은 자동으로 정규화할 수 있지만 플러그인 구현 코드는 직접 이식해야 합니다. V1 플러그인 함수는 도구와 훅을 담은 단일 객체를 반환했습니다. V2 플러그인은 id와 setup(ctx)를 포함한 정의를 기본(default) export하며, setup은 컨텍스트를 통해 훅, 변환, 도구 및 구독을 등록합니다.
경고: V1 플러그인 구현은 V2에서 실행되지 않습니다. 파일을 옮기거나 설정 항목 이름만 바꾸는 것으로는 충분하지 않습니다.
플러그인 설정 마이그레이션
plugin을 plugins로 이름을 변경합니다. 패키지와 옵션 튜플은 객체로 교체하세요.
// V1
{
"plugin": [
"opencode-example-plugin",
["./plugin/local.ts", { "enabled": true }]
]
}
// V2
{
"plugins": [
"opencode-example-plugin",
{
"package": "./plugin/local",
"options": { "enabled": true }
}
]
}V2는 .opencode/plugin/과 .opencode/plugins/ 모두에서 로컬 플러그인을 검색합니다. V2 파일에는 .opencode/plugins/를 사용하세요. 설정에 지정하는 로컬 경로는 반드시 디렉터리여야 합니다. 위 예시에서는 이식한 구현을 ./plugin/local/index.ts로 이동하세요. ./plugin/local.ts처럼 파일을 지정하면 로그에 경고가 남고 건너뛰어집니다. 이동할 때 보조 모듈도 플러그인 옆에 함께 유지하세요. 로컬 플러그인과 패키지 플러그인은 동일한 구현 API를 사용합니다.
진입점 교체
패키지 import를 변경하고, export하던 플러그인 함수를 Plugin.define으로 교체한 뒤 초기화 코드를 setup 안으로 옮기세요.
import type { Plugin } from "@opencode-ai/plugin"
export const ExamplePlugin: Plugin = async ({ directory, project, client }) => {
await client.app.log({
body: { service: "example", level: "info", message: `Loaded for ${project.id}` },
})
return {
// V1 tools and hooks
}
}import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "example",
async setup(ctx) {
await ctx.storage.set("last-project", ctx.location.project.id)
console.log(`Loaded for ${ctx.location.directory}`)
},
})모든 V2 플러그인에는 안정적인 id가 필요합니다. 플러그인 스토리지는 이 ID를 범위로 사용하며, 상태 및 진단에서도 플러그인을 식별합니다. 게시된 플러그인은 대상 OpenCode 릴리스와 호환되는 @opencode/plugin 버전에 의존해야 합니다.
컨텍스트 마이그레이션
V2 컨텍스트는 OpenCode 클라이언트이자 플러그인 API입니다. 대부분의 작업은 별도의 client 속성 대신 도메인별로 그룹화되어 있습니다.
| V1 | V2 |
|---|---|
directory | ctx.location.directory |
project | ctx.location.project |
client | ctx.session, ctx.permission, ctx.agent 같은 도메인 메서드 |
| 플러그인 옵션 인수 | ctx.options |
반환된 dispose() 훅 | setup에서 반환하는 정리(cleanup) 함수 |
반환된 event 훅 | ctx.event.subscribe() |
| 반환된 설정, 모델 또는 도구 변경 | 해당 도메인의 transform(...) |
$ Bun 셸 헬퍼 | 플러그인에서 사용하는 프로세스 API를 직접 import하여 관리 |
ctx.location은 이 플러그인 인스턴스가 로드된 위치를 나타냅니다. 플러그인이 관찰할 수 있는 모든 세션이나 이벤트의 위치는 아니므로, 구분이 중요할 때는 세션이나 이벤트 데이터를 직접 읽으세요.
컨텍스트는 표에 나열된 것 외에도 카탈로그, 명령어, 통합 기능, MCP 서버, 레퍼런스, 스킬, 스토리지, VCS, 워크트리 및 웹 검색 등 훨씬 많은 도메인을 노출합니다. 자세한 내용은 전체 플러그인 컨텍스트를 참고하세요.
setup에서 훅 등록
V1은 문자열 키로 훅을 반환했습니다. V2는 해당 작업을 소유한 도메인에 각 훅을 등록합니다. 콜백은 별도의 input과 output 객체 대신 변경 가능한 단일 이벤트 객체를 받습니다.
import type { Plugin } from "@opencode-ai/plugin"
export const GuardPlugin: Plugin = async () => ({
"tool.execute.before": async (input, output) => {
if (input.tool === "read" && output.args.filePath.includes(".env")) {
throw new Error("Do not read .env files")
}
},
"shell.env": async (_input, output) => {
output.env.COMPANY_ENV = "development"
},
})import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "company.guard",
async setup(ctx) {
await ctx.tool.hook("execute.before", (event) => {
const input = event.input as { filePath?: string }
if (event.tool === "read" && input.filePath?.includes(".env")) {
throw new Error("Do not read .env files")
}
})
await ctx.shell.hook("create.before", (event) => {
event.env.COMPANY_ENV = "development"
})
},
})등록된 항목은 플러그인의 수명 동안 활성 상태를 유지하며 언로드될 때 자동으로 해제됩니다. registration.dispose()로 특정 훅이나 변환을 조기에 제거해야 할 때만 반환된 등록 객체를 보관하세요.
아래 표에서 각 V1 훅에 가장 가까운 V2 API를 확인할 수 있습니다.
| V1 훅 | V2 API |
|---|---|
event | ctx.event.subscribe() |
dispose | setup에서 반환하는 정리(cleanup) 함수 |
config | 영향을 받는 도메인의 transform(...) |
tool 맵 | ctx.tool.transform(...) |
auth | ctx.integration.transform(...) 및 통합 API |
provider | ctx.provider.transform(...) 및 ctx.model.transform(...) |
chat.message | ctx.session.hook("prompt", ...) |
chat.params | ctx.session.hook("context", ...) |
chat.headers | ctx.session.hook("model.request", ...) 또는 "http.request" |
permission.ask | ctx.permission.hook("evaluate", ...) |
command.execute.before | 의도에 따라 명령어 변환 또는 prompt 훅 |
tool.execute.before | ctx.tool.hook("execute.before", ...) |
tool.execute.after | ctx.tool.hook("execute.after", ...) |
shell.env | ctx.shell.hook("create.before", ...) |
tool.definition | ctx.tool.transform(...) |
experimental.chat.system.transform | ctx.session.hook("context", ...)에서 event.system 편집 |
experimental.chat.messages.transform | ctx.session.hook("context", ...)에서 event.messages 편집 |
experimental.session.compacting | ctx.session.hook("compaction", ...) |
이는 마이그레이션 대상이며 항상 단순 이름 변경인 것은 아닙니다. 특히 V2의 prompt 훅은 영속적 프롬프트 수락(admission) 전에 실행되는 반면, context는 에이전트 모델 요청 직전에 실행됩니다. 모든 종류의 모델 요청에 변환을 적용해야 한다면 context, compaction, generate, title을 각각 등록하세요.
모든 V1 실험적 훅에 직접 대응하는 V2 훅이 존재하는 것은 아닙니다. experimental.compaction.autocontinue, experimental.provider.small_model 또는 experimental.text.complete를 사용하는 플러그인은 내부 수명 주기 가정을 그대로 유지하기보다 V2의 세션, 프로바이더, 모델 및 이벤트 API에 맞춰 재설계해야 합니다.
command.execute.before 역시 1:1로 대응하는 전역 훅이 없습니다. 플러그인이 해당 명령어를 소유하는 경우 ctx.command.transform으로 명령어를 등록하세요. 명령어 및 기타 프롬프트 소스에서 제출된 프롬프트를 수정하는 것이 실제 목적이라면 prompt 훅을 사용하세요.
요청 훅 마이그레이션
V2는 프롬프트 수락, 모델에 표시되는 컨텍스트, 의미적(semantic) 모델 옵션 및 네이티브 HTTP를 분리합니다. 플러그인에 필요한 가장 좁은 계층을 선택하세요.
import type { Plugin } from "@opencode-ai/plugin"
export const RequestPlugin: Plugin = async () => ({
"chat.params": async (_input, output) => {
output.temperature = 0.2
output.maxOutputTokens = 8_000
},
"chat.headers": async (_input, output) => {
output.headers["x-plugin"] = "review"
},
"experimental.chat.system.transform": async (_input, output) => {
output.system.push("Focus on correctness.")
},
})import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "review-request",
async setup(ctx) {
await ctx.session.hook("context", (event) => {
event.system.push({ type: "text", text: "Focus on correctness." })
event.options.temperature = 0.2
event.options.maxTokens = 8_000
})
await ctx.session.hook("model.request", (event) => {
event.headers["x-plugin"] = "review"
})
},
})의미적 프로바이더 옵션은 event.options를 사용하세요. 모델 요청 헤더와 원시 요청 설정에는 model.request를 사용하고, 프로바이더의 네이티브 HTTP 교환에 직접 접근해야 할 때만 http.request 또는 http.response를 사용하세요. 특정 프로바이더 전용 훅은 ctx.session.hook의 세 번째 인수로 { providerID: "..." }를 전달할 수 있습니다.
사용자 지정 도구 마이그레이션
V1은 이전 tool() 헬퍼로 만든 tool 맵을 반환했습니다. V2는 동기식 ctx.tool.transform 에디터를 통해 도구 정의를 등록합니다. 도구 스키마는 JSON Schema를 사용하며 실행 결과는 구조화된 콘텐츠를 반환합니다.
import { tool } from "@opencode-ai/plugin"
export const ToolsPlugin = async () => ({
tool: {
greeting: tool({
description: "Create a greeting",
args: { name: tool.schema.string() },
async execute(args) {
return `Hello ${args.name}!`
},
}),
},
})import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "greeting",
async setup(ctx) {
await ctx.tool.transform((editor) => {
editor.add({
name: "greeting",
description: "Create a greeting",
input: {
type: "object",
properties: { name: { type: "string" } },
required: ["name"],
additionalProperties: false,
},
async execute(input) {
return { content: `Hello ${(input as { name: string }).name}!` }
},
})
})
},
})변환(transform)은 재실행 가능한(replayable) 상태 편집입니다. 콜백은 동기적이고 가벼워야 하며 일회성 부수 효과(side effect)가 없어야 합니다. 등록 전에 외부 데이터를 로드하여 콜백에 캡처해 두고, 해당 데이터가 변경되면 도메인의 reload() 메서드를 호출하세요. 뒤에 등록된 플러그인 변환은 이전 변경 사항을 볼 수 있으며 이를 업데이트, 교체 또는 제거할 수 있습니다.
동일한 변환 패턴이 V1의 config 및 provider 훅을 대체하지만, V2는 변경 가능한 단일 전역 설정 객체를 노출하지 않습니다. 변경 사항을 소유한 도메인(ctx.agent, ctx.provider, ctx.model, ctx.command, ctx.integration, ctx.mcp, ctx.reference, ctx.skill, ctx.tool, ctx.vcs, ctx.websearch 또는 ctx.worktree)에 직접 등록하세요. 인증 방식은 통합(integration)에 속하며, 프로바이더 변환은 소스 정의와 프로바이더 설정을 기여하고, 모델 변환은 활성 프로바이더의 전체 모델 컬렉션에 제한 사항과 재정의를 적용합니다.
await ctx.provider.transform((editor) => {
editor.update("anthropic", (provider) => {
provider.headers = { ...provider.headers, "x-company": "engineering" }
})
})
await ctx.model.transform((editor) => {
editor.list("anthropic").forEach((model) => {
if (!model.capabilities.tools) editor.remove(model.providerID, model.id)
})
})이벤트 및 정리(cleanup) 마이그레이션
V1의 event 콜백은 공개 서버 이벤트 스트림에 대한 비동기 구독으로 변경되었습니다. setup이 반환하는 정리 함수에서 구독을 중단(abort)하세요.
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "notifications",
setup(ctx) {
const controller = new AbortController()
void (async () => {
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
if (event.type === "session.idle") console.log("Session completed")
}
})()
return () => controller.abort()
},
})타이머, 하위 프로세스, 소켓 및 플러그인이 소유한 기타 리소스에는 정리 함수를 사용하세요. 훅 및 변환 등록은 플러그인 범위에 묶여 있으므로 자동으로 정리됩니다.
옵션 및 영구 상태 마이그레이션
옵션은 ctx.options에서 읽습니다. 플러그인에 속한 상태를 저장할 때는 임의의 전역 파일을 만들지 말고 ctx.storage를 사용하세요. JSON 값이 영속적으로 저장되며 해당 플러그인 범위로 격리됩니다.
const strict = ctx.options.strict === true
await ctx.storage.set("settings", { strict })
const settings = await ctx.storage.get("settings")단일 패키지에서 V1 및 V2 동시 지원
패키지는 하나의 기본 export에서 두 구현을 일시적으로 함께 노출할 수 있습니다. V1은 server()를 호출하고 V2는 setup()을 호출합니다. 두 API는 여전히 별개이며 이 구조가 훅을 자동으로 변환해 주지는 않습니다.
import { Plugin } from "@opencode/plugin"
export default {
...Plugin.define({
id: "example",
async setup(ctx) {
await ctx.tool.hook("execute.before", () => {
console.log("A tool is about to run")
})
},
}),
async server() {
return {
"tool.execute.before": async () => {
console.log("A tool is about to run")
},
}
},
}V1 객체 진입점은 OpenCode 1.18.29 이상에서 지원됩니다. 이전 V1 릴리스를 지원해야 한다면 별도의 패키지 버전이나 진입점을 사용하고 지원한다고 명시한 가장 오래된 릴리스에서 테스트하세요. 지원 기간이 끝나면 V1 구현을 제거하세요.
이식한 플러그인 검증
각 플러그인에 대해 다음을 확인합니다.
- 활성 플러그인 목록에 플러그인의 ID와 소스가 표시되는지 확인합니다.
- 등록된 모든 훅, 변환, 도구, 명령어 및 이벤트 구독을 실행해 봅니다.
- 플러그인을 다시 로드하거나 제거하여 정리(cleanup) 동작을 검증합니다.
- 깨끗한 프로젝트에서 플러그인 옵션과 영구 저장 상태를 테스트합니다.
- 게시된 패키지의 경우 워크스페이스에 링크된 사본뿐만 아니라 설치된 패키지도 테스트합니다.
전체 Promise API는 서버, Effect 진입점은 Effect 플러그인, 사용자 지정 메서드와 이벤트는 플러그인 RPC, 터미널 UI는 TUI 플러그인을 참고하세요.