# Pluginy Effect

`@opencode/plugin/effect` to natywna dla Effect wersja API pluginów OpenCode. Jego operacje kontekstu zwracają Effecty
lub strumienie, wywołania zwrotne zwracają Effecty, a czas życia pluginu jest reprezentowany przez `Scope`.

OpenCode udostępnia `effect` (w tym eksportowane podścieżki `effect/*`) i `@opencode/plugin` w czasie działania przy
wczytywaniu pluginów i ich zależności z `node_modules`. Zainstaluj je jako zależności peer/dev do lokalnego
sprawdzania typów i testowania, zamiast dołączać je do pakietu pluginu.

```sh
bun add --peer @opencode/plugin effect@4.0.1
```

Wyeksportuj plugin Effect z `.opencode/plugins/`, aby wczytywał się automatycznie.

```ts title=".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)
    }),
})
```

Opublikowane pakiety i katalogi pluginów poza `.opencode/plugins/` używają tej samej konfiguracji `plugins` co inne
pluginy serwera.

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

Zobacz [Konfiguracja pluginów](/pl/docs/plugins), aby poznać włączanie, rozwiązywanie pakietów i pierwszeństwo konfiguracji.

```ts title="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 })
    }),
})
```

## Cykl życia

`effect` działa po wczytaniu pluginu. Jego zakres zamyka się przy przeładowaniu lub wyładowaniu pluginu, więc
rejestracje, fibry w zakresie i finalizatory są zwalniane razem.

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

Używaj fibr w zakresie do pracy w tle. Zakres pluginu przerywa fibrę podczas sprzątania.

```ts
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)
  }),
```

### Kontekst

Kontekst udostępnia klienta Effect podłączonego serwera OpenCode oraz transformacje, hooki, magazyn, przeładowania
i opcje dostępne tylko dla pluginów. Nie udostępnia prywatnych usług Core OpenCode.

```ts
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 })
  }),
```

Definicja pluginu i pełny kontekst są zadeklarowane następująco.

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

### Opcje

Przekazuj opcje w formie obiektowej w `opencode.json(c)`.

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

Odczytuj opcje z `ctx.options`. Zawęź nieznane wartości przed użyciem.

```ts title="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 })
    }),
})
```

## Transformacje

Transformacje synchronicznie zmieniają stan za pomocą edytora. W każdej domenie OpenCode stosuje je w kolejności
rejestracji. Najpierw źródła udostępniają dostawców i niezmienne definicje modeli. Następnie transformacje modeli
modyfikują modele brane pod uwagę u aktywnych dostawców. Wykonanie efektu rejestracji wiąże ją z zakresem pluginu.

```ts title="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,
        })
      })
    }),
})
```

Transformacja modeli może egzekwować zasady w całej kolekcji kandydatów aktywnych dostawców.

```ts title="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)
        })
    })
  }),
```

Wywołaj `reload`, gdy zmieni się stan zewnętrzny używany przez transformację. Tutaj `loadFromSource()` zwraca wpisy
`{ info: Provider.Info, models: readonly Model.Info[] }`; przeładowanie dostawcy unieważnia też cały wynik modeli.

```ts title="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

Odczytuj wszystkich agentów lub pobierz jednego po ID. Odpowiedzi klienta zawierają rozwiązaną lokalizację i dane
schematu.

```ts
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 })
  }),
```

Transformuj lub przeładuj agentów.

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

Schemat: [`Agent.Info`](/pl/docs/api#schema-Agent.Info).

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

### Dostawcy

Odczytuj dostępnych dostawców lub sprawdź metadane jednego dostawcy po ID.

```ts
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,
    })
  }),
