서버
OpenCode 플러그인의 서버 파트(도구, 훅, 통합 기능, 명령어 및 에이전트)를 개발합니다.
플러그인의 서버 파트는 OpenCode 서버 내부에서 실행됩니다. OpenCode의 동작을 수정하고 도구, 훅, 통합 기능, 명령어, 에이전트 같은 기능을 추가합니다. 플러그인 패키지의 구성, 로드 및 게시 방법은 개요를 참고하세요.
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "example",
async setup(ctx) {
await ctx.storage.set("loaded", true)
},
})수명 주기(Lifecycle)
setup은 플러그인이 로드될 때 실행됩니다. 플러그인이 언로드될 때 실행되는 정리(cleanup) 함수를 반환할 수 있습니다.
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "example",
setup(ctx) {
console.log(`loaded in OpenCode ${ctx.app.version}`)
return () => console.log("unloaded")
},
})컨텍스트
플러그인 컨텍스트는 본질적으로 OpenCode 서버 클라이언트입니다. 읽기 및 액션 메서드는 클라이언트와 동일한 입력과 응답을 사용합니다. 여기에 변환(transform), 런타임 훅, 리로드, 등록 및 플러그인 옵션을 위한 플러그인 전용 메서드가 추가됩니다.
setup(ctx) {
console.log(ctx.app.version)
}ctx.location은 이 플러그인 인스턴스가 로드된 위치를 나타냅니다. directory, 선택적 workspaceID 및 project 메타데이터(id, directory, canonical)를 포함하며 Promise 플러그인과 Effect 플러그인 모두에서 사용할 수 있습니다. 이는 플러그인 인스턴스 자체의 위치이지, 플러그인이 접근할 수 있는 모든 세션이나 수신하는 모든 이벤트의 위치는 아닙니다.
setup(ctx) {
console.log(ctx.location.directory)
console.log(ctx.location.project.canonical)
}옵션
opencode.json(c)에서 객체 형식을 사용해 플러그인 옵션을 전달합니다.
{
"plugins": [
{
"package": "./plugins/company",
"options": {
"strict": true,
},
},
],
}setup 중에 ctx.options에서 해당 값을 읽을 수 있습니다.
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "company",
setup(ctx) {
const strict = ctx.options.strict === true
},
})변환(Transforms)
변환은 OpenCode의 도메인 상태에 대한 동기식 편집이며, 각 변환은 해당 도메인의 이전 등록을 기반으로 누적됩니다. ctx.model.list() 같은 레지스트리 읽기는 플러그인 setup 중에도 지금까지의 모든 등록을 반영합니다. 시작 시 배치 처리(startup batching)는 업데이트 알림만 병합할 뿐 읽기 반환값을 지연시키지 않습니다. 단, 리소스 상태 API는 실행 중인 리소스의 실제 상태를 보고하므로 정의가 등록되었다고 해서 연결이나 기타 리소스 작업이 완료되었음을 의미하지는 않습니다.
소스는 ctx.provider.transform을 통해 프로바이더와 불변 모델 정의를 제공합니다.
import { Model, Plugin, Provider } from "@opencode/plugin"
export default Plugin.define({
id: "company.models",
async setup(ctx) {
const providerID = Provider.ID.make("acme")
const models = [{ ...Model.Info.default(providerID, Model.ID.make("reasoner")), name: "Acme Reasoner" }]
await ctx.provider.transform((editor) => {
editor.add({
info: {
...Provider.Info.empty(providerID),
name: "Acme",
activation: "enabled",
package: "@opencode/ai/providers/openai-compatible",
settings: { baseURL: "http://127.0.0.1:8000/v1" },
},
models,
})
})
const available = await ctx.model.list()
},
})등록, 제거 또는 reload()가 호출되면 레지스트리가 변경된 것으로 표시되며, 다음 읽기 시 모든 활성 변환을 등록 순서대로 새 값에 재실행하여 레지스트리를 재구성합니다. 변환은 가볍고 반복 실행 가능하게 유지하세요. 이미 읽은 값은 이후 재구성으로 변경되지 않습니다.
프로바이더 변환과 가용성이 결정된 후, OpenCode는 활성 프로바이더의 모델을 구체화하고 모든 모델 변환을 순서대로 재실행합니다. 모델 정책은 새로 갱신된 소스를 포함해 전체 후보 컬렉션을 검사할 수 있습니다.
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "company.model-budget",
async setup(ctx) {
await ctx.model.transform((editor) => {
editor
.list()
.filter((model) => model.cost.some((tier) => tier.output > 20))
.forEach((model) => {
editor.remove(model.providerID, model.id)
})
})
},
})캡처된 입력은 자동으로 감시되지 않습니다. 동기 콜백 이전에 외부 데이터를 로드하고, 해당 입력이 변경된 후 reload()를 호출하세요. 아래 예시에서 loadFromSource()는 { info: Provider.Info, models: readonly Model.Info[] } 항목을 반환합니다.
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "company.models",
async setup(ctx) {
const source = { providers: await loadFromSource() }
await ctx.provider.transform((editor) => {
source.providers.forEach((provider) => editor.add(provider))
})
const refresh = async () => {
source.providers = await loadFromSource()
await ctx.provider.reload()
}
const timer = setInterval(() => void refresh().catch(console.error), 60_000)
return () => clearInterval(timer)
},
})프로바이더가 변경되면 활성 모델 결과 전체가 무효화되므로 출력 가격 정책은 새로 고쳐진 모델에도 계속 적용됩니다. 모델 변환에 캡처된 입력만 변경된 경우에는 ctx.model.reload()를 사용하세요.
API
에이전트(Agent)
모든 에이전트를 읽거나 ID로 단일 에이전트를 가져옵니다.
const agents = await ctx.agent.list()
const build = await ctx.agent.get({ agentID: "build" })변환을 등록하여 기본 에이전트를 검사, 업데이트, 제거 또는 선택합니다.
await ctx.agent.transform((editor) => {
const agents = editor.list()
const build = editor.get("build")
editor.default("build")
editor.update("build", (agent) => {
agent.description = "Builds features and fixes bugs"
})
editor.remove("legacy")
})변환에서 사용하는 외부 상태가 변경되면 에이전트를 다시 로드합니다.
await ctx.agent.reload()레퍼런스
스키마: Agent.Info (opens in a new tab)
interface AgentContext {
list(input?: AgentListInput, requestOptions?: RequestOptions): Promise<AgentListOutput>
get(input: AgentGetInput, requestOptions?: RequestOptions): Promise<AgentGetOutput>
transform(callback: (editor: AgentEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface AgentEditor {
list(): readonly AgentInfo[]
get(id: string): AgentInfo | undefined
default(id: string | undefined): void
update(id: string, update: (agent: AgentInfo) => void): void
remove(id: string): void
}
interface Registration {
dispose(): Promise<void>
}프로바이더(Providers)
사용 가능한 프로바이더를 읽거나 ID로 단일 프로바이더의 메타데이터를 조회합니다.
const providers = await ctx.provider.list()
const provider = await ctx.provider.get({ providerID: "anthropic" })프로바이더 변환은 프로바이더 설정과 소스 정의를 편집합니다. 에디터 읽기는 비활성 프로바이더를 포함하며 불변 정의를 노출합니다. models.update는 소스 모델의 소유된 복사본을 편집합니다.
await ctx.provider.transform((editor) => {
editor.update("anthropic", (provider) => {
provider.headers = { ...provider.headers, "x-company": "engineering" }
})
editor.models.update("anthropic", "claude-sonnet-5-5", (model) => {
model.name = "Team Sonnet"
})
editor.models.remove("anthropic", "legacy-model")
editor.remove("legacy-provider")
})models.set으로 프로바이더의 소스 인벤토리를 교체한 다음, 캡처된 정의가 변경되면 다시 로드합니다.
const source = { models: await loadModels() }
await ctx.provider.transform((editor) => {
editor.models.set("acme", source.models)
})
source.models = await loadModels()
await ctx.provider.reload()계정별 검색(discovery)의 경우 인벤토리를 로드하는 데 사용한 연결을 sourceConnection으로 전달하세요. 다른 연결이 선택되어 있는 동안 OpenCode는 플러그인이 갱신된 인벤토리를 게시할 때까지 해당 프로바이더를 제외합니다.
const connection = await ctx.integration.connection.active("acme")
if (!connection) return
const inventory = await loadInventory(connection)
await ctx.provider.transform((editor) => {
editor.add({ info: inventory.provider, models: inventory.models, sourceConnection: connection })
})레퍼런스
스키마: Provider.Info (opens in a new tab), Model.Info (opens in a new tab)
interface ProviderDomain extends ProviderApi {
transform(callback: (editor: ProviderEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface ProviderRecord {
readonly provider: Provider.Info
readonly models: ReadonlyMap<string, Model.Info>
readonly sourceConnection?: ConnectionInfo
}
interface ProviderEditor {
list(): readonly ProviderRecord[]
get(providerID: string): ProviderRecord | undefined
add(input: { info: Provider.Info; models: readonly Model.Info[]; sourceConnection?: ConnectionInfo }): void
update(providerID: string, update: (provider: DeepMutable<Provider.Info>) => void): void
remove(providerID: string): void
readonly models: {
set(providerID: string, models: readonly Model.Info[]): void
update(providerID: string, modelID: string, update: (model: DeepMutable<Model.Info>) => void): void
remove(providerID: string, modelID: string): void
}
}모델(Models)
사용 가능한 모델과 기본 선택 항목을 읽습니다.
const models = await ctx.model.list()
const selected = await ctx.model.default()모델 변환은 활성 프로바이더 후보 컬렉션 전체를 편집합니다. 비활성화된 후보도 모든 변환이 끝날 때까지 편집할 수 있으며, update는 사용 가능한 프로바이더 아래에만 모델을 추가할 수 있습니다.
await ctx.model.transform((editor) => {
editor.list("anthropic").forEach((model) => {
editor.update(model.providerID, model.id, (draft) => {
draft.enabled = draft.capabilities.tools
})
})
editor.default.set("anthropic", "claude-sonnet-5-5")
editor.remove("anthropic", "legacy-model")
})콜백은 원시(raw) 모델 재정의를 편집합니다. 프로바이더 기본값은 OpenCode가 결과를 커밋할 때 한 번 병합되며, 변경되지 않은 읽기는 해당 결과를 재사용합니다. editor.provider는 모델 변환 출력이 아니라 비활성 템플릿을 포함한 불변 소스 정의를 노출합니다.
await ctx.model.transform((editor) => {
const source = editor.provider.get("anthropic")?.models.get("claude-sonnet-5-5")
if (!source) return
editor.update("anthropic", source.id, (model) => {
model.limit.context = Math.min(model.limit.context, source.limit.context)
})
})
await ctx.model.reload()레퍼런스
스키마: Model.Info (opens in a new tab)
interface ModelDomain extends ModelApi {
transform(callback: (editor: ModelEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface ModelEditor {
list(providerID?: string): readonly DeepMutable<Model.Info>[]
get(providerID: string, modelID: string): DeepMutable<Model.Info> | undefined
update(providerID: string, modelID: string, update: (model: DeepMutable<Model.Info>) => void): void
remove(providerID: string, modelID: string): void
readonly default: {
get(): { providerID: string; modelID: string } | undefined
set(providerID: string, modelID: string): void
}
readonly provider: {
list(): readonly ProviderRecord[]
get(providerID: string): ProviderRecord | undefined
}
}명령어(Commands)
특정 위치에서 사용 가능한 명령어를 읽습니다.
const commands = await ctx.command.list()변환으로 명령어를 등록합니다. 실행기(executor)는 세션, 프롬프트 첨부 파일 및 요청된 전달 모드(delivery mode)를 전달받습니다.
await ctx.command.transform((editor) => {
editor.add({
name: "security-review",
description: "Review changes for security issues",
execute: async ({ sessionID, prompt, delivery }) => {
await ctx.session.prompt({
...prompt,
sessionID,
text: `Review these changes for security issues.\n\n${prompt.text}`,
delivery,
})
},
})
})변환에서 사용하는 외부 상태가 변경되면 명령어를 다시 로드합니다.
await ctx.command.reload()레퍼런스
스키마: Command.Info (opens in a new tab), Session.Inbox.Delivery (opens in a new tab)
interface CommandContext {
list(input?: CommandListInput, requestOptions?: RequestOptions): Promise<CommandListOutput>
transform(callback: (editor: CommandEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface CommandEditor {
add(definition: CommandDefinition): void
}
interface CommandDefinition {
name: string
description?: string
execute(input: CommandInvocation): Promise<void>
}
interface CommandInvocation {
sessionID: string
prompt: PromptInput
delivery: "steer" | "queue"
}통합 기능(Integrations)
통합 목록을 읽고 활성 자격 증명을 검사합니다.
const integrations = await ctx.integration.list()
const github = await ctx.integration.get({ integrationID: "github" })
const connection = await ctx.integration.connection.active("github")
const credential = connection ? await ctx.integration.connection.resolve(connection) : undefinedAPI 키로 통합을 연결합니다.
await ctx.integration.connect.key({
integrationID: "github",
key: process.env.GITHUB_TOKEN!,
})OAuth 연결 시도를 시작, 확인, 완료 또는 취소합니다.
const attempt = await ctx.integration.oauth.connect({ integrationID: "github", methodID: "oauth" })
const status = await ctx.integration.oauth.status({ integrationID: "github", attemptID: attempt.data.attemptID })
await ctx.integration.oauth.complete({ integrationID: "github", attemptID: attempt.data.attemptID, code })
await ctx.integration.oauth.cancel({ integrationID: "github", attemptID: attempt.data.attemptID })명령어 기반 연결도 동일한 시작, 상태 확인 및 취소 흐름을 제공합니다.
const attempt = await ctx.integration.command.connect({ integrationID: "acme", methodID: "cli" })
const status = await ctx.integration.command.status({ integrationID: "acme", attemptID: attempt.data.attemptID })
await ctx.integration.command.cancel({ integrationID: "acme", attemptID: attempt.data.attemptID })변환을 등록해 통합 기능을 검사하고 인증 방식을 관리합니다.
await ctx.integration.transform((editor) => {
const integrations = editor.list()
const acme = editor.get("acme")
editor.update("acme", (integration) => {
integration.name = "Acme"
})
editor.method.update({
integrationID: "acme",
method: { id: "cli", type: "command", label: "Sign in with Acme CLI", command: ["acme", "login"] },
})
const methods = editor.method.list("acme")
const legacy = methods.find((method) => method.type === "command" && method.id === "legacy")
if (legacy) editor.method.remove("acme", legacy)
editor.remove("legacy")
})변환에서 사용하는 외부 상태가 변경되면 통합 기능을 다시 로드합니다.
await ctx.integration.reload()레퍼런스
스키마: Integration.Info (opens in a new tab), Integration.Method (opens in a new tab), Connection.Info (opens in a new tab), Form.Answer (opens in a new tab)
interface IntegrationContext {
list(input?: IntegrationListInput, requestOptions?: RequestOptions): Promise<IntegrationListOutput>
get(input: IntegrationGetInput, requestOptions?: RequestOptions): Promise<IntegrationGetOutput>
connect: {
key(input: IntegrationConnectKeyInput, requestOptions?: RequestOptions): Promise<void>
}
oauth: {
connect(
input: IntegrationOauthConnectInput,
requestOptions?: RequestOptions,
): Promise<IntegrationOauthConnectOutput>
status(input: IntegrationOauthStatusInput, requestOptions?: RequestOptions): Promise<IntegrationOauthStatusOutput>
complete(input: IntegrationOauthCompleteInput, requestOptions?: RequestOptions): Promise<void>
cancel(input: IntegrationOauthCancelInput, requestOptions?: RequestOptions): Promise<void>
}
command: {
connect(
input: IntegrationCommandConnectInput,
requestOptions?: RequestOptions,
): Promise<IntegrationCommandConnectOutput>
status(
input: IntegrationCommandStatusInput,
requestOptions?: RequestOptions,
): Promise<IntegrationCommandStatusOutput>
cancel(input: IntegrationCommandCancelInput, requestOptions?: RequestOptions): Promise<void>
}
transform(callback: (editor: IntegrationEditor) => void): Promise<Registration>
reload(): Promise<void>
connection: {
active(integrationID: string): Promise<ConnectionInfo | undefined>
resolve(connection: ConnectionInfo): Promise<CredentialValue | undefined>
}
}
interface IntegrationEditor {
list(): readonly IntegrationRef[]
get(id: string): IntegrationRef | undefined
update(id: string, update: (integration: IntegrationRef) => void): void
remove(id: string): void
method: {
list(integrationID: string): readonly IntegrationMethod[]
update(input: IntegrationMethodRegistration): void
remove(integrationID: string, method: IntegrationMethod): void
}
}자격 증명(Credentials)
저장된 자격 증명을 해당 통합의 활성 자격 증명으로 지정합니다.
await ctx.credential.activate({ credentialID })레퍼런스
interface CredentialContext {
activate(input: CredentialActivateInput, requestOptions?: RequestOptions): Promise<void>
}MCP
MCP 서버와 현재 연결 상태를 나열합니다.
const servers = await ctx.mcp.list()플러그인은 오직 변환을 통해서만 MCP 서버를 관리합니다. 서버를 추가하거나 교체하려면 editor.set, 설정을 변경하려면 editor.update, 제거하려면 editor.remove를 사용하세요. 설정 검사는 editor.list와 editor.get으로 수행합니다.
await ctx.mcp.transform((editor) => {
const servers = editor.list()
const docs = editor.get("docs")
editor.set("docs", { type: "remote", url: "https://mcp.example.com" })
editor.update("docs", (server) => {
server.disabled = false
})
editor.remove("legacy")
})변환에서 disabled: true를 설정하면 서버를 비활성화하고 연결을 해제하며, disabled: false를 설정하면 활성화해 OpenCode가 연결할 수 있게 합니다. OpenCode는 변환된 설정에 따라 서버 수명 주기를 자동으로 조정(reconcile)합니다.
변환에서 사용하는 외부 상태가 변경된 후 reload()를 호출하면 변환을 재적용하고 서버 상태를 다시 조정합니다.
await ctx.mcp.reload()레퍼런스
스키마: Mcp.Server (opens in a new tab), Mcp.LocalConfigEncoded (opens in a new tab), Mcp.RemoteConfigEncoded (opens in a new tab)
interface MCPContext {
list(input?: McpListInput, requestOptions?: RequestOptions): Promise<McpListOutput>
transform(callback: (editor: MCPEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface MCPEditor {
list(): readonly (readonly [string, McpServerConfig])[]
get(name: string): McpServerConfig | undefined
set(name: string, config: McpServerConfig): void
update(name: string, update: (config: McpServerConfig) => void): void
remove(name: string): void
}플러그인(Plugins)
특정 위치에서 현재 활성화된 플러그인 목록을 조회합니다.
const plugins = await ctx.plugin.list()레퍼런스
스키마: Plugin.Info (opens in a new tab), Plugin.Source (opens in a new tab)
interface PluginContext {
list(input?: PluginListInput, requestOptions?: RequestOptions): Promise<PluginListOutput>
}레퍼런스(References)
특정 위치에서 사용 가능한 레퍼런스를 읽습니다.
const references = await ctx.reference.list()변환을 등록하여 로컬 및 Git 레퍼런스를 검사, 추가 또는 제거합니다. get(name)은 현재 설정된 소스를 반환하며 해당 이름이 없으면 undefined를 반환합니다.
await ctx.reference.transform((editor) => {
const references = editor.list()
editor.add("handbook", { type: "local", path: "/workspace/docs/handbook" })
editor.add("standards", { type: "git", repository: "https://github.com/acme/standards", branch: "main" })
const handbook = editor.get("handbook")
editor.remove("legacy")
})변환에서 사용하는 외부 상태가 변경되면 레퍼런스를 다시 로드합니다.
await ctx.reference.reload()레퍼런스
스키마: Reference.Info (opens in a new tab), Reference.LocalSource (opens in a new tab), Reference.GitSource (opens in a new tab)
interface ReferenceContext {
list(input?: ReferenceListInput, requestOptions?: RequestOptions): Promise<ReferenceListOutput>
transform(callback: (editor: ReferenceEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface ReferenceEditor {
list(): readonly (readonly [string, ReferenceLocalSource | ReferenceGitSource])[]
get(name: string): ReferenceLocalSource | ReferenceGitSource | undefined
add(name: string, source: ReferenceLocalSource | ReferenceGitSource): void
remove(name: string): void
}생성(Generate, 실험적)
세션을 생성하거나 도구를 호출하거나 세션 기록에 추가하지 않고 선택한 모델로 결과를 생성합니다. 이 API는 변경될 수 있습니다. ctx.generate.text도 여전히 작동하지만 지원 중단 예정(deprecated)이므로 대신 ctx.experimental.generate.text를 사용하세요.
const review = await ctx.experimental.generate.text({
model: { providerID: "anthropic", id: "claude-sonnet-5-5" },
prompt: "Review this proposed action.",
})
const { images } = await ctx.experimental.generate.image({
model: { providerID: "openai", id: "gpt-image-1-mini" },
prompt: "A watercolor fox in the snow",
aspect: "16:9",
})
const { answers } = await ctx.experimental.generate.decisions({
model: { providerID: "opencode", id: "jev-1.13" },
input: [{ type: "text", text: "I was charged twice, please refund one." }],
questions: [{ type: "predicate", name: "refund", instructions: "Is this a refund request?" }],
})권한(Permissions)
작업을 수행하기 전에 권한을 요청합니다. assert는 저장된 승인을 포함해 세션의 권한 규칙을 평가하며, 규칙이 ask로 해석되면 사용자에게 확인을 요청합니다. 작업이 허용되면 resolve됩니다.
execute: async (input, context) => {
await ctx.permission.assert({
sessionID: context.sessionID,
agent: context.agent,
source: { type: "tool", messageID: context.messageID, id: context.id },
action: "deploy",
resources: [input.environment],
save: [input.environment],
})
return { content: await deploy(input.environment) }
}action과resources는 규칙과 대조됩니다. 하나라도deny이면 작업이 차단되고, 그렇지 않고ask가 하나라도 있으면 확인을 요청합니다.save는 사용자가 "항상 허용"을 선택할 때 저장할 패턴 목록입니다.agent는 어떤 에이전트의 규칙을 적용할지 지정하며 기본값은 세션의 에이전트입니다.source는 권한 프롬프트를 도구 호출에 연결합니다.metadata는 권한 프롬프트와evaluate훅에 추가 세부 정보를 전달합니다.
거부 규칙이나 피드백이 포함된 거절은 사유가 담긴 Tool.Error로 reject되어 모델이 이를 확인하고 계속 진행할 수 있습니다. 일반 거절은 현재 단계를 종료합니다. 이러한 오류는 도구 출력으로 반환하지 말고 그대로 전파(propagate)하세요.
대기 중인 권한 요청을 검사하거나 처리합니다.
const pending = await ctx.permission.list({ sessionID })
const request = await ctx.permission.get({ sessionID, requestID })
await ctx.permission.reply({ sessionID, requestID, decision: "once" })세션 범위의 권한 규칙을 교체합니다. 이 규칙은 에이전트의 규칙 이후에 평가되며 마지막으로 일치하는 규칙이 우선합니다. 하위 세션은 생성 시점에 적용 중인 규칙을 상속받습니다.
await ctx.session.update({
sessionID,
permissions: [{ action: "edit", resource: "/path/to/original/checkout/**", effect: "deny" }],
})세션(Sessions)
세션을 생성하거나 조회합니다.
const created = await ctx.session.create({ title: "Review" })
const session = await ctx.session.get({ sessionID })
const messages = await ctx.session.context({ sessionID })세션을 한 페이지씩 나열합니다. 다음 페이지를 가져오려면 cursor.next를 cursor로 다시 전달하세요. 커서가 필터를 기억하므로 필터를 반복 지정할 필요가 없습니다.
const page = await ctx.session.list({ directory: ctx.location.directory, limit: 20 })
const next = page.cursor.next ? await ctx.session.list({ cursor: page.cursor.next, limit: 20 }) : undefined이후 요청에 사용할 에이전트나 모델을 변경합니다.
await ctx.session.switchAgent({ sessionID, agent: "build" })
await ctx.session.switchModel({ sessionID, model: { providerID: "anthropic", id: "claude-sonnet-5-5" } })사용자 프롬프트, 일회성 생성 요청, 명령어 또는 합성(synthetic) 메시지를 전송합니다.
const prompt = await ctx.session.prompt({ sessionID, text: "Review the current changes" })
const generated = await ctx.session.generate({ sessionID, prompt: "Summarize this project" })
await ctx.session.command({ sessionID, name: "review", text: "--staged" })
const synthetic = await ctx.session.synthetic({ sessionID, text: "Deployment completed" })generate는 어시스턴트 메시지가 보고하는 것과 동일한 형식으로 text와 함께 호출의 tokens 및 cost를 반환합니다.
세션 이름을 변경하거나, 중단하거나, 완료될 때까지 대기합니다.
await ctx.session.update({ sessionID, title: "Review" })
await ctx.session.interrupt({ sessionID, resume: false })
await ctx.session.wait({ sessionID })remove로 임시 세션을 제거합니다. 제거 시 진행 중인 실행이 중지되고 하위 세션도 재귀적으로 삭제됩니다.
await ctx.session.remove({ sessionID })compact로 압축(compaction)을 요청합니다. 이 메서드는 완료된 요약이 아니라 수락된 수신함 항목을 반환하며, 기본적으로 다음 단계 경계에서 압축이 실행됩니다. 대신 대기열 순서를 유지하려면 delivery: "queue"를 전달하세요.
const compaction = await ctx.session.compact({ sessionID })instructions.entry로 키가 지정된 세션 지침 항목을 첨부, 나열 또는 제거할 수 있습니다. 항목은 세션 지침 내에 <context key="..."> 블록으로 렌더링되며, 업데이트나 제거는 메시지 턴을 대기열에 추가하지 않고 다음 단계 경계에서 반영됩니다.
await ctx.session.instructions.entry.put({ sessionID, key: "deploy-target", value: "production" })
const entries = await ctx.session.instructions.entry.list({ sessionID })
await ctx.session.instructions.entry.remove({ sessionID, key: "deploy-target" })레퍼런스
스키마: Session.Info (opens in a new tab), Model.Ref (opens in a new tab), Session.Inbox.User (opens in a new tab), Session.Inbox.Synthetic (opens in a new tab), InstructionEntry.Info (opens in a new tab)
interface SessionContext {
create(input?: SessionCreateInput, requestOptions?: RequestOptions): Promise<SessionInfo>
get(input: SessionGetInput, requestOptions?: RequestOptions): Promise<SessionInfo>
remove(input: SessionRemoveInput, requestOptions?: RequestOptions): Promise<void>
context(input: SessionContextInput, requestOptions?: RequestOptions): Promise<readonly SessionMessageInfo[]>
instructions: {
entry: {
list(
input: ExperimentalSessionInstructionsEntryListInput,
requestOptions?: RequestOptions,
): Promise<readonly InstructionEntryInfo[]>
put(input: ExperimentalSessionInstructionsEntryPutInput, requestOptions?: RequestOptions): Promise<void>
remove(input: ExperimentalSessionInstructionsEntryRemoveInput, requestOptions?: RequestOptions): Promise<void>
}
}
switchAgent(input: SessionSwitchAgentInput, requestOptions?: RequestOptions): Promise<void>
switchModel(input: SessionSwitchModelInput, requestOptions?: RequestOptions): Promise<void>
update(input: SessionUpdateInput, requestOptions?: RequestOptions): Promise<void>
move(input: SessionMoveInput, requestOptions?: RequestOptions): Promise<void>
prompt(input: SessionPromptInput, requestOptions?: RequestOptions): Promise<SessionInboxUser>
generate(input: SessionGenerateInput, requestOptions?: RequestOptions): Promise<{ text: string }>
command(input: SessionCommandInput, requestOptions?: RequestOptions): Promise<void>
compact(input: SessionCompactInput, requestOptions?: RequestOptions): Promise<SessionInboxCompaction>
synthetic(input: SessionSyntheticInput, requestOptions?: RequestOptions): Promise<SessionInboxSynthetic>
interrupt(input: SessionInterruptInput, requestOptions?: RequestOptions): Promise<{ interrupted: boolean }>
wait(input: ExperimentalSessionWaitInput, requestOptions?: RequestOptions): Promise<void>
}스킬(Skills)
특정 위치에서 사용 가능한 스킬을 읽습니다.
const skills = await ctx.skill.list()변환을 등록해 스킬을 검사, 추가, 업데이트 또는 제거합니다. get(id)는 현재 에디터 항목을 반환하며 해당 스킬이 없으면 undefined를 반환합니다.
import { Skill } from "@opencode/plugin"
await ctx.skill.transform((editor) => {
const skills = editor.list()
editor.add({
id: Skill.ID.make("review"),
name: Skill.Name.make("Review"),
description: "Review the current changes",
path: Skill.Info.fields.path.make("/workspace/.opencode/skills/review/SKILL.md"),
content: "Review the current changes for correctness and missing tests.",
})
const review = editor.get("review")
editor.update("review", (skill) => {
skill.autoinvoke = true
})
editor.remove("legacy")
})변환에서 사용하는 외부 상태가 변경되면 스킬을 다시 로드합니다.
await ctx.skill.reload()레퍼런스
스키마: Skill.Info (opens in a new tab)
interface SkillContext {
list(input?: SkillListInput, requestOptions?: RequestOptions): Promise<SkillListOutput>
transform(callback: (editor: SkillEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface SkillEditor {
list(): readonly SkillInfo[]
get(id: string): SkillInfo | undefined
add(skill: SkillInfo): void
update(id: string, update: (skill: SkillInfo) => void): void
remove(id: string): void
}스토리지(Storage)
플러그인 범위로 격리된 영구 JSON 값을 저장, 조회 또는 제거합니다.
await ctx.storage.set("settings", { strict: true })
const settings = await ctx.storage.get("settings")
await ctx.storage.remove("settings")선택적 커서 페이지네이션을 사용하여 접두사로 키를 스캔합니다.
const page = await ctx.storage.scan({ prefix: "cache/", limit: 100 })
const next = page.next레퍼런스
interface StorageContext {
get(key: string): Promise<Json | undefined>
set(key: string, value: Json): Promise<void>
remove(key: string): Promise<void>
scan(options: StorageScanOptions): Promise<StorageScanResult>
}
interface StorageScanOptions {
prefix: string
after?: string
limit?: number
}
interface StorageScanResult {
entries: readonly { key: string; value: Json }[]
next?: string
}도구(Tools)
변환 콜백 외부에서 모든 변환이 적용된 후 현재 등록된 도구를 읽습니다. 각 도구는 유효한 이름을 담은 id를 가집니다.
const tools = await ctx.tool.list()
const read = tools.find((tool) => tool.id === "read")Promise 플러그인을 포함해 동기식 변환을 통해 도구를 등록, 업데이트 및 제거합니다. 등록하거나 다시 로드하기 전에 외부 데이터를 로드하세요. 동일한 유효 도구 이름에 대해 나중에 등록된 유효한 정의가 이전 정의를 재정의합니다.
const registration = await ctx.tool.transform((editor) => {
editor.namespace({
name: "acme",
description: "Customer account tools",
})
editor.add({
name: "greeting",
description: "Create a greeting",
input: {
type: "object",
properties: { name: { type: "string" } },
required: ["name"],
additionalProperties: false,
},
options: { namespace: "acme", codemode: true },
execute: async (input, context) => {
await context.progress({ status: "greeting" })
return { content: `Hello ${(input as { name: string }).name}!` }
},
})
})Promise 도구 실행기는 context.signal을 받습니다. 세션을 중지할 때 기반 작업도 함께 중지되도록 fetch 같은 취소 가능한 작업에 이 시그널을 전달하세요.
execute: async ({ url }, context) => {
const response = await fetch(url, { signal: context.signal })
return { content: await response.text() }
}자유 형식(Freeform) 도구 입력
필수 문자열 필드가 정확히 하나뿐인 직접 도구의 경우 모델이 JSON 래퍼 없이 해당 문자열을 직접 작성하도록 허용할 수 있습니다. freeform을 { type: "text" }, { type: "regex", pattern } 또는 { type: "lark", grammar }로 설정하세요.
editor.add({
name: "ticket",
description: "Look up a ticket by ID",
options: { codemode: false },
input: Schema.Struct({ id: Schema.String }),
freeform: { type: "regex", pattern: "OPS-[0-9]+" },
execute: async ({ id }) => ({ content: await lookup(id) }),
})선택된 모델의 API가 models.dev에 regex를 나열하고 있으면 모델은 OPS-42를 직접 작성할 수 있습니다. 그렇지 않으면 Core는 freeform만 생략합니다. 모델은 여전히 ticket 도구를 가지며 {"id":"OPS-42"}로 호출합니다. 형식 목록이 없거나 비어 있으면 자유 형식을 지원하지 않음을 의미합니다. 어느 쪽이든 실행기는 { id }를 받습니다.
Code Mode(codemode: true) 내부에서 자유 형식 도구는 await tools.ticket("OPS-42")처럼 문자열을 직접 받으며, await tools.ticket({ id: "OPS-42" })도 함께 작동합니다.
콜백에 캡처된 소스 데이터가 변경된 후에는 reload()를 호출하세요. 리로드는 순서를 변경하지 않고 활성 변환을 재실행하며, 플러그인 setup을 다시 실행하지는 않습니다.
await ctx.tool.reload()현재 에디터에 있는 도구를 검사하려면 list()와 get()을 사용하세요. 도구는 유효한 이름을 담은 id를 가지며, 해당 ID가 없으면 get()은 undefined를 반환합니다. update와 remove에는 네임스페이스를 포함한 유효한 도구 이름(위 예시에서는 acme_greeting)을 사용하세요. 네임스페이스의 점(.)과 도구 이름의 지원되지 않는 문자는 _로 변환됩니다. 존재하지 않는 이름은 무시되며, 새 도구를 만들려면 완전한 정의와 함께 add를 호출해야 합니다. 업데이트 시 이름과 네임스페이스는 유지됩니다. 중첩된 값을 직접 변경하지 말고 새 스키마나 옵션을 할당하여 교체하세요. 잘못된 업데이트는 로그에 기록되고 이전 정의가 그대로 유지됩니다.
await ctx.tool.transform((editor) => {
editor.update("acme_greeting", (tool) => {
tool.description = "Greet the user by name"
})
editor.remove("acme_obsolete")
})업데이트와 제거는 MCP 카탈로그 새로 고침 이후를 포함해 추가(add) 작업과 함께 순서대로 재실행됩니다. 해당 등록을 해제(dispose)하면 변경 사항이 제거되고 나머지 변환에서 다시 빌드됩니다.
등록을 해제해 해당 변환을 제거하고 나머지 변환에서 다시 빌드하면 이전에 재정의했던 정의가 다시 나타납니다. 해제는 멱등(idempotent)하며 플러그인을 언로드할 때도 등록이 자동 해제됩니다.
await registration.dispose()각 모델 요청은 안정적이고 실행 가능한 도구 스냅샷을 캡처합니다. 이후의 변환, 리로드 및 해제는 향후 스냅샷에만 영향을 주며 이미 캡처된 정의, Code Mode 네임스페이스 설명 또는 실행기에는 영향을 주지 않습니다. 변경 가능한 플러그인 데이터를 클로저로 참조하는 실행기는 해당 데이터를 계속 관찰하므로, 특정 정의에 고정해야 하는 값은 변환 내부에서 캡처하세요.
레퍼런스
스키마: Tool.Content (opens in a new tab), Tool.TextContent (opens in a new tab), Tool.FileContent (opens in a new tab)
interface ToolContext {
list(): Promise<readonly (ToolInfo & { readonly id: string })[]>
transform(callback: (editor: ToolEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface ToolEditor {
list(): readonly (ToolInfo & { readonly id: string })[]
get(id: string): (ToolInfo & { readonly id: string }) | undefined
namespace(namespace: { name: string; description: string }): void
add(tool: ToolInfo): void
update(id: string, update: (tool: Types.Mutable<ToolInfo>) => void): void
remove(id: string): void
}VCS
저장소 정보, 작업 사본 상태 또는 파일 diff를 읽습니다.
const info = await ctx.vcs.get()
const branches = await ctx.vcs.branch.list({ search: "feature", limit: 10 })
const changes = await ctx.vcs.status()
const diff = await ctx.vcs.diff({ mode: "working", context: 3 })변환으로 위치 범위의 VCS 프로바이더를 등록합니다. 감지된 저장소 유형과 일치하는 프로바이더가 자동으로 선택되며, 다른 프로바이더를 선택하려면 editor.default.set을 사용하세요.
await ctx.vcs.transform((editor) => {
editor.add({
id: "custom",
name: "Custom VCS",
info: async () => ({ branch: { current: "feature", default: "main" } }),
branches: async (input, { signal }) => readBranches(input, signal),
status: async (scope, { signal }) => readStatus(scope.worktree, signal),
diff: async (input, { signal }) => readDiff(input, signal),
})
editor.default.set("custom")
})프로바이더 콜백은 현재 위치, 작업 사본 루트, 정규 프로젝트 루트 및 선택적 저장소 스토어를 받습니다. diff 콜백은 선택한 모드, 요청된 컨텍스트 및 출력 바이트 예산도 추가로 받습니다. 저장소 감지는 계속 OpenCode의 내장 Git 및 Mercurial 감지기를 사용합니다.
프로바이더는 선택적으로 scope.worktree에 저장소를 생성하는 init(scope, { signal })을 구현할 수 있습니다. 초기화는 감지된 저장소 유형이 아니라 ID(기본값 Git)로 프로바이더를 선택합니다. 해당 위치에 아직 저장소가 없더라도 init이 있는 프로바이더를 등록하세요. OpenCode는 디렉터리가 존재하고 저장소가 없는지 확인한 뒤 이를 호출하고 프로젝트를 다시 검색합니다. 새로운 저장소 형식은 이 콜백 외에도 별도의 감지 지원이 필요합니다.
레퍼런스
스키마: Vcs.Info (opens in a new tab), Vcs.FileStatus (opens in a new tab), FileDiff.Info (opens in a new tab)
interface VcsContext {
get(input?: VcsGetInput, requestOptions?: RequestOptions): Promise<VcsGetOutput>
branch: {
list(input?: VcsBranchListInput, requestOptions?: RequestOptions): Promise<VcsBranchListOutput>
}
status(input?: VcsStatusInput, requestOptions?: RequestOptions): Promise<VcsStatusOutput>
diff(input: VcsDiffInput, requestOptions?: RequestOptions): Promise<VcsDiffOutput>
transform(callback: (editor: VcsEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface VcsEditor {
add(definition: VcsDefinition): void
default: {
get(): string | undefined
set(providerID: string): void
}
}
interface VcsDefinition {
init?(scope: VcsScope, context: { signal: AbortSignal }): Promise<void>
// Existing info, branches, status, and diff callbacks are required.
}워크트리(Worktrees)
일반 플러그인 수명 주기를 사용해 로컬 워크트리 전략을 등록합니다. 이 예시의 구현 모듈은 옵션 검증과 백엔드의 create, remove, list 작업을 담당합니다.
import { Plugin } from "@opencode/plugin"
import { makeStrategy } from "./strategy"
export default Plugin.define({
id: "company.worktrees",
async setup(ctx) {
const strategy = makeStrategy(ctx.options)
await ctx.worktree.transform((editor) => {
editor.add(strategy)
})
},
})plugins를 통해 플러그인을 로드하고 공통 대상 디렉터리는 별도로 설정합니다.
{
"worktree": { "directory": "../worktrees" },
"plugins": [{ "package": "./plugins/worktrees", "options": {} }],
}- 전략을 추가하면 자동으로 선택됩니다. 마지막 활성 등록이 우선하므로 별도의 전략 선택 설정이 필요 없습니다.
- 등록을 해제하거나 플러그인을 언로드하면 이전 구현이 복원되며 최종적으로는 번들된 Git 전략으로 돌아갑니다.
reload()는 캡처된 입력이 변경된 후 변환을 재실행하며 플러그인setup을 다시 실행하지는 않습니다.- 생성 실패 시 Git으로 재시도하지 않습니다. 기존 워크트리는 기본값이 변경되더라도 기록된 소유자(owner)를 유지합니다.
- 전략은 로컬 디렉터리를 관리합니다. 원격 워크스페이스 프로비저닝은 이 인터페이스의 범위가 아닙니다.
작업(Operations)
플러그인 컨텍스트는 클라이언트와 동일한 프로젝트 기반 워크트리 작업을 노출합니다. 모든 작업에는 projectID가 필요합니다. list는 동일한 프로젝트의 알려진 체크아웃을 포함해 저장된 인벤토리만 읽으며 설정 로드, 플러그인 시작 또는 파일 시스템 변경 감지를 수행하지 않습니다.
const projectID = ctx.location.project.id
const created = await ctx.worktree.create({ projectID, name: "task" })
const inventory = await ctx.worktree.list({ projectID })
await ctx.worktree.refresh({ projectID })
await ctx.worktree.remove({ projectID, directory: created.directory, force: false })create는 프로젝트의 저장된 canonical 디렉터리에서 설정과 플러그인을 로드하고 선택된 전략을 사용합니다. 선택적으로 상위 directory, 소스 from, 시작 branch 및 name을 받습니다. 소스의 기본값은 정규(canonical) 체크아웃이며, from 재정의는 해당 프로젝트에 속해야 합니다. 소스를 선택해도 설정 루트는 변경되지 않습니다. 지정한 시작 ref는 선택된 전략이 지원해야 합니다(예: Rift의 네이티브 스냅샷 작업에는 ref 선택 옵션이 없음).
create와 refresh는 정규 체크아웃의 플러그인이 활성화될 때까지 기다립니다. 해당 체크아웃의 플러그인 setup 중에 호출된 경우에는 지금까지의 등록만 확인하며 자신의 활성화를 기다리지 않습니다.
remove는 정규 설정을 로드하고 플러그인을 활성화한 다음, 현재 선택된 기본값 대신 워크트리에 기록된 전략을 사용합니다. 기록된 소유자를 사용할 수 없으면 오류가 발생합니다. 워크트리 대상 경로는 다른 위치일 수 있습니다.
await ctx.worktree.remove({
directory: "/worktrees/task",
projectID,
force: false,
})소유자가 누락된 경우 Git으로 폴백하지 않고 제거가 실패합니다. 전략은 Core나 Git 오류에 의존하지 않고 강제 확인을 요청하기 위해 @opencode/plugin에서 Worktree를 import하여 new Worktree.OperationError({ message: "Uncommitted changes", forceRequired: true })를 throw할 수 있습니다.
refresh는 정규 설정을 로드하고 사용 가능한 모든 전략에 알려진 체크아웃 루트 전반에서 워크트리를 찾도록 요청합니다. 결과를 병합하고 기록된 소유권을 유지하며 누락된 디렉터리를 정리합니다. 실패한 검색 소스는 로그에 기록되고 나머지 소스는 계속 진행됩니다. 기존 디렉터리는 사용 가능한 어떤 전략도 보고하지 않더라도 저장된 상태로 유지됩니다. 변경된 인벤토리를 읽으려면 worktree.updated를 관찰하고 list를 다시 호출하세요.
await ctx.worktree.refresh({ projectID })레퍼런스
구현은 이름 지정과 충돌 처리가 끝난 권장 대상 경로를 전달받습니다. 백엔드가 자체 레이아웃을 요구할 경우 다를 수 있으므로 create에서 실제 디렉터리를 반환하세요. OpenCode는 반환된 경로를 해석하여 인벤토리, 시작 명령어 및 API 결과에 사용합니다. 반환된 디렉터리는 반드시 존재해야 합니다.
다른 대상을 선택하는 전략은 해당 위치의 이름 충돌을 직접 처리해야 합니다. OpenCode는 전략을 호출하기 전에 여전히 권장 상위 디렉터리를 생성합니다. list는 전략이 소유한 디렉터리와 저장소 루트만 보고해야 합니다.
interface WorktreeDefinition {
readonly id: string
create(
input: { sourceDirectory: string; directory: string; branch?: string },
context: { signal: AbortSignal },
): Promise<{ directory: string }>
remove(input: { directory: string; force: boolean }, context: { signal: AbortSignal }): Promise<void>
list(
sourceDirectory: string,
context: { signal: AbortSignal },
): Promise<readonly { directory: string; type: "root" | "worktree" }[]>
}
interface WorktreeEditor {
add(definition: WorktreeDefinition): void
}
interface WorktreeDomain extends WorktreeApi {
transform(callback: (editor: WorktreeEditor) => void): Promise<Registration>
reload(): Promise<void>
}Promise 콜백은 signal 취소와 협력해야 합니다. Effect 콜백은 Effect를 반환하며 대신 Effect 인터럽트를 사용합니다. 등록은 플러그인 런타임 범위에 유지되며, 프로젝트 작업은 정규 체크아웃의 레지스트리를 사용합니다. Core 설정 어댑터가 디렉터리 설정을 해당 레지스트리에 제공합니다.
웹 검색(Websearch)
웹 검색 프로바이더를 나열하거나 선택한 프로바이더를 통해 쿼리를 실행합니다.
const providers = await ctx.websearch.providers()
const results = await ctx.websearch.query({ query: "OpenCode plugins", providerID: "internal" })변환으로 프로바이더를 등록하고 기본 프로바이더를 선택합니다.
await ctx.websearch.transform((editor) => {
editor.add({
id: "internal",
name: "Internal search",
execute: async ({ query }, { signal }) => {
const response = await fetch(`https://search.example.com?q=${encodeURIComponent(query)}`, { signal })
const result = (await response.json()) as { url: string; title: string; content: string }
return [{ url: result.url, title: result.title, content: result.content, time: {} }]
},
})
editor.default.set("internal")
})웹 검색을 비활성화하려면 false를 선택하고, 외부 상태가 변경된 후에는 프로바이더를 다시 로드하세요.
await ctx.websearch.transform((editor) => editor.default.set(false))
await ctx.websearch.reload()레퍼런스
스키마: WebSearch.Provider (opens in a new tab), WebSearch.Result (opens in a new tab)
interface WebSearchContext {
providers(input?: WebsearchProvidersInput, requestOptions?: RequestOptions): Promise<WebsearchProvidersOutput>
query(input: WebsearchQueryInput, requestOptions?: RequestOptions): Promise<WebsearchQueryOutput>
transform(callback: (editor: WebSearchEditor) => void): Promise<Registration>
reload(): Promise<void>
}
interface WebSearchEditor {
add(provider: WebSearchDefinition): void
default: {
get(): string | false | undefined
set(providerID: string | false): void
}
}이벤트(Events)
연결된 서버의 공개 이벤트 스트림을 구독합니다. 플러그인 정리 시 스트림을 중단(abort)하세요. 예를 들어 ctx.event.subscribe({ types: ["config.updated"] })처럼 types를 전달하면 해당 이벤트 유형만 수신하며 이벤트 타입도 이에 맞게 추론됩니다. 플러그인은 서버 내부에서 실행되므로 SDK 클라이언트와 달리 server.connected를 수신하지 않습니다. 알 수 없는 유형 이름은 서버 로그에 경고가 기록되고 무시됩니다.
const controller = new AbortController()
void (async () => {
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
console.log(event.type)
}
})()
return () => controller.abort()레퍼런스
스키마: V2EventEncoded (opens in a new tab)
type EventType = Exclude<OpenCodeEvent["type"], "server.connected">
interface EventContext {
subscribe<Type extends EventType = EventType>(options?: {
types?: Type[]
signal?: AbortSignal
}): AsyncIterable<Extract<OpenCodeEvent, { type: Type }>>
}훅(Hooks)
훅은 실시간 작업을 가로챕니다. 해당 도메인에 훅을 등록하고 더 이상 필요하지 않을 때 반환된 등록 객체를 해제(dispose)하세요.
const registration = await ctx.session.hook("context", () => {})
await registration.dispose()여러 플러그인이 동일한 훅을 등록할 수 있습니다. OpenCode는 플러그인 순서대로 훅을 실행하므로 나중 훅은 이전 훅의 변경 사항을 확인할 수 있습니다.
세션(Sessions)
세션 훅은 프롬프트 수락, 모델 호출, 네이티브 HTTP 및 재시도를 가로챕니다.
포크(Forks)
fork 훅은 OpenCode가 기록을 복사한 뒤 fork 호출이 반환되기 전에 실행됩니다. sessionID는 새 세션을 식별합니다.
await ctx.session.hook("fork", ({ sessionID }) => console.log(sessionID))프롬프트 수락(Prompt admission)
첨부 파일 및 스킬 해석과 영구 수신함(inbox) 수락 이전에 들어오는 사용자 프롬프트를 가로챕니다.
await ctx.session.hook("prompt", (event) => {
event.prompt.text = event.prompt.text.replaceAll("company-secret", "[redacted]")
event.prompt.files ??= []
event.prompt.files.push({ uri: "file:///project/policy.md" })
event.metadata = { ...event.metadata, source: "company-policy" }
event.delivery = "queue"
})훅은 소유된 변경 가능한 초안(draft)을 전달받습니다.
prompt:text,files,agents의 에이전트 멘션 및 선택된skills를 포함합니다.metadata: 애플리케이션이 정의한 수락 메타데이터를 포함합니다.delivery: 기본값은"steer"이며"queue"로 변경할 수 있습니다.- 세션 및 메시지 ID는 읽기 전용이므로 훅이 수락 대상을 리디렉션할 수 없습니다.
훅에서 추가한 파일과 스킬은 일반 해석 및 검증 경로를 따릅니다. 텍스트를 다시 작성할 때는 더 이상 일치하지 않는 첨부 파일의 mention 오프셋을 업데이트하거나 제거하세요. 에이전트 멘션은 세션의 활성 에이전트를 전환하지 않습니다.
프롬프트 훅은 다음 조건에서 실행됩니다.
- 세션 위치의 플러그인이 준비된 후 등록 순서대로 실행됩니다.
session.prompt를 통해 제출되는 명령어는 이 훅을 실행합니다.- 합성(synthetic) 메시지, 셸 메시지, 압축 제어 및 이동 제어는 이 훅을 실행하지 않습니다.
- 모든 모델 호출 전이 아니라 수락 시점에 한 번 실행됩니다.
- 모델 해석이 수락 이후에 일어나므로 프로바이더 범위 지정은 사용할 수 없습니다.
편집 내용은 정규 영구 사용자 입력이 됩니다. 준비에 실패하거나 중단되면 OpenCode는 프롬프트를 수락하지 않습니다.
프롬프트 훅은 재시도에 안전(retry-safe)하게 유지하세요. 정확히 한 번(exactly-once) 실행되는 부수 효과 경계가 아닙니다.
- 이미 대기 중이거나 전달된 ID를 재시도하면 훅을 다시 실행하지 않고 원래 수락 결과를 반환합니다.
- 동시 제출 시 훅이 두 번 이상 실행될 수 있지만 가장 먼저 성공한 수락만 채택됩니다.
- 프롬프트 훅은 입력을 변환하며 타입이 지정된 거부 API를 노출하지 않습니다.
모델 요청(Model requests)
모델로 디스패치하기 직전에 조립된 시스템 지침, 메시지, 도구 또는 요청 옵션을 수정합니다. 세션이 발행하는 각 요청 종류마다 별도의 훅이 있으므로 플러그인이 에이전트 루프와 보조 요청을 다르게 처리할 수 있습니다.
context: 도구 기반 연속 실행을 포함한 에이전트 루프에 대해 실행됩니다.compaction: 체크포인트 요약에 대해 실행됩니다.messages는 요약 대상 대화록이며 훅 실행 후 OpenCode가 요약 프롬프트를 추가합니다.result를 설정하면 직접 압축을 기록하고 모델 호출을 건너뛸 수 있으며, 완료된 압축 메시지와 동일한 필드를 받습니다.generate: 일회성ctx.session.generate호출에 대해 실행됩니다.title: 제목 생성에 대해 실행됩니다.agent와tools가 없으며,result를 설정해 제목을 직접 제공할 수 있습니다.
await ctx.session.hook("context", (event) => {
event.system.push({ type: "text", text: "Keep the review focused on correctness." })
delete event.tools.write
event.options.temperature = 0.2
event.options.maxTokens = 8_000
})
await ctx.session.hook("compaction", async (event) => {
event.result = { summary: await summarize(event.messages) }
})변경 사항은 나가는 모델 호출에만 영향을 주며 저장된 기록이나 설정은 변경하지 않습니다. 모든 요청에 적용해야 하는 훅은 각 종류별로 모두 등록해야 합니다.
context, compaction, generate 훅의 메시지에는 저장된 메시지의 읽기 전용 metadata(예: prompt 훅에서 설정한 값)가 포함됩니다. 이 값은 모델로 전송되지 않습니다.
OpenCode의 지침을 담은 system 파트에는 metadata.experimental.instructions에 각 소스가 { key, text } 목록(예: core/date, core/environment)으로 나열되어 있어 훅이 소스를 구분할 수 있습니다. 이 목록은 복사본이므로 파트의 text를 편집해도 목록이 갱신되지 않습니다. 이 기능은 실험적이며 변경될 수 있습니다.
요청 재정의는 다음 규칙을 따릅니다.
options는 각 모델 호출마다 빈 상태로 시작하며 해석된 모델 설정을 포함하지 않습니다.- 타입이 지정된 키는 생성(generation) 설정이며, 그 외의 모든 키는 선택된 프로토콜에 프로바이더 옵션으로 전달됩니다.
- 훅은 등록 순서대로 실행되며 이전 훅이 설정한 재정의 값을 확인할 수 있습니다.
- 요청 재정의는 모델 기본값보다 우선하며, 모델 기본값은 라우트 기본값보다 우선합니다.
- 프로바이더 옵션 객체는 재귀적으로 병합되며, 배열과 스칼라 값은 이전 값을 교체합니다.
- 재정의 값을 삭제하거나
undefined로 설정하면 제거하는 것이 아니라 설정된 기본값으로 폴백합니다. - 원시 HTTP 본문 오버레이는 프로토콜 변환 이후에 적용되며 결과 필드를 재정의할 수 있습니다.
프로바이더 옵션(Provider options)
프로바이더 옵션은 원시 HTTP 본문 필드가 아니라 선택된 프로토콜의 의미적(semantic) 옵션 이름을 사용합니다. 프로바이더별 설정은 해당 프로바이더로 범위를 지정하세요. 예를 들어 OpenAI Responses는 reasoningEffort를 사용합니다.
await ctx.session.hook(
"context",
(event) => {
event.options.reasoningEffort = "high"
},
{ providerID: "openai" },
)생성 옵션은 선택된 프로토콜과 모델에 따라 다릅니다.
maxTokens는 의미적 출력 토큰 한도입니다.- Gemini는
topK를 지원하지만 OpenAI Responses는 이를 노출하지 않습니다.
모델 해석(Model resolve)
실험적 기능입니다. 세션이 요청에 사용할 모델을 해석할 때마다 다른 준비 작업 이전에 실행됩니다. model은 선택된 모델로 시작하며, 모델 선택기에서 숨겨진 모델을 포함해 같은 프로바이더의 다른 모델로 변경해 해당 요청을 처리할 수 있습니다. 세션은 원래 선택된 모델을 유지하고 해당 요청과 어시스턴트 메시지만 새 모델을 사용합니다. kind는 어떤 요청이 해석 중인지 알려주므로 라우터가 제목 생성을 건너뛰거나 압축 후 다시 라우팅할 수 있습니다. 다른 프로바이더의 모델을 지정하면 사용 불가 오류로 실패합니다.
await ctx.session.hook(
"experimental.model.resolve",
(event) => {
if (event.model.id === "auto" && event.kind !== "title")
event.model = { providerID: event.model.providerID, id: pick(event.sessionID) }
},
{ providerID: "acme" },
)모델 요청 설정(Model request)
모델 요청 설정을 수정하며 선택적으로 훅을 하나의 프로바이더로 범위 지정할 수 있습니다. 이벤트는 아래 HTTP 훅과 동일한 kind를 포함합니다.
await ctx.session.hook(
"model.request",
(event) => {
event.headers["x-plugin"] = "review"
},
{ providerID: "anthropic" },
)네이티브 HTTP
네이티브 프로바이더 요청 또는 응답을 수정합니다. 본문(body)은 일회성 스트림이므로 읽기 전에 복제하거나 교체해야 합니다.
두 훅 모두 세션이 발행하는 모든 요청에 대해 실행됩니다. event.kind는 요청을 발행한 흐름을 나타냅니다. 에이전트 루프는 "primary", 체크포인트 요약은 "compaction", 제목 생성은 "title", 일회성 ctx.session.generate 호출은 "generate"입니다. 보조 요청을 구분할 때 에이전트 ID 대신 이 값을 사용하세요.
await ctx.session.hook("http.request", (event) => {
event.request.headers.set("x-session-id", event.sessionID)
if (event.kind === "title") event.request.headers.set("x-priority", "background")
})
await ctx.session.hook("http.response", (event) => {
event.response = new Response(event.response.body, {
status: event.response.status,
headers: { ...Object.fromEntries(event.response.headers), "x-plugin": "review" },
})
})네이티브 WebSocket (실험적)
WebSocket으로 스트리밍하는 프로바이더는 세션당 하나의 연결을 열어 요청 간에 재사용하므로 http.request와 http.response에서는 해당 트래픽을 볼 수 없습니다. experimental.ws.handshake 훅은 연결을 선택하기 전에 모델 호출당 한 번 실행됩니다. HTTP 훅과 동일한 sessionID, agent, model, kind에 더해 연결 url과 headers를 포함합니다. url이나 headers를 변경하면 요청이 사용하는 소켓이 바뀌므로 순환된 Bearer 토큰이 새 연결을 열게 됩니다.
WebSocket 라우트가 폴백하는 HTTP 요청을 포함해 모든 HTTP 요청에서는 여전히 HTTP 훅이 실행됩니다.
await ctx.session.hook(
"experimental.ws.handshake",
async (event) => {
event.headers.authorization = `Bearer ${await mintToken(event.url)}`
delete event.headers["api-key"]
},
{ providerID: "azure" },
)experimental.ws.send와 experimental.ws.receive는 프레임 자체를 노출하며, HTTP 요청/응답 본문을 편집하는 것의 WebSocket 버전입니다. send는 프로바이더 드라이버가 아웃바운드 프레임을 만든 후 쓰기 전에 실행되고, receive는 드라이버가 관찰하기 전에 각 인바운드 프레임에서 실행됩니다. 둘 다 프레임을 문자열로 전달하며 훅이 반환될 때 frame에 들어 있는 내용을 전송하거나 전달합니다.
OpenCode는 재작성된 프레임의 유효성을 검사하지 않습니다. 드라이버가 프로바이더 응답으로 상태를 추적하므로 프로토콜 의미를 바꾸는 재작성은 HTTP 본문 재작성과 마찬가지로 플러그인의 책임입니다.
await ctx.session.hook(
"experimental.ws.send",
(event) => {
const body = JSON.parse(event.frame)
if (body.type === "response.create") body.metadata = { ...body.metadata, session: event.sessionID }
event.frame = JSON.stringify(body)
},
{ providerID: "openai" },
)
await ctx.session.hook("experimental.ws.receive", (event) => {
if (event.frame.includes('"type":"error"')) console.error(event.frame)
})이 훅들은 실험적이며 이름이나 형태가 변경될 수 있습니다.
재시도 정책(Retry policy)
프로바이더 실패에 대한 재시도 결정을 재정의하거나 지연 시간(밀리초)을 교체합니다. 이 훅은 OpenCode가 실패를 분류하고 정책을 제안한 후, 재시도가 예약되기 전에 실행됩니다. OpenCode가 내부적으로 다음 시도를 어떻게 수행하는지는 노출하지 않습니다.
await ctx.session.hook("retry", (event) => {
if (event.error.status === 429) {
event.decision = { retry: true, delay: 10_000 }
return
}
if (event.error.type === "provider.invalid-request" && event.attempt === 2) {
event.decision = { retry: true, delay: 0 }
return
}
if (event.attempt >= 3) event.decision = { retry: false }
})재시도 훅은 치명적 실패를 재시도 가능하게 만들거나 제안된 재시도를 거부하는 방식으로 OpenCode의 초기 decision을 변경할 수 있습니다.
재시도 결정은 다음 규칙을 따릅니다.
- 여러 훅이 등록 순서대로 실행되며 나중 훅은 현재 결정을 확인합니다.
- 내장된 최대 시도 횟수는 절대 상한으로 유지됩니다.
attempt는 검토 중인 물리적 시도 횟수입니다. 최초 요청이1이므로 첫 번째 재시도는2입니다.NaN, 무한대 또는 음수 같은 잘못된 지연 값은 계산된 기본 지연 값으로 폴백합니다.- 컨텍스트 오버플로 복구는 동일한 요청을 재시도하는 대신 대화를 압축하므로 별도로 처리됩니다.
세션 레퍼런스
import type { SessionPrompt } from "@opencode/plugin/promise/session"
interface SessionHooks {
prompt: SessionPrompt
context: SessionContextHook
compaction: SessionContextHook & { result?: SessionCompactionResult }
generate: SessionContextHook
title: SessionRequestHook & { result?: string }
"experimental.model.resolve": SessionModelResolveHook
"model.request": SessionModelRequestHook
"http.request": SessionHttpRequestHook
"http.response": SessionHttpResponseHook
"experimental.ws.handshake": SessionWebSocketHandshakeHook
"experimental.ws.send": SessionWebSocketSendHook
"experimental.ws.receive": SessionWebSocketReceiveHook
retry: SessionRetryHook
}
interface SessionModelResolveHook {
readonly sessionID: string
readonly agent: string
readonly kind: "primary" | "compaction" | "title" | "generate"
model: { providerID: string; id: string; variant?: string }
}
interface SessionWebSocketHandshakeHook {
readonly sessionID: string
readonly agent: string
readonly model: { providerID: string; id: string; variant?: string }
readonly kind: "primary" | "compaction" | "title" | "generate"
url: string
headers: Record<string, string>
}
interface SessionWebSocketSendHook {
readonly sessionID: string
readonly agent: string
readonly model: { providerID: string; id: string; variant?: string }
readonly kind: "primary" | "compaction" | "title" | "generate"
frame: string
}
interface SessionWebSocketReceiveHook {
readonly sessionID: string
readonly agent: string
readonly model: { providerID: string; id: string; variant?: string }
readonly kind: "primary" | "compaction" | "title" | "generate"
frame: string
}
type RetryDecision = { retry: false } | { retry: true; delay: number }
interface SessionRetryHook {
readonly sessionID: string
readonly agent: string
readonly model: { providerID: string; id: string; variant?: string }
readonly error: { type: string; message: string; status?: number }
readonly attempt: number
decision: RetryDecision
}
interface SessionRequestHook {
readonly sessionID: string
readonly model: { providerID: string; id: string; variant?: string }
system: SystemPart[]
messages: Message[]
options: {
maxTokens?: number
temperature?: number
topP?: number
topK?: number
frequencyPenalty?: number
presencePenalty?: number
seed?: number
stop?: string[]
} & Record<string, unknown>
}
interface SessionContextHook extends SessionRequestHook {
readonly agent: string
tools: Record<string, { description: string; input: JsonSchema }>
}
interface SessionCompactionResult {
summary: string
native?: Record<string, unknown>
metadata?: Record<string, unknown>
tokens?: TokenUsage
}
interface SessionHookContext {
hook<Name extends keyof SessionHooks>(
name: Name,
callback: (event: SessionHooks[Name]) => Promise<void> | void,
options?: Name extends "prompt" ? never : { providerID?: string },
): Promise<Registration>
}권한(Permissions)
설정된 규칙이 평가된 후 작업이 실행되거나 권한 프롬프트가 게시되기 전에 권한 결정을 검토합니다.
await ctx.permission.hook("evaluate", async (event) => {
if (event.action === "read") return
const messages = await ctx.session.context({ sessionID: event.sessionID })
const review = await ctx.generate.text({
model: { providerID: "anthropic", id: "claude-sonnet-5-5" },
prompt: buildSafetyPrompt({ messages, action: event.action, resources: event.resources }),
})
const decision = parseDecision(review.text)
event.effect = decision.effect
event.message = decision.reason
})권한 훅은 다음 규칙을 따릅니다.
- 훅은
allow및ask결정에 대해 실행됩니다. - 명시적으로 설정된
deny는 최종 결정이며 훅을 호출하지 않습니다. - 훅은
effect를allow,ask또는deny로 변경할 수 있습니다. message는 승격된 권한 요청에 표시되거나 거부 사유가 됩니다.
레퍼런스
interface PermissionEvaluation {
readonly sessionID: string
readonly agent?: string
readonly action: string
readonly resources: readonly string[]
readonly metadata?: Record<string, unknown>
readonly source?: { type: "tool"; messageID: string; id: string }
effect: "allow" | "ask" | "deny"
message?: string
}셸(Shell)
실행 전에 셸 명령어, 작업 디렉터리, 타임아웃, 실행 파일 또는 환경 변수를 수정합니다.
await ctx.shell.hook("create.before", (event) => {
event.timeout = Math.min(event.timeout, 60_000)
event.env.COMPANY_ENV = "development"
})레퍼런스
interface ShellHookContext {
hook(name: "create.before", callback: (event: ShellCreateBefore) => Promise<void> | void): Promise<Registration>
}
interface ShellCreateBefore {
command: string
cwd: string
timeout: number
shell: string
env: Record<string, string | undefined>
}도구(Tools)
실행 전에 도구 입력을 검사하거나 교체합니다.
await ctx.tool.hook("execute.before", (event) => {
if (event.tool === "read") console.log(event.input)
})실행 후 성공 결과 또는 실패를 검사합니다.
await ctx.tool.hook("execute.after", (event) => {
if (event.status === "completed") event.result = { ...event.result, metadata: { observed: true } }
if (event.status === "error") console.error(event.error.message)
})레퍼런스
interface ToolHooks {
"execute.before": ToolExecuteBefore
"execute.after": ToolExecuteCompleted | ToolExecuteFailed
}
interface ToolHookContext {
hook<Name extends keyof ToolHooks>(
name: Name,
callback: (event: ToolHooks[Name]) => Promise<void> | void,
): Promise<Registration>
}V1 지원
플러그인은 동일한 패키지 진입점에서 V1과 V2를 모두 지원할 수 있습니다. V1 server() 함수와 V2 setup() 함수를 모두 포함한 단일 객체를 기본 export하세요.
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은
server()를 호출하고 반환된 훅을 사용합니다. - V2는 기본 export의
id와setup()(Effect 플러그인의 경우effect())을 읽으며server()는 무시합니다. - 각 구현은 자체 API를 유지해야 합니다. export를 공유한다고 해서 V1 훅이 V2 훅으로 자동 변환되지는 않습니다.
server()와 별개로 V2 정의의 타입을 검사할 수 있도록Plugin.define(...)를 export 객체에 스프레드(spread)하세요.
V1 객체 형식은 OpenCode 1.18.29에서 지원됩니다. 이전 V1 릴리스에서는 대신 함수 export를 기대할 수 있으므로, 지원하려는 가장 오래된 V1 릴리스와 V2 모두에서 설치된 패키지를 테스트하세요.