サーバー
ツール、フック、インテグレーション、コマンド、エージェントを提供する OpenCode プラグインのサーバーパートを構築します。
プラグインのサーバーパートは OpenCode サーバー内で動作します。ツール、フック、インテグレーション、コマンド、エージェントによって OpenCode の動作を変更し、新機能を追加できます。プラグインパッケージの構成、読み込み、公開方法については概要を参照してください。
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "example",
async setup(ctx) {
await ctx.storage.set("loaded", true)
},
})ライフサイクル
プラグインの読み込み時に setup が実行されます。アンロード時に実行されるクリーンアップ関数を返すことができます。
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() などのレジストリ読み取りは、プラグインのセットアップ中を含め、それまでのすべての登録を即座に反映します。起動時のバッチ処理は更新通知をまとめるだけで、読み取り結果の反映を遅延させることはありません。一方、リソースステータス 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 指定で 1 件取得します。
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 を指定して 1 つのプロバイダーのメタデータを参照します。
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()アカウント固有の検出を行う場合は、インベントリの読み込みに使用した接続を 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")
})コールバックは生のモデルオーバーライドを編集します。プロバイダーのデフォルト設定は 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()変換を使ってコマンドを登録します。エグゼキューターはセッション、プロンプト添付ファイル、要求された配信モードを受け取ります。
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
}生成(実験的機能)
セッションの作成、ツール呼び出し、セッション履歴への追加を行わずに、選択したモデルで直接生成します。これらの API は今後変更される可能性があります。ctx.generate.text も引き続き動作しますが、非推奨となっており、代わりに 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フックに追加の詳細情報を渡します。
deny ルールまたはフィードバック付きの拒否では、理由を含む Tool.Error で reject されるため、モデルはその理由を確認して処理を継続できます。単純な拒否は現在のステップを終了させます。これらのエラーはツール出力として返すのではなく、そのまま伝播させてください。
保留中の権限リクエストを確認または解決します。
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 })セッションを 1 ページずつ一覧取得します。次のページを取得するには 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 はアシスタントメッセージと同じ形式で、呼び出しの tokens と cost に加えて text を返します。
セッションの名前変更、中断、待機を行います。
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 でコンパクションをリクエストします。返却されるのは完了済みの要約ではなく受理されたインボックス項目であり、デフォルトでは次のステップ境界でコンパクションが実行されます。キュー順序を維持したい場合は代わりに 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() }
}フリーフォームツール入力
必須の文字列フィールドを 1 つだけ持つダイレクトツールでは、モデルが 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() を呼び出してください。reload は順序を変えずにアクティブな変換を再実行するだけで、プラグインの setup 自体を再実行することはありません。
await ctx.tool.reload()エディター内の現在のツールを確認するには list() と get() を使用します。各ツールは実効名を格納する id を持ち、その ID が存在しない場合 get() は undefined を返します。update と remove には、名前空間を含む実効ツール名(上記例では acme_greeting)を指定してください。名前空間内のドットやツール名内の未サポート文字は _ に変換されます。存在しない名前は無視され、ツールを新規作成するには完全な定義とともに add を使用する必要があります。update は名前と名前空間を保持します。スキーマやオプションを変更する場合はネストされた値を直接変更せず、新しいオブジェクトを代入してください。無効な更新はログに記録され、直前の定義が維持されます。
await ctx.tool.transform((editor) => {
editor.update("acme_greeting", (tool) => {
tool.description = "Greet the user by name"
})
editor.remove("acme_obsolete")
})更新と削除は、MCP カタログの更新後を含め、追加処理とともに登録順で再実行されます。その登録を破棄(dispose)すると変更が取り消され、残りの変換から再構築されます。
登録を破棄するとその変換が取り除かれ、残りの変換から再構築されるため、上書きされていた以前の定義が再び有効になります。dispose はべき等であり、プラグインをアンロードした際にも登録は自動的に破棄されます。
await registration.dispose()各モデルリクエストは安定した実行可能なツールスナップショットを取得します。後続の変換、reload、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 検出器が使用されます。
プロバイダーはオプションで init(scope, { signal }) を実装し、scope.worktree 内にリポジトリを作成できます。初期化時は検出されたリポジトリ種別ではなく ID でプロバイダーが選択されます(デフォルトは Git)。ロケーションにまだリポジトリが存在しない場合でも init を備えたプロバイダーを登録できます。OpenCode はディレクトリが存在しリポジトリがないことを確認してから init を呼び出し、その後プロジェクトを再検出します。新しいリポジトリ形式にはこのコールバックとは別に検出サポートが必要です。
リファレンス
スキーマ: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)を保持します。
- ストラテジーはローカルディレクトリを管理します。リモートワークスペースのプロビジョニングはこのインターフェースの対象外です。
操作
プラグインコンテキストはクライアントと同じプロジェクトベースのワークツリー操作を公開します。すべての操作に 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 を受け付けます。ソースのデフォルトは正規チェックアウトであり、from を上書きする場合はそのプロジェクトに属するディレクトリである必要があります。ソースを変更しても設定ルートは変わりません。開始 ref を指定する場合は選択されたストラテジーがそれをサポートしている必要があります(たとえば Rift のネイティブスナップショット操作には ref 選択オプションがありません)。
create と refresh は正規チェックアウトのプラグインが有効化されるまで待機します。そのチェックアウトのプラグイン setup 中に行われた呼び出しは、その時点までに登録された内容を参照し、自身の有効化完了は待ちません。
remove は正規設定を読み込んでプラグインを有効化した後、現在選択されているデフォルトではなく、そのワークツリーに記録されたストラテジーを使用します。記録された所有者が利用できない場合はエラーになります。ワークツリーの作成先は別の場所にあっても構いません。
await ctx.worktree.remove({
directory: "/worktrees/task",
projectID,
force: false,
})所有者が欠落している場合、Git へフォールバックせず削除が失敗します。ストラテジーは @opencode/plugin から Worktree をインポートして new Worktree.OperationError({ message: "Uncommitted changes", forceRequired: true }) をスローすることで、Core や Git のエラーに依存せず強制削除の確認を要求できます。
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 の割り込み(interruption)を使用します。登録はプラグインランタイムにスコープされ、プロジェクト操作は正規チェックアウトのレジストリを使用します。Core の設定アダプターがディレクトリ設定をそのレジストリへ供給します。
Web 検索(Websearch)
Web 検索プロバイダーを一覧取得するか、選択したプロバイダー経由でクエリを実行します。
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 を選択して Web 検索を無効化するか、外部状態が変化した後にプロバイダーをリロードします。
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)
接続先サーバーのパブリックイベントストリームをサブスクライブします。プラグインのクリーンアップ時にストリームをアボートしてください。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)
フックは実行中のライブ操作をインターセプトします。該当ドメインにフックを登録し、不要になったら返却された登録(registration)を破棄してください。
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)
添付ファイルやスキルの解決および永続インボックスへの受理が行われる前に、受信したユーザープロンプトをインターセプトします。
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"
})フックは所有されたミュータブルなドラフトを受け取ります。
promptにはtext、files、agents内のエージェントメンション、選択されたskillsが含まれます。metadataにはアプリケーション定義の受理メタデータが含まれます。deliveryはデフォルトで"steer"であり、"queue"に変更できます。- セッション ID およびメッセージ ID は読み取り専用であり、フックから受理先を変更することはできません。
フックが追加したファイルやスキルは通常の解決・検証パスを通ります。テキストを書き換える場合は、一致しなくなった添付ファイルの mention オフセットを更新または削除してください。エージェントメンションによってセッションのアクティブエージェントが切り替わることはありません。
プロンプトフックは以下の条件で実行されます。
- セッションのロケーションプラグインの準備が完了した後、登録順に実行されます。
session.prompt経由で送信するコマンドではこのフックが実行されます。- 合成メッセージ、シェルメッセージ、コンパクション制御、移動制御では実行されません。
- フックは受理時に一度だけ実行され、モデル呼び出しのたびには実行されません。
- モデル解決は受理後に行われるため、プロバイダー単位のスコープ指定は利用できません。
ここでの編集内容が永続化される正規のユーザー入力になります。準備が失敗または中断された場合、OpenCode はプロンプトを受理しません。
プロンプトフックはリトライ安全(retry-safe)に実装してください。厳密に一度(exactly-once)の副作用境界ではありません。
- すでに保留中または配信済みの ID をリトライすると、フックを再実行せずに元の受理結果が返されます。
- 同時送信によってフックが複数回実行される場合がありますが、最初に受理に成功した 1 件のみが採用されます。
- プロンプトフックは入力を変換するためのものであり、型付きの拒否 API は公開しません。
モデルリクエスト
モデルへの送信直前に、組み立てられたシステム指示、メッセージ、ツール、またはリクエストオプションを変更できます。セッションが発行するリクエストの種類ごとに個別のフックが用意されているため、プラグインはエージェントループと補助リクエストを別々に扱えます。
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 に core/date や core/environment などの { key, text } の配列も保持されます。この配列はコピーであるため、パーツの text を編集しても配列は更新されません。これは実験的機能であり、今後変更される可能性があります。
リクエストオーバーライドは以下のルールに従います。
optionsはモデル呼び出しごとに空の状態で開始され、解決済みのモデル設定は含まれません。- 型付きキーは生成設定として扱われ、その他のキーは選択されたプロトコルにプロバイダーオプションとして渡されます。
- フックは登録順に実行され、先のフックによるオーバーライドを参照できます。
- リクエストオーバーライドはモデルデフォルトより優先され、モデルデフォルトはルートデフォルトより優先されます。
- プロバイダーオプションのオブジェクトは再帰的にマージされ、配列とスカラー値は先の値を置き換えます。
- オーバーライドを削除するか
undefinedを設定すると、設定を削除するのではなく設定済みのデフォルトにフォールバックします。 - 生の HTTP ボディオーバーレイはプロトコル変換(lowering)の後に適用され、変換後のフィールドを上書きできます。
プロバイダーオプション
プロバイダーオプションには生の HTTP ボディフィールドではなく、選択されたプロトコルのセマンティックなオプション名を使用します。プロバイダー固有の設定は対象プロバイダーにスコープしてください。たとえば 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)
モデルリクエスト設定を変更でき、必要に応じてフックを 1 つのプロバイダーに限定することもできます。イベントは下記の HTTP フックと同じ kind を持ちます。
await ctx.session.hook(
"model.request",
(event) => {
event.headers["x-plugin"] = "review"
},
{ providerID: "anthropic" },
)ネイティブ HTTP
ネイティブなプロバイダーリクエストまたはレスポンスを変更できます。これらのボディはワンショットストリームであるため、読み取る前に clone または置換してください。
どちらのフックもセッションが発行するすべてのリクエストに対して実行されます。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 経由でストリーミングするプロバイダーはセッションごとに 1 つの接続を開き、複数のリクエストで再利用するため、http.request と http.response はそのトラフィックを観測しません。experimental.ws.handshake フックは接続が選択される前のモデル呼び出しごとに 1 回実行され、HTTP フックと同じ sessionID、agent、model、kind に加え、接続先の url と headers を持ちます。url や headers を変更するとリクエストが使用するソケットが切り替わるため、ローテーションされた Bearer トークンで接続を再オープンできます。
WebSocket ルートがフォールバックしたリクエストを含め、すべての 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)
})これらのフックは実験的機能であり、名称や構造が変更される可能性があります。
リトライポリシー
プロバイダー障害に対するリトライ判定を上書きしたり、遅延時間(ミリ秒)を差し替えたりできます。このフックは 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() 関数を持つ単一のオブジェクトをデフォルトエクスポートしてください。
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 はデフォルトエクスポートの
idとsetup()(Effect プラグインの場合はeffect())を読み取り、server()を無視します。 - それぞれの実装は独自の API 上で維持してください。エクスポートを共有しても V1 フックが V2 フックへ自動変換されるわけではありません。
Plugin.define(...)をエクスポートオブジェクトへスプレッドすることで、V2 定義をserver()とは別に型チェックできます。
V1 のオブジェクト形式は OpenCode 1.18.29 でサポートされています。それより古い V1 リリースでは関数エクスポートが求められる場合があるため、サポート対象とする最古の V1 リリースおよび V2 の両方でインストール済みパッケージをテストしてください。