```

Transformacje dostawców edytują ustawienia dostawcy i definicje źródeł. Odczyt edytora obejmuje nieaktywnych dostawców
i udostępnia niezmienne definicje; `models.update` edytuje należącą do pluginu kopię modelu źródłowego.

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

Zastąp spis źródła przez `models.set`, a następnie przeładuj po zmianie przechwyconych definicji.

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

W przypadku odkrywania właściwego dla konta przekaż połączenie użyte do wczytania spisu jako `sourceConnection`.
OpenCode wyklucza tego dostawcę, gdy wybrane jest inne połączenie, dopóki plugin nie opublikuje odświeżonego spisu.

{/* prettier-ignore */}
```ts
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 })
})
```

Schematy: [`Provider.Info`](/pl/docs/api#schema-Provider.Info), [`Model.Info`](/pl/docs/api#schema-Model.Info).

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

### Modele

Odczytuj dostępne modele i wybór domyślny.

```ts
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 })
  }),
```

Transformacje modeli edytują całą kolekcję kandydatów aktywnych dostawców. Wyłączeni kandydaci pozostają edytowalni do
zakończenia wszystkich transformacji; `update` może dodać model tylko u dostępnego dostawcy.

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

Wywołania zwrotne edytują surowe nadpisania modeli. Domyślne wartości dostawcy są scalane raz, gdy OpenCode zatwierdza
wynik; niezmienione odczyty używają tego wyniku ponownie. `editor.provider` odczytuje niezmienne definicje źródeł, w tym
nieaktywne szablony, a nie wynik transformacji modeli.

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

Schemat: [`Model.Info`](/pl/docs/api#schema-Model.Info).

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

### Polecenia

Odczytuj polecenia dostępne w bieżącej lokalizacji.

```ts
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) })
  }),
```

Obecna transformacja poleceń tylko dodaje. Executor otrzymuje sesję, załączniki promptu i tryb dostarczenia.

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

Schematy: [`Command.Info`](/pl/docs/api#schema-Command.Info),
[`Session.Inbox.Delivery`](/pl/docs/api#schema-Session.Inbox.Delivery).

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

### Integracje

Odczytuj integracje i rozwiąż aktywne poświadczenie, gdy istnieje.

```ts
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,
    })
  }),
```

Połącz się kluczem lub przeprowadź próbę OAuth przez podłączone API.

```ts
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 })
  }),
```

Transformuj integracje i metody uwierzytelniania. Wywołania zwrotne metod OAuth to Effecty i mogą pozyskiwać zasoby
w zakresie.

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

Schematy: [`Integration.Info`](/pl/docs/api#schema-Integration.Info), [`Integration.Method`](/pl/docs/api#schema-Integration.Method),
[`Connection.Info`](/pl/docs/api#schema-Connection.Info), [`Form.Answer`](/pl/docs/api#schema-Form.Answer).

```ts
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

Wyświetl serwery MCP i ich bieżący stan połączenia.

```ts
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 })
  }),
```

Pluginy zarządzają serwerami MCP tylko przez transformacje. Użyj `editor.set`, aby dodać lub zastąpić serwer,
`editor.update`, aby zmienić jego konfigurację, i `editor.remove`, aby go usunąć. Sprawdzaj konfigurację przez
`editor.list` i `editor.get`.

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

Ustaw `disabled: true` w transformacji, aby wyłączyć serwer i go odłączyć, lub `disabled: false`, aby go włączyć
i pozwolić OpenCode się połączyć. OpenCode uzgadnia cykl życia serwera na podstawie przekształconej konfiguracji.

Wywołaj `reload()` po zmianie stanu zewnętrznego używanego przez transformację, aby ponownie zastosować transformacje
i uzgodnić serwery.

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

