한국어
문서
OpenCode에서 빌드하기
플러그인
Effect 플러그인

Effect 플러그인

Effect 네이티브 플러그인 API로 서버 플러그인을 작성합니다.

@opencode/plugin/effect는 OpenCode 플러그인 API의 Effect 네이티브 버전입니다. 컨텍스트 작업은 Effect 또는 Stream을 반환하고, 콜백은 Effect를 반환하며, 플러그인 수명 주기는 Scope로 표현됩니다.

OpenCode는 플러그인과 그 node_modules 의존성을 로드할 때 런타임에 effect(export된 effect/* 하위 경로 포함)와 @opencode/plugin을 제공합니다. 플러그인에 번들링하지 말고 로컬 타입 검사 및 테스트를 위해 peer/dev 의존성으로 설치하세요.

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

자동 로드를 위해 .opencode/plugins/에서 Effect 플러그인을 export합니다.

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

수명 주기(Lifecycle)

effect는 플러그인이 로드될 때 실행됩니다. 플러그인이 다시 로드되거나 언로드되면 해당 Scope가 닫히므로 등록, 범위 지정 파이버(scoped fiber) 및 파이널라이저(finalizer)가 함께 해제됩니다.

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

백그라운드 작업에는 범위 지정 파이버를 사용하세요. 정리 중에 플러그인 Scope가 해당 파이버를 인터럽트합니다.

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 클라이언트와 함께 플러그인 전용 변환, 훅, 스토리지, 리로드 및 옵션을 노출합니다. 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하면 플러그인 Scope 내에 유지됩니다.

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[] } 항목을 반환하며, 프로바이더 리로드는 전체 모델 결과도 함께 무효화합니다.

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로 단일 에이전트를 가져옵니다. 클라이언트 응답에는 해석된 위치와 스키마 데이터가 포함됩니다.

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로 단일 프로바이더의 메타데이터를 조회합니다.

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으로 소스 인벤토리를 교체한 다음 캡처된 정의가 변경되면 다시 로드합니다.

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

계정별 검색(discovery)의 경우 인벤토리를 로드하는 데 사용한 연결을 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")
    })
  }),

콜백은 원시(raw) 모델 재정의를 편집합니다. 프로바이더 기본값은 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)

통합 목록을 읽고 활성 자격 증명이 존재하면 이를 해석(resolve)합니다.

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는 변환된 설정에 따라 서버 수명 주기를 자동으로 조정합니다.

변환에서 사용하는 외부 상태가 변경된 후 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 레퍼런스를 추가하거나 제거한 뒤 외부 상태가 변경되면 다시 로드합니다. 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)
  }),

세션을 한 페이지씩 나열합니다. 다음 페이지를 가져오려면 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로 압축(compaction)을 요청합니다. 완료된 요약이 아니라 수락된 수신함 항목을 반환하며, 기본적으로 다음 단계 경계에서 압축이 실행됩니다. 대신 대기열 순서를 유지하려면 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 values)에는 다시 export된 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()를 호출하세요. 리로드는 순서를 변경하지 않고 활성 변환을 재실행하며 플러그인 effect를 다시 실행하지는 않습니다.

Effect 도구는 Promise 도구와 동일한 자유 형식 입력 선언을 지원합니다. 모델이 해당 형식을 지원하지 않는 경우 도구는 일반 객체 입력을 유지합니다.

도구는 유효한 이름을 담은 id를 가지며, 해당 ID가 없으면 get()은 undefined를 반환합니다. update와 remove에는 네임스페이스를 포함한 유효한 도구 이름(위 예시에서는 acme_greeting)을 사용하세요. 네임스페이스의 점(.)과 도구 이름의 지원되지 않는 문자는 _로 변환됩니다. 존재하지 않는 이름은 무시되며, 새 도구를 만들려면 완전한 정의와 함께 add를 호출해야 합니다. 업데이트 시 이름과 네임스페이스는 유지됩니다. 중첩된 값을 직접 변경하지 말고 새 스키마나 옵션을 할당해 교체하세요. 잘못된 업데이트는 로그에 기록되고 이전 정의가 그대로 유지됩니다.

{/* prettier-ignore */}

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

업데이트와 제거는 MCP 카탈로그 새로 고침 이후를 포함해 추가(add) 작업과 함께 순서대로 재실행됩니다.

transform은 범위 지정 등록을 반환합니다. yield* registration.dispose를 실행하면 해당 변환이 제거되고 나머지 변환에서 다시 빌드되어 이전에 재정의했던 정의가 다시 나타납니다. 해제는 멱등하며 플러그인 Scope를 닫을 때도 등록이 자동 해제됩니다.

각 모델 요청은 도구 스냅샷을 캡처합니다. 리로드와 해제는 향후 스냅샷에만 영향을 주며 기존 요청이 이미 캡처한 정의나 실행기에는 영향을 주지 않습니다. 변경 가능한 플러그인 데이터를 클로저로 참조하는 실행기는 해당 데이터를 계속 관찰하므로, 특정 정의에 고정해야 하는 값은 변환 내부에서 캡처하세요.

