日本語
ドキュメント
OpenCode で開発
プラグイン
Effect プラグイン

Effect プラグイン

Effect ネイティブのプラグイン API を使用してサーバープラグインを開発します。

@opencode/plugin/effect は OpenCode プラグイン API の Effect ネイティブ版です。コンテキスト操作は Effect または Stream を返し、コールバックも Effect を返し、プラグインのライフタイムは Scope で表現されます。

OpenCode はプラグインおよびその node_modules 依存関係を読み込む際、実行時に effect(エクスポートされた effect/* サブパスを含む)と @opencode/plugin を提供します。プラグインにバンドルするのではなく、ローカルでの型チェックやテスト用に peer/dev 依存関係としてインストールしてください。

bun add --peer @opencode/plugin [email protected]

.opencode/plugins/ から Effect プラグインをエクスポートすると自動的に読み込まれます。

.opencode/plugins/concise/index.ts
import { Plugin } from "@opencode/plugin/effect"
import { Effect } from "effect"
 
export default Plugin.define({
  id: "example",
  effect: (ctx) =>
    Effect.gen(function* () {
      const storage = ctx.storage
      yield* storage.set("loaded", true)
    }),
})

公開パッケージや .opencode/plugins/ 外にあるプラグインディレクトリでは、他のサーバープラグインと同じ plugins 設定を使用します。

opencode.jsonc
{
  "$schema": "https://opencode.ai/config.json",
  "plugins": [
    "opencode-acme-effect-plugin",
    "[email protected]",
    "@acme/opencode-effect-plugin",
    "./plugins/local-effect",
    {
      "package": "@acme/opencode-effect-plugin",
      "options": { "agent": "reviewer", "strict": true },
    },
  ],
}

有効化、パッケージ解決、設定の優先順位については、プラグインの設定を参照してください。

plugins/local-effect/index.ts
import { Plugin } from "@opencode/plugin/effect"
import { Effect } from "effect"
 
export default Plugin.define({
  id: "local-effect",
  effect: (ctx) =>
    Effect.gen(function* () {
      yield* Effect.logInfo("Effect plugin loaded", { version: ctx.app.version })
    }),
})

ライフサイクル

プラグインの読み込み時に effect が実行されます。プラグインの再読み込みやアンロード時にそのスコープが閉じられるため、各種登録、スコープ付きファイバー、ファイナライザーはまとめて解放されます。

import { Plugin } from "@opencode/plugin/effect"
import { Effect } from "effect"
 
export default Plugin.define({
  id: "lifecycle",
  effect: (ctx) =>
    Effect.gen(function* () {
      yield* Effect.logInfo("loaded", { version: ctx.app.version })
      yield* Effect.addFinalizer(() => Effect.logInfo("unloaded"))
    }),
})

バックグラウンド処理にはスコープ付きファイバーを使用してください。クリーンアップ時にプラグインスコープがファイバーを中断します。

effect: (ctx) =>
  Effect.gen(function* () {
    const storage = ctx.storage
    yield* Effect.repeat(
      storage.set("heartbeat", { time: Date.now() }),
      { schedule: Schedule.spaced("1 minute") },
    ).pipe(Effect.forkScoped)
  }),

コンテキスト

コンテキストは接続先 OpenCode サーバー向けの Effect クライアントに加え、プラグイン専用の変換(transform)、フック、ストレージ、リロード、オプションを公開します。OpenCode の内部 Core サービスは公開されません。

effect: (ctx) =>
  Effect.gen(function* () {
    const plugins = ctx.plugin
    const active = yield* plugins.list().pipe(Effect.orDie)
    yield* Effect.logInfo("active plugins", { count: active.data.length })
  }),

プラグイン定義と完全なコンテキストは以下のように宣言されています。

interface Context {
  readonly app: App
  readonly location: Location.Info
  readonly options: PluginOptions
  readonly agent: AgentDomain
  readonly aisdk: AISDKDomain
  readonly command: CommandDomain
  readonly event: EventDomain
  readonly experimental: {
    readonly terminal: Pick<ExperimentalApi<unknown>["persistentPty"], "read">
    readonly generate: GenerateApi<unknown>
  }
  readonly integration: IntegrationDomain
  readonly mcp: MCPDomain
  readonly model: ModelDomain
  /** @deprecated Use `experimental.generate.text`. */
  readonly generate: Pick<ExperimentalGenerateApi<unknown>, "text">
  readonly permission: PermissionDomain
  readonly plugin: Pick<PluginApi<unknown>, "list">
  readonly provider: ProviderDomain
  readonly reference: ReferenceDomain
  readonly rpc: RpcDomain
  readonly session: SessionDomain
  readonly shell: ShellDomain
  readonly skill: SkillDomain
  readonly storage: StorageDomain
  readonly tool: ToolDomain
  readonly vcs: VcsDomain
  readonly websearch: WebSearchDomain
  readonly worktree: WorktreeDomain
}
 
interface Plugin<R = Scope.Scope> {
  readonly id: string
  readonly effect: (context: Context) => Effect.Effect<void, never, R>
}

オプション

opencode.json(c) のオブジェクト形式を使用してオプションを渡します。

opencode.jsonc
{
  "plugins": [
    {
      "package": "./plugins/company-effect",
      "options": { "strict": true },
    },
  ],
}

オプションは ctx.options から読み取ります。使用前に unknown 値の型を絞り込んでください。

plugins/company-effect/index.ts
import { Plugin } from "@opencode/plugin/effect"
import { Effect } from "effect"
 
export default Plugin.define({
  id: "company",
  effect: (ctx) =>
    Effect.gen(function* () {
      const strict = ctx.options.strict === true
      yield* Effect.logInfo("company plugin configured", { strict })
    }),
})

変換(Transforms)

変換はエディターを通じて状態を同期的に編集します。OpenCode は各ドメイン内で登録順にすべての変換を適用します。最初にソースがプロバイダーとイミュータブルなモデル定義を提供し、続いてモデル変換がアクティブプロバイダーの候補モデルを編集します。登録を yield することでプラグインスコープ内に保持されます。

plugins/models-effect/index.ts
import { Model, Plugin, Provider } from "@opencode/plugin/effect"
import { Effect } from "effect"
 