Schematy: [`Mcp.Server`](/pl/docs/api#schema-Mcp.Server), [`Mcp.LocalConfigEncoded`](/pl/docs/api#schema-Mcp.LocalConfigEncoded),
[`Mcp.RemoteConfigEncoded`](/pl/docs/api#schema-Mcp.RemoteConfigEncoded).

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

### Pluginy

Wyświetl aktywne, nieudane i rozwiązane pluginy w bieżącej lokalizacji.

```ts
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 })
  }),
```

Filtruj wartości schematu w potoku Effect, gdy liczą się tylko aktywne pluginy.

```ts
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 })
  }),
```

Schematy: [`Plugin.Info`](/pl/docs/api#schema-Plugin.Info), [`Plugin.Source`](/pl/docs/api#schema-Plugin.Source).

```ts
interface PluginApi<E = never> {
  readonly list: PluginListOperation<E>
}

interface Context {
  readonly plugin: PluginApi<unknown>
}
```

### Referencje

Odczytuj referencje dostępne w bieżącej lokalizacji.

```ts
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 })
  }),
```

Dodawaj i usuwaj referencje lokalne i Git, a następnie przeładuj po zmianie stanu zewnętrznego. `get(name)` zwraca
bieżące skonfigurowane źródło lub `undefined`, gdy nazwa nie występuje.

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

Schematy: [`Reference.Info`](/pl/docs/api#schema-Reference.Info), [`Reference.LocalSource`](/pl/docs/api#schema-Reference.LocalSource),
[`Reference.GitSource`](/pl/docs/api#schema-Reference.GitSource).

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

### Sesje

Utwórz lub odczytaj sesję, a następnie wybierz agenta i model używane w późniejszej pracy.

```ts
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)
  }),
```

Wysyłaj prompty, tymczasowe żądania generowania, polecenia lub wiadomości syntetyczne.

```ts
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)
  }),
```

Wyświetlaj sesje strona po stronie. Aby pobrać następną stronę, przekaż `cursor.next` z powrotem jako `cursor`.
Kursor pamięta filtry, więc nie musisz ich powtarzać.

```ts
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
  }),
```

Usuń tymczasową sesję przez `remove`. Usunięcie zatrzymuje aktywne wykonanie i rekurencyjnie usuwa sesje podrzędne.

```ts
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)
  }),
```

Poproś o kompaktowanie przez `compact`. Zwraca przyjęty element skrzynki odbiorczej, a nie ukończone podsumowanie;
kompaktowanie domyślnie działa na granicy następnego kroku. Przekaż `delivery: "queue"`, aby zamiast tego zachować
kolejność kolejki.

```ts
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)
  }),
```

Dołączaj, wyświetlaj i usuwaj kluczowane wpisy instrukcji sesji przez `instructions.entry`. Wpisy są renderowane jako
bloki `<context key="...">` w instrukcjach sesji, a aktualizacje i usunięcia są ogłaszane na granicy następnego kroku
bez dodawania tury wiadomości do kolejki.

```ts
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)
  }),
```

Schematy: [`Session.Info`](/pl/docs/api#schema-Session.Info), [`Model.Ref`](/pl/docs/api#schema-Model.Ref),
[`Session.Inbox.User`](/pl/docs/api#schema-Session.Inbox.User),
[`Session.Inbox.Synthetic`](/pl/docs/api#schema-Session.Inbox.Synthetic),
[`InstructionEntry.Info`](/pl/docs/api#schema-InstructionEntry.Info).

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

### Skille

Odczytuj skille w bieżącej lokalizacji.

```ts
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) })
  }),
```

Transformuj i przeładowuj skille. Używaj ponownie eksportowanych konstruktorów schematów Effect dla wartości
brandowanych. `get(id)` zwraca bieżący wpis edytora lub `undefined`, gdy skill nie występuje.

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

Schemat: [`Skill.Info`](/pl/docs/api#schema-Skill.Info).

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

### Magazyn

Przechowuj, odczytuj i usuwaj trwałe wartości JSON ograniczone do ID pluginu.

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

Skanuj klucze według prefiksu z paginacją kursora.

```ts
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 })
  }),
```

Magazyn przyjmuje typ JSON Effect i zwraca Effecty bezpośrednio.

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

### Narzędzia

Rejestruj typowane narzędzia z Effect `Schema`. Executor otrzymuje zdekodowane dane wejściowe i zwraca Effect
zawierający typowane dane wyjściowe, treść wyświetlaną lub metadane.

Edytor obsługuje `add`, `update` i `remove`. Wywołanie zwrotne transformacji jest synchroniczne: nie może zwracać Effectu
ani Promise. Wczytaj dane zewnętrzne przed rejestracją lub przeładowaniem. OpenCode odtwarza aktywne transformacje
w kolejności rejestracji na świeżym edytorze; dla tej samej efektywnej nazwy narzędzia późniejsza prawidłowa rejestracja
zastępuje wcześniejszą.

```ts
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}!` } }
          }),
      })
    })
  }),