스키마: 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 감지기를 사용합니다.

프로바이더는 선택적으로 scope.worktree에 저장소를 생성하는 init(scope)을 구현할 수 있습니다. 초기화는 감지된 저장소 유형이 아니라 ID(기본값 Git)로 프로바이더를 선택합니다. 해당 위치에 아직 저장소가 없더라도 init이 있는 프로바이더를 등록하세요. OpenCode는 디렉터리가 존재하고 저장소가 없는지 확인한 뒤 이를 호출하고 프로젝트를 다시 검색합니다. 새로운 저장소 형식은 이 콜백 외에도 별도의 감지 지원이 필요합니다.

스키마: Vcs.Info (opens in a new tab), Vcs.FileStatus (opens in a new tab), FileDiff.Info (opens in a new tab).

interface 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.
}

웹 검색(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 실행기를 등록하고 기본 프로바이더를 선택합니다. 웹 검색을 비활성화하려면 기본값을 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입니다. 자동 인터럽트를 위해 플러그인 Scope 내에서 소비자를 포크(fork)하세요.

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를 전달하세요. 스트림 타입이 자동으로 일치하므로 별도의 타입 가드가 필요하지 않습니다.

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는 플러그인 순서대로 실행하므로 나중 훅은 이전 변경 사항을 확인할 수 있습니다. 등록은 플러그인 Scope 동안 활성 상태를 유지합니다.

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에 각 소스가 { key, text } 목록(예: core/date, core/environment)으로 나열되어 있어 훅이 소스를 구분할 수 있습니다. 이 목록은 복사본이므로 파트의 text를 편집해도 목록이 갱신되지 않습니다. 이 기능은 실험적이며 변경될 수 있습니다.

모델 요청 설정을 수정하며 선택적으로 훅을 하나의 프로바이더로 범위 지정할 수 있습니다. 이벤트는 아래 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" },
    )
  }),

네이티브 프로바이더 요청 또는 응답을 수정합니다. 본문은 일회성 스트림이므로 읽기 전에 복제하거나 교체해야 합니다. 두 훅 모두 세션이 발행하는 모든 요청에 대해 실행되며, 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으로 스트리밍하는 프로바이더는 세션당 하나의 연결을 재사용하므로 HTTP 훅에서는 해당 트래픽을 볼 수 없습니다. 실험적 experimental.ws.handshake 훅은 연결을 선택하기 전에 모델 호출당 한 번 실행되며 연결 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의 기본 정책이므로, 훅은 일반적으로 치명적인 프로바이더 실패를 재시도 가능하게 만들거나 제안된 재시도를 거부할 수 있습니다. 여러 훅이 등록 순서대로 실행되며 나중 훅은 현재 결정을 확인합니다. 내장된 최대 시도 횟수는 절대 상한으로 유지됩니다. 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) 훅은 입력을 교체하거나 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) 훅은 성공 결과와 실패를 검사하거나 교체할 수 있습니다.

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>
}

공유 등록 타입은 어떤 작업이 플러그인 Scope를 요구하는지 보여줍니다.

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 플러그인과 동일한 기본 export를 사용합니다. 메인 진입점에서 Effect 구현을 export하고 effect를 peerDependency로 선언하세요. 개발 시 단일 사본만 설치되도록 devDependencies에는 @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, export된 effect/* 하위 경로 및 @opencode/plugin의 import(플러그인의 node_modules 의존성 내부의 import 포함)를 호스트의 런타임 인스턴스로 리디렉션하여 파이버, 로거 및 Schema 파서가 하나의 런타임 사본을 공유하도록 합니다.

  • 게시되는 플러그인 아티팩트에 effect를 번들링하지 마세요. 번들러로 빌드하는 경우 effect와 effect/*를 external로 지정하세요.
  • 플러그인과 그 node_modules 의존성은 항상 호스트 OpenCode 릴리스의 effect 인스턴스에서 실행됩니다. 대상 OpenCode 릴리스와 호환되는 effect API 및 모듈 경로를 사용하세요. 다른 effect 메이저 버전(예: Effect 3) 기반으로 빌드된 의존성도 호스트의 effect를 받게 되므로 지원되지 않습니다.
  • 공개 effect 하위 경로만 제공됩니다. Effect의 비공개 internal 모듈을 import하는 플러그인은 해당 경로를 명시한 오류와 함께 로드에 실패합니다.
  • 컴파일된 OpenCode 바이너리에는 Effect HTTP API 문서 페이지에서 사용하는 Scalar 및 Swagger UI 에셋이 포함되어 있지 않으므로, 플러그인에서 해당 페이지를 제공하면 대신 안내 문구가 표시됩니다.

패키지 진입점은 effect 함수가 포함된 Plugin.define을 export합니다.

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