export default Plugin.define({
  id: "company.models",
  effect: (ctx) =>
    Effect.gen(function* () {
      const providerID = Provider.ID.make("acme")
      const models = [{ ...Model.Info.default(providerID, Model.ID.make("reasoner")), name: "Acme Reasoner" }]
      yield* 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,
        })
      })
    }),
})

モデル変換では、アクティブなプロバイダーの候補モデル全体に対してポリシーを適用できます。

plugins/model-budget-effect/index.ts
effect: (ctx) =>
  Effect.gen(function* () {
    yield* 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[] } のエントリを返します。プロバイダーの reload はモデル解決結果全体も無効化します。

plugins/models-effect/index.ts
effect: (ctx) =>
  Effect.gen(function* () {
    const provider = ctx.provider
    const source = { providers: yield* loadFromSource() }
 
    yield* provider.transform((editor) => {
      source.providers.forEach((provider) => editor.add(provider))
    })
 
    yield* Effect.repeat(
      Effect.gen(function* () {
        source.providers = yield* loadFromSource()
        yield* provider.reload()
      }),
      { schedule: Schedule.spaced("1 minute") },
    ).pipe(Effect.forkScoped)
  }),

API

エージェント(Agent)

すべてのエージェントを読み取るか、ID 指定で 1 件取得します。クライアントレスポンスには解決済みのロケーションとスキーマデータが含まれます。

effect: (ctx) =>
  Effect.gen(function* () {
    const agent = ctx.agent
    const agents = yield* agent.list().pipe(Effect.orDie)
    const build = yield* agent.get({ agentID: Agent.ID.make("build") }).pipe(Effect.orDie)
    yield* Effect.logInfo("agents", { count: agents.data.length, build: build.data.name })
  }),

エージェントの変換またはリロードを行います。

effect: (ctx) =>
  Effect.gen(function* () {
    const agent = ctx.agent
    yield* agent.transform((editor) => {
      editor.default("build")
      editor.update("build", (item) => (item.description = "Builds features and fixes bugs"))
      editor.remove("legacy")
    })
    yield* agent.reload()
  }),

スキーマ:Agent.Info (opens in a new tab)。

interface AgentEditor {
  list(): readonly Types.DeepMutable<Agent.Info>[]
  get(id: string): Types.DeepMutable<Agent.Info> | undefined
  default(id: string | undefined): void
  update(id: string, update: (agent: Types.DeepMutable<Agent.Info>) => void): void
  remove(id: string): void
}
 
interface AgentDomain extends AgentApi<unknown> {
  readonly transform: Transform<AgentEditor>
  readonly reload: () => Effect.Effect<void>
}

プロバイダー(Providers)

利用可能なプロバイダーを読み取るか、ID を指定して 1 つのプロバイダーのメタデータを参照します。

effect: (ctx) =>
  Effect.gen(function* () {
    const provider = ctx.provider
    const providers = yield* provider.list().pipe(Effect.orDie)
    const anthropic = yield* provider.get({ providerID: Provider.ID.make("anthropic") }).pipe(Effect.orDie)
    yield* Effect.logInfo("providers", {
      providers: providers.data.length,
      anthropic: anthropic.data.name,
    })
  }),

プロバイダー変換はプロバイダー設定とソース定義を編集します。エディターの読み取りには非アクティブなプロバイダーも含まれ、イミュータブルな定義を公開します。models.update はソースモデルの所有コピーを編集します。

effect: (ctx) =>
  Effect.gen(function* () {
    yield* 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 でソースインベントリを丸ごと置き換え、キャプチャした定義が変化した後に reload を呼び出します。

effect: (ctx) =>
  Effect.gen(function* () {
    const provider = ctx.provider
    const source = { models: yield* loadModels() }
    yield* provider.transform((editor) => editor.models.set("acme", source.models))
    source.models = yield* loadModels()
    yield* provider.reload()
  }),

アカウント固有のモデル検出を行う場合は、インベントリの読み込みに使用した接続を sourceConnection として渡します。別の接続が選択されている間、OpenCode はプラグインが最新のインベントリを公開するまでそのプロバイダーを除外します。

{/* prettier-ignore */}

const connection = yield* ctx.integration.connection.active("acme")
if (!connection) return
const inventory = yield* loadInventory(connection)
yield* 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 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: Types.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: Types.DeepMutable<Model.Info>) => void): void
    remove(providerID: string, modelID: string): void
  }
}
 
interface ProviderDomain extends ProviderApi<unknown> {
  readonly transform: Transform<ProviderEditor>
  readonly reload: () => Effect.Effect<void>
}

モデル(Models)

利用可能なモデルとデフォルト選択を読み取ります。

effect: (ctx) =>
  Effect.gen(function* () {
    const model = ctx.model
    const models = yield* model.list().pipe(Effect.orDie)
    const selected = yield* model.default().pipe(Effect.orDie)
    yield* Effect.logInfo("models", { count: models.data.length, selected: selected.data?.name })
  }),

モデル変換はアクティブなプロバイダーの候補モデルコレクション全体を編集します。無効化された候補もすべての変換が完了するまで編集可能であり、update でモデルを追加できるのは利用可能なプロバイダー配下のみです。