```

Wywołaj `yield* ctx.tool.reload()` po zmianie danych źródłowych przechwyconych przez wywołanie zwrotne. Przeładowanie
odtwarza aktywne transformacje bez zmiany ich kolejności; nie uruchamia ponownie efektu pluginu.

Narzędzia Effect przyjmują tę samą [deklarację wejścia freeform](/pl/docs/build/plugins/server#freeform-tool-input) co narzędzia
Promise. Jeśli model nie ogłasza tego formatu, narzędzie zachowuje normalne wejście obiektowe.

Pole `id` zawiera nazwę, pod którą narzędzie jest dostępne. Jeśli nie ma narzędzia o podanym ID, `get()` zwraca
`undefined`. Do `update` i `remove` przekaż nazwę narzędzia razem z przestrzenią nazw (`acme_greeting` powyżej).
Każdą kropkę w przestrzeni nazw OpenCode zastępuje znakiem `_`. W nazwach narzędzi zachowuje tylko litery, cyfry, `_`
i `-`, a pozostałe znaki zastępuje znakiem `_`. Jeśli podana nazwa nie istnieje, operacja nic nie zmienia. Aby utworzyć narzędzie,
wywołaj `add` z pełną definicją. Aktualizacja nie zmienia nazwy ani przestrzeni nazw. Aby zastąpić schematy lub opcje,
przypisz nowe wartości, zamiast modyfikować wartości zagnieżdżone. Nieprawidłowe aktualizacje trafiają do logów, a
poprzednia definicja pozostaje bez zmian.

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

Aktualizacje i usunięcia są odtwarzane po kolei wraz z dodaniami, także po odświeżeniu katalogu MCP.

`transform` zwraca rejestrację w zakresie. Uruchom `yield* registration.dispose`, aby usunąć jej transformację
i odbudować z pozostałych transformacji, ujawniając wcześniejszą definicję, którą zastąpiła. Zwolnienie jest
idempotentne, a zamknięcie zakresu pluginu również zwalnia jego rejestracje.

Każde żądanie do modelu zapisuje migawkę narzędzi. Przeładowanie i usunięcie rejestracji wpływają tylko na przyszłe migawki,
a nie na definicje i funkcje wykonawcze zapisane już dla bieżącego żądania. Jeśli funkcja wykonawcza odwołuje się przez
domknięcie do zmiennych danych pluginu, nadal widzi ich zmiany. Jeśli wartość ma pozostać związana z daną definicją,
przechwyć ją w transformacji.

Schematy: [`Tool.Content`](/pl/docs/api#schema-Tool.Content), [`Tool.TextContent`](/pl/docs/api#schema-Tool.TextContent),
[`Tool.FileContent`](/pl/docs/api#schema-Tool.FileContent).

```ts
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

Odczytuj informacje o repozytorium, stan kopii roboczej lub zmiany w plikach.

```ts
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 })
  }),
```

Zarejestruj dostawcę w zakresie lokalizacji przez transformację w zakresie. Dostawcy pasujący do wykrytego typu
repozytorium są wybierani automatycznie; użyj `editor.default.set`, aby wybrać innego dostawcę.

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

Wywołania zwrotne dostawcy otrzymują bieżącą lokalizację, katalog główny kopii roboczej, kanoniczny katalog główny
projektu i opcjonalny magazyn repozytorium. Funkcje zwracające zmiany otrzymują też wybrany tryb, żądany kontekst i budżet
bajtów wyjściowych. Odkrywanie repozytoriów nadal używa wbudowanych detektorów Git i Mercurial OpenCode.

Dostawcy mogą opcjonalnie implementować `init(scope)`, aby utworzyć repozytorium w `scope.worktree`. Inicjalizacja
wybiera dostawcę po ID (domyślnie Git), a nie po wykrytym typie repozytorium. Zarejestruj dostawcę z `init`, nawet gdy
lokalizacja nie ma jeszcze repozytorium; OpenCode sprawdza, czy katalog istnieje i nie ma repozytorium, przed jego
wywołaniem, a następnie ponownie odkrywa projekt. Nowe formaty repozytoriów nadal wymagają obsługi odkrywania poza tym
wywołaniem zwrotnym.