effect: (ctx) =>
  Effect.gen(function* () {
    yield* 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 はモデル変換の出力ではなく、非アクティブなテンプレートを含むイミュータブルなソース定義を読み取ります。

effect: (ctx) =>
  Effect.gen(function* () {
    const model = ctx.model
    yield* model.transform((editor) => {
      const source = editor.provider.get("anthropic")?.models.get("claude-sonnet-5-5")
      if (!source) return
      editor.update("anthropic", source.id, (draft) => {
        draft.limit.context = Math.min(draft.limit.context, source.limit.context)
      })
    })
    yield* model.reload()
  }),

スキーマ:Model.Info (opens in a new tab)。

interface ModelEditor {
  list(providerID?: string): readonly Types.DeepMutable<Model.Info>[]
  get(providerID: string, modelID: string): Types.DeepMutable<Model.Info> | undefined
  update(providerID: string, modelID: string, update: (model: Types.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
  }
}
 
interface ModelDomain extends ModelApi<unknown> {
  readonly transform: Transform<ModelEditor>
  readonly reload: () => Effect.Effect<void>
}

コマンド(Commands)

現在のロケーションで利用可能なコマンドを読み取ります。

effect: (ctx) =>
  Effect.gen(function* () {
    const command = ctx.command
    const commands = yield* command.list().pipe(Effect.orDie)
    yield* Effect.logInfo("commands", { names: commands.data.map((item) => item.name) })
  }),

現在のコマンド変換は追加専用(add-only)です。エグゼキューターはセッション、プロンプト添付ファイル、配信モードを受け取ります。

effect: (ctx) =>
  Effect.gen(function* () {
    const command = ctx.command
    const session = ctx.session
    yield* command.transform((editor) => {
      editor.add({
        name: "security-review",
        description: "Review changes for security issues",
        execute: (input) =>
          session.prompt({
            ...input.prompt,
            sessionID: input.sessionID,
            text: `Review these changes for security issues.\n\n${input.prompt.text}`,
            delivery: input.delivery,
          }).pipe(Effect.asVoid),
      })
    })
    yield* command.reload()
  }),

スキーマ:Command.Info (opens in a new tab)、Session.Inbox.Delivery (opens in a new tab)。

interface CommandInvocation {
  readonly sessionID: Session.ID
  readonly prompt: PromptInput.Prompt
  readonly delivery: SessionInbox.Delivery
}
 
interface CommandDefinition {
  readonly name: string
  readonly description?: string
  readonly execute: (input: CommandInvocation) => Effect.Effect<void, unknown>
}
 
interface CommandEditor {
  add(definition: CommandDefinition): void
}
 
interface CommandDomain extends Pick<CommandApi<unknown>, "list"> {
  readonly transform: Transform<CommandEditor>
  readonly reload: () => Effect.Effect<void>
}

インテグレーション(Integrations)

インテグレーションを読み取り、存在する場合はアクティブな認証情報を解決します。

effect: (ctx) =>
  Effect.gen(function* () {
    const integration = ctx.integration
    const integrations = yield* integration.list().pipe(Effect.orDie)
    const github = yield* integration.get({ integrationID: Integration.ID.make("github") }).pipe(Effect.orDie)
    const connection = yield* integration.connection.active("github")
    const credential = connection ? yield* integration.connection.resolve(connection).pipe(Effect.orDie) : undefined
    yield* Effect.logInfo("integration", {
      count: integrations.data.length,
      github: github.data.name,
      credential: credential?.type,
    })
  }),

接続 API を通じてキーで接続するか、OAuth 認証フローを実行します。

effect: (ctx) =>
  Effect.gen(function* () {
    const integration = ctx.integration
    const token = yield* Config.Redacted("GITHUB_TOKEN").pipe(Effect.orDie)
    yield* integration.connect
      .key({ integrationID: Integration.ID.make("github"), key: Redacted.value(token) })
      .pipe(Effect.orDie)
 
    const attempt = yield* integration.oauth
      .connect({
        integrationID: Integration.ID.make("acme"),
        methodID: Integration.MethodID.make("oauth"),
      })
      .pipe(Effect.orDie)
    const status = yield* integration.oauth
      .status({
        integrationID: Integration.ID.make("acme"),
        attemptID: attempt.data.attemptID,
      })
      .pipe(Effect.orDie)
    yield* Effect.logInfo("OAuth status", { status: status.data })
  }),

インテグレーションと認証方式を変換します。OAuth 方式のコールバックは Effect であり、スコープ付きリソースを取得できます。

effect: (ctx) =>
  Effect.gen(function* () {
    const integration = ctx.integration
    yield* integration.transform((editor) => {
      editor.update("acme", (item) => (item.name = "Acme"))
      editor.method.update({
        integrationID: "acme",
        method: { id: "device", type: "oauth", label: "Sign in with Acme" },
        authorize: () =>
          Effect.succeed({
            mode: "code",
            url: "https://acme.example/device",
            instructions: "Enter the displayed code",
            callback: (code) => exchangeCode(code),
          }),
      })
    })
    yield* 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)。

type IntegrationOAuthAuthorization = {
  readonly url: string
  readonly instructions: string
  readonly expiresAt?: number
} & (
  | { readonly mode: "auto"; readonly callback: Effect.Effect<Credential.OAuth, unknown> }
  | { readonly mode: "code"; readonly callback: (code: string) => Effect.Effect<Credential.OAuth, unknown> }
)
 
type IntegrationOAuthMethodRegistration = {
  readonly integrationID: string
  readonly method: IntegrationOAuthMethod
  readonly authorize: (answer: Form.Answer) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
  readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
  readonly label?: (credential: Credential.OAuth) => string | undefined
}
 
interface IntegrationEditor {
  list(): readonly IntegrationRef[]
  get(id: string): IntegrationRef | undefined
  update(id: string, update: (integration: IntegrationRef) => void): void
  remove(id: string): void
  readonly method: {
    list(integrationID: string): readonly IntegrationMethod[]
    update(input: IntegrationMethodRegistration): void
    remove(integrationID: string, method: IntegrationMethod): void
  }
}
 
interface IntegrationDomain extends Omit<IntegrationApi<unknown>, "wellknown"> {
  readonly transform: Transform<IntegrationEditor>
  readonly reload: () => Effect.Effect<void>
  readonly connection: {
    readonly active: (integrationID: string) => Effect.Effect<ConnectionInfo | undefined>
    readonly resolve: (connection: ConnectionInfo) => Effect.Effect<Credential.Value | undefined, unknown>
  }
}

MCP

MCP サーバーとその現在の接続状態を一覧表示します。

effect: (ctx) =>
  Effect.gen(function* () {
    const mcp = ctx.mcp
    const servers = yield* mcp.list().pipe(Effect.orDie)
    yield* Effect.logInfo("MCP servers", { count: servers.data.length })
  }),

プラグインは変換を通じてのみ MCP サーバーを管理します。サーバーの追加・置換には editor.set、設定変更には editor.update、削除には editor.remove を使用します。設定の参照には editor.list と editor.get を使用します。

effect: (ctx) =>
  Effect.gen(function* () {
    const mcp = ctx.mcp
    yield* 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() を呼び出して変換を再適用し、サーバーの状態を再調整してください。

effect: (ctx) =>
  Effect.gen(function* () {
    const mcp = ctx.mcp
    yield* mcp.reload()
  }),

スキーマ:Mcp.Server (opens in a new tab)、Mcp.LocalConfigEncoded (opens in a new tab)、Mcp.RemoteConfigEncoded (opens in a new tab)。

interface MCPEditor {
  list(): readonly [string, Types.DeepMutable<Mcp.ServerConfig>][]
  get(name: string): Types.DeepMutable<Mcp.ServerConfig> | undefined
  set(name: string, config: Mcp.ServerConfig): void
  update(name: string, update: (config: Types.DeepMutable<Mcp.ServerConfig>) => void): void
  remove(name: string): void
}
 
interface MCPDomain extends Pick<McpApi<unknown>, "list"> {
  readonly transform: Transform<MCPEditor>
  readonly reload: () => Effect.Effect<void>
}

プラグイン(Plugins)

現在のロケーションでアクティブ、失敗、または解決済みのプラグインを一覧表示します。

effect: (ctx) =>
  Effect.gen(function* () {
    const plugin = ctx.plugin
    const plugins = yield* plugin.list().pipe(Effect.orDie)
    yield* Effect.forEach(plugins.data, (item) => Effect.logInfo("plugin", item), { discard: true })
  }),

アクティブなプラグインのみが必要な場合は、Effect パイプライン内でスキーマ値をフィルタリングします。

effect: (ctx) =>
  Effect.gen(function* () {
    const plugin = ctx.plugin
    const active = yield* plugin.list().pipe(
      Effect.orDie,
      Effect.map((result) => result.data.filter((item) => item.state.status === "active")),
    )
    yield* Effect.logInfo("active plugin count", { count: active.length })
  }),

スキーマ:Plugin.Info (opens in a new tab)、Plugin.Source (opens in a new tab)。

interface PluginApi<E = never> {
  readonly list: PluginListOperation<E>
}
 
interface Context {
  readonly plugin: PluginApi<unknown>
}

リファレンス(References)

現在のロケーションで利用可能なリファレンスを読み取ります。

effect: (ctx) =>
  Effect.gen(function* () {
    const reference = ctx.reference
    const references = yield* reference.list().pipe(Effect.orDie)
    yield* Effect.logInfo("references", { count: references.data.length })
  }),

ローカルおよび Git のリファレンスを追加・削除し、外部状態が変化した後は reload を呼び出します。get(name) は現在設定されているソースを返し、その名前が存在しない場合は undefined を返します。

effect: (ctx) =>
  Effect.gen(function* () {
    const reference = ctx.reference
    yield* reference.transform((editor) => {
      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")
    })
    yield* reference.reload()
  }),

スキーマ:Reference.Info (opens in a new tab)、Reference.LocalSource (opens in a new tab)、Reference.GitSource (opens in a new tab)。

interface ReferenceEditor {
  add(name: string, source: ReferenceLocalSource | ReferenceGitSource): void
  remove(name: string): void
  list(): readonly (readonly [string, ReferenceLocalSource | ReferenceGitSource])[]
  get(name: string): ReferenceLocalSource | ReferenceGitSource | undefined
}
 
interface ReferenceDomain extends ReferenceApi<unknown> {
  readonly transform: Transform<ReferenceEditor>
  readonly reload: () => Effect.Effect<void>
}

セッション(Sessions)

セッションを作成または読み取り、以降の処理で使用するエージェントとモデルを選択します。

effect: (ctx) =>
  Effect.gen(function* () {
    const session = ctx.session
    const created = yield* session.create({ title: "Review" }).pipe(Effect.orDie)
    const current = yield* session.get({ sessionID: created.id }).pipe(Effect.orDie)
    yield* session.switchAgent({ sessionID: current.id, agent: Agent.ID.make("build") }).pipe(Effect.orDie)
    yield* session
      .switchModel({
        sessionID: current.id,
        model: { providerID: Provider.ID.make("anthropic"), id: Model.ID.make("claude-sonnet-5-5") },
      })
      .pipe(Effect.orDie)
  }),

プロンプト、一時的な生成リクエスト、コマンド、または合成メッセージ(synthetic)を送信します。

effect: (ctx) =>
  Effect.gen(function* () {
    const session = ctx.session
    const created = yield* session.create({ title: "Automation" }).pipe(Effect.orDie)
    yield* session.prompt({ sessionID: created.id, text: "Review the current changes" }).pipe(Effect.orDie)
    const summary = yield* session
      .generate({ sessionID: created.id, prompt: "Summarize this project" })
      .pipe(Effect.orDie)
    yield* session.command({ sessionID: created.id, name: "review", text: "--staged" }).pipe(Effect.orDie)
    yield* session
      .synthetic({ sessionID: created.id, text: `Summary generated: ${summary.text}`, resume: false })
      .pipe(Effect.orDie)
  }),

セッションを 1 ページずつ一覧取得します。次のページを取得するには、cursor.next を cursor として渡します。カーソルはフィルター条件を記憶しているため、条件を繰り返し指定する必要はありません。

effect: (ctx) =>
  Effect.gen(function* () {
    const page = yield* ctx.session.list({ directory: ctx.location.directory, limit: 20 }).pipe(Effect.orDie)
    const next = page.cursor.next
      ? yield* ctx.session.list({ cursor: page.cursor.next, limit: 20 }).pipe(Effect.orDie)
      : undefined
  }),

一時的なセッションを remove で削除します。削除を行うと進行中の実行が停止され、子セッションも再帰的に削除されます。

effect: (ctx) =>
  Effect.gen(function* () {
    const created = yield* ctx.session.create({ title: "Temporary worker" }).pipe(Effect.orDie)
    yield* ctx.session.remove({ sessionID: created.id }).pipe(Effect.orDie)
  }),

compact でコンパクションをリクエストします。返却されるのは完了済みの要約ではなく受理されたインボックス項目であり、デフォルトでは次のステップ境界でコンパクションが実行されます。キュー順序を維持したい場合は代わりに delivery: "queue" を渡してください。

effect: (ctx) =>
  Effect.gen(function* () {
    const created = yield* ctx.session.create({ title: "Review" }).pipe(Effect.orDie)
    const compaction = yield* ctx.session.compact({ sessionID: created.id }).pipe(Effect.orDie)
  }),

instructions.entry を使ってキー付きのセッション指示エントリを添付・一覧取得・削除できます。エントリはセッションの指示内に <context key="..."> ブロックとしてレンダリングされ、更新や削除はメッセージターンをキューに追加することなく次のステップ境界で通知されます。

effect: (ctx) =>
  Effect.gen(function* () {
    const created = yield* ctx.session.create({ title: "Review" }).pipe(Effect.orDie)
    yield* ctx.session.instructions.entry
      .put({ sessionID: created.id, key: "deploy-target", value: "production" })
      .pipe(Effect.orDie)
    const entries = yield* ctx.session.instructions.entry.list({ sessionID: created.id }).pipe(Effect.orDie)
    yield* ctx.session.instructions.entry.remove({ sessionID: created.id, key: "deploy-target" }).pipe(Effect.orDie)
  }),

スキーマ: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)。

type SessionDomain = Pick<
  SessionApi<unknown>,
  | "list"
  | "create"
  | "get"
  | "remove"
  | "switchAgent"
  | "switchModel"
  | "prompt"
  | "generate"
  | "command"
  | "compact"
  | "synthetic"
  | "interrupt"
  | "update"
  | "move"
  | "wait"
  | "context"
  | "instructions"
>

スキル(Skills)

現在のロケーションにあるスキルを読み取ります。

effect: (ctx) =>
  Effect.gen(function* () {
    const skill = ctx.skill
    const skills = yield* skill.list().pipe(Effect.orDie)
    yield* Effect.logInfo("skills", { ids: skills.data.map((item) => item.id) })
  }),

スキルの変換とリロードを行います。ブランド型(branded value)の作成には再エクスポートされた Effect スキーマコンストラクターを使用してください。get(id) は現在のエディターエントリを返し、スキルが存在しない場合は undefined を返します。

effect: (ctx) =>
  Effect.gen(function* () {
    const skill = ctx.skill
    yield* skill.transform((editor) => {
      editor.add(Skill.Info.make({
        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", (item) => (item.autoinvoke = true))
      editor.remove("legacy")
    })
    yield* skill.reload()
  }),

スキーマ:Skill.Info (opens in a new tab)。

interface SkillEditor {
  list(): readonly Types.DeepMutable<Skill.Info>[]
  get(id: string): Types.DeepMutable<Skill.Info> | undefined
  add(skill: Skill.Info): void
  update(id: string, update: (skill: Types.DeepMutable<Skill.Info>) => void): void
  remove(id: string): void
}
 
interface SkillDomain extends SkillApi<unknown> {
  readonly transform: Transform<SkillEditor>
  readonly reload: () => Effect.Effect<void>
}

ストレージ(Storage)

プラグイン ID ごとにスコープされた永続的な JSON 値を保存、読み取り、削除します。

effect: (ctx) =>
  Effect.gen(function* () {
    const storage = ctx.storage
    yield* storage.set("settings", { strict: true })
    const settings = yield* storage.get("settings")
    yield* Effect.logInfo("settings", { settings })
    yield* storage.remove("settings")
  }),

カーソルページネーションを使用してプレフィックス単位でキーをスキャンします。

effect: (ctx) =>
  Effect.gen(function* () {
    const storage = ctx.storage
    const first = yield* storage.scan({ prefix: "cache/", limit: 100 })
    const second = first.next
      ? yield* storage.scan({ prefix: "cache/", after: first.next, limit: 100 })
      : { entries: [] }
    yield* Effect.logInfo("cache entries", { count: first.entries.length + second.entries.length })
  }),

ストレージは Effect の JSON 型を受け付け、Effect を直接返します。

interface StorageDomain {
  readonly get: (key: string) => Effect.Effect<Schema.Json | undefined>
  readonly set: (key: string, value: Schema.Json) => Effect.Effect<void>
  readonly remove: (key: string) => Effect.Effect<void>
  readonly scan: (options: StorageScanOptions) => Effect.Effect<StorageScanResult>
}

ツール(Tools)

Effect の Schema を使用して型付きツールを登録します。エグゼキューターはデコード済みの入力を受け取り、型付きの出力・表示コンテンツ・メタデータを含む Effect を返します。

エディターは add、update、remove をサポートしています。変換コールバックは同期的である必要があり、Effect や Promise を返してはいけません。外部データは登録またはリロードの前に読み込んでください。OpenCode は新しいエディター上でアクティブな変換を登録順に再実行し、同じ実効ツール名に対しては後続の有効な登録が先の登録を上書きします。

effect: (ctx) =>
  Effect.gen(function* () {
    const tool = ctx.tool
    yield* tool.transform((editor) => {
      editor.namespace({
        name: "acme",
        description: "Customer account tools",
      })
      editor.add({
        name: "greeting",
        description: "Create a greeting",
        input: Schema.Struct({ name: Schema.String }),
        output: Schema.Struct({ greeting: Schema.String }),
        options: { namespace: "acme", codemode: true },
        execute: ({ name }, context) =>
          Effect.gen(function* () {
            yield* context.progress({ status: "greeting" })
            return { output: { greeting: `Hello ${name}!` } }
          }),
      })
    })
  }),

コールバックがキャプチャしているソースデータを変更した後は、yield* ctx.tool.reload() を呼び出してください。reload は順序を変えずにアクティブな変換を再実行するだけで、プラグインの effect 自体を再実行することはありません。

Effect ツールも Promise ツールと同じフリーフォーム入力宣言を受け付けます。モデルがその形式に対応していない場合、ツールは通常のオブジェクト入力を維持します。

各ツールは実効名を格納する id を持ち、該当 ID が存在しない場合 get() は undefined を返します。update および remove には、名前空間を含む実効ツール名(上記例では acme_greeting)を指定してください。名前空間内のドットやツール名内の未サポート文字は _ に変換されます。存在しない名前は無視され、ツールを新規作成するには完全な定義とともに add を使用する必要があります。update は名前と名前空間を保持します。スキーマやオプションを変更する場合はネストされた値を直接変更せず、新しいオブジェクトを代入してください。無効な更新はログに記録され、直前の定義が維持されます。

{/* prettier-ignore */}

yield* ctx.tool.transform((editor) => {
  editor.update("acme_greeting", (tool) => {
    tool.description = "Greet the user by name"
  })
  editor.remove("acme_obsolete")
})

更新と削除は、MCP カタログの更新後を含め、追加処理とともに登録順で再実行されます。

transform はスコープ付きの登録を返します。yield* registration.dispose を実行するとその変換が削除され、残りの変換から再構築されるため、上書きされていた以前の定義が再び有効になります。dispose はべき等であり、プラグインのスコープが閉じられると登録も自動的に破棄されます。

各モデルリクエストはツールのスナップショットを取得します。reload や dispose が影響するのは将来のスナップショットのみであり、既存のリクエストがすでに取得した定義やエグゼキューターには影響しません。ミュータブルなプラグインデータをクロージャで参照するエグゼキューターは引き続きそのデータを観測するため、特定の定義に値を固定したい場合は変換内で値をキャプチャしてください。

スキーマ:Tool.Content (opens in a new tab)、Tool.TextContent (opens in a new tab)、Tool.FileContent (opens in a new tab)。

interface ToolEditor {
  list(): readonly (Tool.Info & { readonly id: string })[]
  get(id: string): (Tool.Info & { readonly id: string }) | undefined
  namespace(namespace: { name: string; description: string }): void
  add<Input extends Tool.ValueSchema<any>, Output extends Tool.ValueSchema<any> | undefined>(
    tool: Tool.Info<Input, Output>,
  ): void
  update(id: string, update: (tool: Types.Mutable<Tool.Info>) => void): void
  remove(id: string): void
}
 
interface ToolDomain {
  readonly list: () => Effect.Effect<readonly (Tool.Info & { readonly id: string })[]>
  readonly transform: Transform<ToolEditor>
  readonly reload: () => Effect.Effect<void>
}

VCS

リポジトリ情報、作業コピーのステータス、ファイル差分(diff)を読み取ります。

effect: (ctx) =>
  Effect.gen(function* () {
    const vcs = ctx.vcs
    const info = yield* vcs.get().pipe(Effect.orDie)
    const branches = yield* vcs.branch.list({ search: "feature", limit: 10 }).pipe(Effect.orDie)
    const changes = yield* vcs.status().pipe(Effect.orDie)
    const diff = yield* vcs.diff({ mode: "working", context: 3 }).pipe(Effect.orDie)
    yield* Effect.logInfo("vcs", { branch: info.data.branch.current, files: changes.data.length })
  }),

スコープ付きの変換を通じてロケーション単位のプロバイダーを登録します。検出されたリポジトリ種別に一致するプロバイダーが自動選択されますが、editor.default.set を使って別のプロバイダーを選択することもできます。

effect: (ctx) =>
  Effect.gen(function* () {
    const vcs = ctx.vcs
    yield* vcs.transform((editor) => {
      editor.add({
        id: "custom",
        name: "Custom VCS",
        info: () => Effect.succeed({ branch: { current: "feature", default: "main" } }),
        branches: (input) => readBranches(input),
        status: (scope) => readStatus(scope.worktree),
        diff: (input) => readDiff(input),
      })
      editor.default.set("custom")
    })
  }),

プロバイダーのコールバックは、現在のロケーション、作業コピールート、正規プロジェクトルート、および任意のリポジトリストアを受け取ります。diff コールバックはさらに選択モード、要求コンテキスト行数、出力バイト上限も受け取ります。リポジトリ検出には引き続き OpenCode 組み込みの Git および Mercurial 検出器が使用されます。

プロバイダーはオプションで init(scope) を実装し、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 VcsEditor {
  add(definition: VcsDefinition): void
  readonly default: {
    get(): string | undefined
    set(selection: string): void
  }
}
 
interface VcsDomain extends Omit<VcsApi<unknown>, "init"> {
  readonly transform: Transform<VcsEditor>
  readonly reload: () => Effect.Effect<void>
}
 
interface VcsDefinition {
  readonly init?: (scope: VcsScope) => Effect.Effect<void, unknown>
  // Existing info, branches, status, and diff callbacks are required.
}

Web 検索(Websearch)

プロバイダー一覧を取得するか、選択したプロバイダーを通じてクエリを実行します。

effect: (ctx) =>
  Effect.gen(function* () {
    const websearch = ctx.websearch
    const providers = yield* websearch.providers().pipe(Effect.orDie)
    const results = yield* websearch
      .query({ query: "OpenCode plugins", providerID: WebSearch.ID.make("internal") })
      .pipe(Effect.orDie)
    yield* Effect.logInfo("websearch", { providers: providers.data.length, results: results.data.results.length })
  }),

Effect エグゼキューターを登録し、デフォルトプロバイダーを選択します。Web 検索を無効にするにはデフォルトに false を設定してください。

effect: (ctx) =>
  Effect.gen(function* () {
    const websearch = ctx.websearch
    yield* websearch.transform((editor) => {
      editor.add({
        id: "internal",
        name: "Internal search",
        execute: ({ query }) => searchInternal(query),
      })
      editor.default.set("internal")
    })
    yield* websearch.reload()
  }),

スキーマ:WebSearch.Provider (opens in a new tab)、WebSearch.Result (opens in a new tab)。

interface WebSearchDefinition {
  readonly id: string
  readonly name: string
  readonly execute: (input: WebSearch.ProviderInput) => Effect.Effect<readonly WebSearch.Result[], unknown>
}
 
interface WebSearchEditor {
  add(definition: WebSearchDefinition): void
  readonly default: {
    get(): string | false | undefined
    set(selection: string | false): void
  }
}
 
interface WebSearchDomain extends WebsearchApi<unknown> {
  readonly transform: Transform<WebSearchEditor>
  readonly reload: () => Effect.Effect<void>
}

イベント(Events)

パブリックサーバーイベントのサブスクリプションは Effect の Stream です。自動的に割り込み・停止されるよう、コンシューマーはプラグインスコープ内でフォークしてください。

effect: (ctx) =>
  Effect.gen(function* () {
    const event = ctx.event
    yield* event.subscribe().pipe(
      Stream.tap((item) => Effect.logDebug("OpenCode event", { type: item.type })),
      Stream.runDrain,
      Effect.forkScoped,
    )
  }),

必要なイベントタイプのみを受信するには types を渡します。Stream は一致する型に絞り込まれるため、型ガードは不要です。

effect: (ctx) =>
  Effect.gen(function* () {
    const event = ctx.event
    yield* event.subscribe({ types: ["config.updated"] }).pipe(
      Stream.runForEach(() => Effect.logInfo("configuration changed")),
      Effect.forkScoped,
    )
  }),

スキーマ:V2EventEncoded (opens in a new tab)。

type EventType = Exclude<OpenCodeEvent["type"], "server.connected">
 
interface EventDomain {
  readonly subscribe: <Type extends EventType = EventType>(input?: {
    readonly types?: ReadonlyArray<Type>
  }) => Stream.Stream<Extract<OpenCodeEvent, { type: Type }>, unknown>
}

フック(Hooks)

フックは実行中のライブ操作をインターセプトします。複数のプラグインが同じフックを登録でき、OpenCode はプラグイン順に実行するため、後続のフックは先のフックによる変更結果を参照できます。登録はプラグインスコープの存続中ずっと有効です。

effect: (ctx) =>
  Effect.gen(function* () {
    const session = ctx.session
    yield* session.hook("context", () => Effect.void)
  }),

セッション(Sessions)

モデルへの送信直前に、組み立てられたシステム指示、メッセージ、ツールを変更できます。context はエージェントループに対して実行され、compaction、generate、title はそれぞれの補助リクエストに対して実行されます。compaction と title はモデル呼び出しをスキップする result を受け付けます。

effect: (ctx) =>
  Effect.gen(function* () {
    const session = ctx.session
    yield* session.hook("context", (event) =>
      Effect.sync(() => {
        event.system.push({ type: "text", text: "Keep the review focused on correctness." })
        delete event.tools.write
      }),
    )
    yield* session.hook("compaction", (event) =>
      Effect.map(summarize(event.messages), (summary) => {
        event.result = { summary }
      }),
    )
  }),

context、compaction、generate フック内のメッセージは、保存済みメッセージの読み取り専用 metadata(たとえば prompt フックが設定した内容)を保持しています。このメタデータはモデルには送信されません。

OpenCode の指示を保持する system パーツでは、フックが各ソースを区別できるよう、metadata.experimental.instructions に core/date や core/environment などの { key, text } の配列も保持されます。この配列はコピーであるため、パーツの text を編集しても配列は更新されません。これは実験的機能であり、今後変更される可能性があります。

モデルリクエスト設定を変更でき、必要に応じてフックを 1 つのプロバイダーに限定することもできます。イベントは下記の HTTP フックと同じ kind を持ちます。

effect: (ctx) =>
  Effect.gen(function* () {
    const session = ctx.session
    yield* session.hook(
      "model.request",
      (event) => Effect.sync(() => (event.headers["x-plugin"] = "review")),
      { providerID: "anthropic" },
    )
  }),

ネイティブなプロバイダーリクエストまたはレスポンスを変更できます。これらのボディはワンショットストリームであるため、読み取る前に clone または置換してください。どちらのフックもセッションが発行するすべてのリクエストに対して実行され、発行元のフローに応じて event.kind は "primary"、"compaction"、"title"、"generate" のいずれかになります。

effect: (ctx) =>
  Effect.gen(function* () {
    const session = ctx.session
    yield* session.hook("http.request", (event) =>
      Effect.sync(() => {
        event.request.headers.set("x-session-id", event.sessionID)
        if (event.kind === "title") event.request.headers.set("x-priority", "background")
      }),
    )
    yield* session.hook("http.response", (event) =>
      Effect.sync(() => {
        event.response = new Response(event.response.body, {
          status: event.response.status,
          headers: { ...Object.fromEntries(event.response.headers), "x-plugin": "review" },
        })
      }),
    )
  }),

WebSocket 経由でストリーミングするプロバイダーはセッションごとに 1 つの接続を再利用するため、HTTP フックはそのトラフィックを観測しません。実験的な experimental.ws.handshake フックは、接続が選択される前のモデル呼び出しごとに 1 回実行され、接続先の url と headers を公開します。どちらかを変更するとソケットが再オープンされます。なお、WebSocket ルートがフォールバックした HTTP リクエストに対しては引き続き HTTP フックが実行されます。

effect: (ctx) =>
  Effect.gen(function* () {
    yield* ctx.session.hook(
      "experimental.ws.handshake",
      (event) =>
        Effect.gen(function* () {
          event.headers.authorization = `Bearer ${yield* mintToken(event.url)}`
          delete event.headers["api-key"]
        }),
      { providerID: "azure" },
    )
  }),

experimental.ws.send と experimental.ws.receive はフレームそのものを公開します。send はプロバイダードライバーが送信フレームを構築した直後に実行され、receive はドライバーが受信フレームを処理する直前に各フレームごとに実行されます。フック終了時点で frame に格納されている値がそのままネットワーク送信されるかドライバーに渡されます。OpenCode はその内容を検証しません。

effect: (ctx) =>
  Effect.gen(function* () {
    yield* ctx.session.hook(
      "experimental.ws.send",
      (event) =>
        Effect.sync(() => {
          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" },
    )
  }),

プロバイダー障害時のリトライ判定を上書きしたり、遅延時間(ミリ秒)を差し替えたりできます。このフックは OpenCode が障害を分類してポリシーを提案した後、実際にリトライがスケジュールされる前に実行されます。OpenCode が内部で次の試行をどのように実行するかは公開されません。

effect: (ctx) =>
  Effect.gen(function* () {
    yield* ctx.session.hook("retry", (event) =>
      Effect.sync(() => {
        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 }
      }),
    )
  }),

初期値の decision は OpenCode の標準ポリシーであるため、フックによって通常は終了扱いとなるプロバイダー障害をリトライ可能にしたり、提案されたリトライを拒否したりできます。複数のフックは登録順に実行され、後続のフックは最新の decision を参照します。組み込みの最大試行回数は引き続きハードリミットとして機能します。attempt はこれから提案されている物理試行回数であり、初回リクエストが 1、最初のリトライが 2 となります。無効な遅延値(NaN、無限大、負の値)は計算済みの遅延にフォールバックします。コンテキストオーバーフローからの回復は同じリクエストをリトライする代わりに会話をコンパクト化するため、別枠のまま扱われます。

リファレンス

interface SessionHooks {
  readonly context: SessionContext
  readonly compaction: SessionCompaction
  readonly generate: SessionGenerate
  readonly title: SessionTitle
  readonly "model.request": SessionModelRequest
  readonly "http.request": SessionHttpRequest
  readonly "http.response": SessionHttpResponse
  readonly "experimental.ws.handshake": SessionWebSocketHandshake
  readonly "experimental.ws.send": SessionWebSocketSend
  readonly "experimental.ws.receive": SessionWebSocketReceive
  readonly retry: SessionRetry
}
 
type RetryDecision = { retry: false } | { retry: true; delay: number }
 
interface SessionRetry {
  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 SessionHookDomain {
  readonly hook: ModelHooks<SessionHooks>
}

シェル(Shell)

実行前にシェルコマンド、作業ディレクトリ、タイムアウト、実行ファイル、または環境変数を変更できます。

effect: (ctx) =>
  Effect.gen(function* () {
    const shell = ctx.shell
    yield* shell.hook("create.before", (event) =>
      Effect.sync(() => {
        if (event.command === "npm") event.command = "bun"
        event.timeout = Math.min(event.timeout, 60_000)
        event.env.COMPANY_ENV = "development"
      }),
    )
  }),

リファレンス

interface ShellCreateBefore {
  command: string
  cwd: string
  timeout: number
  shell: string
  env: Record<string, string | undefined>
}
 
interface ShellHooks {
  readonly "create.before": ShellCreateBefore
}
 
interface ShellHookDomain {
  readonly hook: Hooks<ShellHooks>
}

ツール(Tools)

事前フック(before hook)では入力を差し替えたり、Tool.Error で失敗させたりできます。

effect: (ctx) =>
  Effect.gen(function* () {
    const tool = ctx.tool
    yield* tool.hook("execute.before", (event) =>
      event.tool === "write"
        ? Effect.fail(new Tool.Error({ message: "Writes are disabled" }))
        : Effect.logDebug("tool input", { tool: event.tool, input: event.input }),
    )
  }),

事後フック(after hook)では成功結果や失敗内容を参照または差し替えられます。

effect: (ctx) =>
  Effect.gen(function* () {
    const tool = ctx.tool
    yield* tool.hook("execute.after", (event) => {
      if (event.status === "error") return Effect.logWarning("tool failed", { message: event.error.message })
      return Effect.sync(() => {
        event.result = { ...event.result, metadata: { observed: true } }
      })
    })
  }),

リファレンス

interface ToolHooks {
  readonly "execute.before": ToolExecuteBefore
  readonly "execute.after": ToolExecuteAfter
}
 
interface ToolFailures extends Record<keyof ToolHooks, unknown> {
  readonly "execute.before": Tool.Error
  readonly "execute.after": never
}
 
interface ToolHookDomain {
  readonly hook: Hooks<ToolHooks, ToolFailures>
}

共通の登録型は、どの操作がプラグインスコープを必要とするかを示しています。

interface Registration {
  readonly dispose: Effect.Effect<void>
}
 
type Hooks<Spec, Failures extends Record<keyof Spec, unknown> = Record<keyof Spec, never>> = <Name extends keyof Spec>(
  name: Name,
  callback: (input: Spec[Name]) => Effect.Effect<void, Failures[Name]>,
) => Effect.Effect<Registration, never, Scope.Scope>
 
type Transform<Input> = (callback: (input: Input) => void) => Effect.Effect<Registration, never, Scope.Scope>

公開

パッケージプラグインでもローカルの Effect プラグインと同じデフォルトエクスポートを使用します。メインエントリーポイントから Effect 実装をエクスポートし、effect を peerDependencies として宣言してください。devDependencies では、開発時に 1 つのコピーのみがインストールされるよう @opencode/plugin が使用するバージョンを固定してください。

package.json
{
  "name": "opencode-acme-effect-plugin",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": "./src/index.ts"
  },
  "dependencies": {
    "@opencode/plugin": "latest"
  },
  "peerDependencies": {
    "effect": "^4.0.1"
  },
  "devDependencies": {
    "effect": "4.0.1"
  }
}

OpenCode は effect、エクスポートされた effect/* サブパス、および @opencode/plugin のインポート(プラグインの node_modules 内依存関係からのインポートを含む)をホスト側のランタイムインスタンスへリダイレクトするため、ファイバー、ロガー、Schema パーサーが単一のランタイムコピーを共有します。

  • 公開するプラグイン成果物に effect をバンドルしないでください。バンドラーでビルドする場合は、effect と effect/* を external に指定してください。
  • プラグインおよびその node_modules 依存関係は、常にホスト OpenCode リリースの effect インスタンス上で実行されます。対象とする OpenCode リリースと互換性のある effect API とモジュールパスを使用してください。別の effect メジャーバージョン(Effect 3 など)向けに構築された依存関係にもホストの effect が供給されるためサポートされません。
  • 提供されるのはパブリックな effect サブパスのみです。Effect の非公開 internal モジュールをインポートするプラグインは、該当パスを示すエラーで読み込みに失敗します。
  • コンパイル済みの OpenCode バイナリには、Effect の HTTP API ドキュメントページで使用される Scalar および Swagger UI アセットは含まれていません。プラグインからそれらのページを提供すると代わりに案内メッセージが表示されます。

パッケージエントリーポイントは、effect 関数を持つ Plugin.define をエクスポートします。

src/index.ts
import { Plugin } from "@opencode/plugin/effect"
import { Effect } from "effect"
 
export default Plugin.define({
  id: "acme.published",
  effect: (ctx) =>
    Effect.gen(function* () {
      const storage = ctx.storage
      yield* storage.set("installed", true)
    }),
})

対象とする OpenCode リリースと互換性のあるバージョンを使用し、ワークスペースリンクされたコピーだけでなくインストール済みのパッケージでもテストしてください。

bun pm pack
bun add ./opencode-acme-effect-plugin-1.0.0.tgz