Schematy: [`Vcs.Info`](/pl/docs/api#schema-Vcs.Info), [`Vcs.FileStatus`](/pl/docs/api#schema-Vcs.FileStatus),
[`FileDiff.Info`](/pl/docs/api#schema-FileDiff.Info).

```ts
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.
}
```

### Wyszukiwanie w internecie

Wyświetl dostawców lub uruchom zapytanie przez wybranego dostawcę.

```ts
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 })
  }),
```

Zarejestruj executor Effect i wybierz dostawcę domyślnego. Ustaw domyślnego na `false`, aby wyłączyć wyszukiwanie
w internecie.

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

Schematy: [`WebSearch.Provider`](/pl/docs/api#schema-WebSearch.Provider),
[`WebSearch.Result`](/pl/docs/api#schema-WebSearch.Result).

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

### Zdarzenia

Subskrypcja publicznych zdarzeń serwera to `Stream` z Effect. Uruchom jej odbiorcę w osobnej fibrze w zakresie pluginu,
aby jego działanie kończyło się automatycznie.

```ts
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,
    )
  }),
```

Przekaż `types`, aby otrzymywać tylko potrzebne typy zdarzeń. Strumień jest typowany odpowiednio, więc strażnik typów
nie jest potrzebny.

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

Schemat: [`V2EventEncoded`](/pl/docs/api#schema-V2EventEncoded).

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

## Hooki

Hooki przechwytują bieżące operacje. Wiele pluginów może zarejestrować ten sam hook; OpenCode uruchamia je w kolejności
pluginów, więc późniejsze hooki widzą wcześniejsze zmiany. Rejestracje pozostają aktywne przez zakres pluginu.

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

### Sesje

Modyfikuj złożone instrukcje systemowe, wiadomości lub narzędzia bezpośrednio przed wysłaniem do modelu. `context`
działa dla pętli agenta; `compaction`, `generate` i `title` działają dla tych pomocniczych żądań. `compaction` i `title`
przyjmują `result`, który pomija wywołanie modelu.

```ts
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 }
      }),
    )
  }),
```

Wiadomości w hookach `context`, `compaction` i `generate` niosą `metadata` swojej zapisanej wiadomości tylko do odczytu
(na przykład to, co ustawił hook `prompt`). Nie jest ona wysyłana do modelu.

Część `system`, która zawiera instrukcje OpenCode, wymienia też każde źródło w `metadata.experimental.instructions` jako
`{ key, text }`, na przykład `core/date` lub `core/environment`, aby hook mógł odróżnić źródła. Lista jest kopią:
edycja `text` części nie aktualizuje jej. Jest to eksperymentalne i może się zmienić.

Modyfikuj ustawienia żądań modelu i opcjonalnie ogranicz hook do jednego dostawcy. Zdarzenie niesie ten sam `kind` co
poniższe hooki HTTP.

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

Modyfikuj natywne żądania lub odpowiedzi dostawcy. Ich treści to strumienie jednorazowe; sklonuj lub zastąp treść przed
odczytem. Oba hooki działają dla każdego żądania wysłanego przez sesję; `event.kind` to `"primary"`, `"compaction"`,
`"title"` lub `"generate"`, zależnie od przepływu, który je wysłał.

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

Dostawcy strumieniujący przez WebSocket używają jednego połączenia na sesję, więc hooki HTTP nigdy nie widzą tego ruchu.
Eksperymentalny hook `experimental.ws.handshake` działa raz na wywołanie modelu przed wybraniem połączenia i udostępnia
`url` oraz `headers` połączenia; zmiana któregokolwiek ponownie otwiera socket. Hooki HTTP nadal działają dla każdego
żądania, na które trasa WebSocket przechodzi w tryb zapasowy.

```ts
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` i `experimental.ws.receive` udostępniają same ramki: `send` działa po zbudowaniu wychodzącej
ramki przez sterownik dostawcy, `receive` działa na każdej przychodzącej ramce przed jej zaobserwowaniem przez sterownik.
To, co `frame` zawiera po powrocie hooka, przechodzi przez sieć lub trafia do sterownika; OpenCode tego nie waliduje.

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

Nadpisz decyzję o ponowieniu dla niepowodzenia dostawcy lub zastąp jego opóźnienie w milisekundach. Hook działa po
sklasyfikowaniu niepowodzenia przez OpenCode i zaproponowaniu zasad, ale przed zaplanowaniem jakiegokolwiek ponowienia.
Nie ujawnia, jak OpenCode wewnętrznie wykonuje następną próbę.

```ts
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 }
      }),
    )
  }),
```

Początkowe `decision` to zasada OpenCode, więc hooki mogą uczynić normalnie końcowe niepowodzenie dostawcy ponawialnym
lub zawetować proponowane ponowienie. Wiele hooków działa w kolejności rejestracji, a późniejsze widzą bieżącą decyzję.
Wbudowany maksymalny licznik prób pozostaje twardym limitem. `attempt` to proponowana fizyczna próba; początkowe żądanie
to próba `1`, więc pierwsze ponowienie to próba `2`. Nieprawidłowe opóźnienia (`NaN`, nieskończoność lub wartości ujemne)
wracają do obliczonego opóźnienia. Odzyskiwanie po przepełnieniu kontekstu pozostaje osobne, ponieważ kompaktuje rozmowę,
zamiast ponawiać to samo żądanie.

#### Referencja

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

### Powłoka

Modyfikuj polecenia powłoki, katalogi robocze, limity czasu, pliki wykonywalne lub zmienne środowiskowe przed wykonaniem.

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

#### Referencja

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

### Narzędzia

Hooki przed mogą zastąpić dane wejściowe lub zakończyć się błędem `Tool.Error`.

```ts
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 }),
    )
  }),
```

Hooki po mogą sprawdzić lub zastąpić udane wyniki i niepowodzenia.

```ts
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 } }
      })
    })
  }),
```

#### Referencja

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

Współdzielone typy rejestracji pokazują, które operacje wymagają zakresu pluginu.

```ts
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>
```

## Publikacja

Plugin pakietowy używa tego samego eksportu domyślnego co lokalny plugin Effect. Eksportuj implementację Effect
z głównego punktu wejścia i zadeklaruj `effect` jako `peerDependency`. W `devDependencies` przypnij wersję używaną przez
`@opencode/plugin`, aby instalacje deweloperskie miały tylko jedną kopię.

```json title="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 przekierowuje importy `effect`, eksportowane podścieżki `effect/*` i `@opencode/plugin` (w tym importy
z zależności w `node_modules` pluginu) do instancji środowiska uruchomieniowego hosta, aby fibry, loggery i parsery
`Schema` współdzieliły jedną kopię środowiska.

- Nie dołączaj `effect` do opublikowanego artefaktu pluginu. Jeśli budujesz bundlerem, oznacz `effect` i `effect/*` jako
  external.
- Pluginy i ich zależności z `node_modules` zawsze wykonują się na instancji `effect` wydania OpenCode hosta. Używaj API
  i ścieżek modułów `effect` zgodnych z docelowym wydaniem OpenCode; zależności zbudowane na innym majorze `effect`
  (takim jak Effect 3) również otrzymują `effect` hosta i nie są obsługiwane.
- Udostępniane są tylko publiczne podścieżki `effect`. Plugin importujący prywatny moduł `internal` Effect nie wczyta
  się, a błąd wskaże ścieżkę.
- Skompilowany plik binarny OpenCode nie zawiera zasobów Scalar i Swagger UI używanych przez strony dokumentacji API HTTP
  Effect; serwowanie tych stron z pluginu pokazuje zamiast tego powiadomienie.

Punkt wejścia pakietu eksportuje `Plugin.define` z funkcją `effect`.

```ts title="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)
    }),
})
```

Używaj wersji zgodnych z docelowym wydaniem OpenCode i testuj zainstalowany pakiet, a nie tylko kopię podłączoną przez
workspace.

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