# Plugin Effect

`@opencode/plugin/effect` è la versione nativa per Effect dell'API dei plugin di OpenCode. Le sue operazioni di contesto restituiscono
Effect o Stream, i callback restituiscono Effect, e la vita del plugin è rappresentata da `Scope`.

OpenCode fornisce `effect` (compresi i sottopercorsi esportati `effect/*`) e `@opencode/plugin` a runtime quando carica
plugin e le loro dipendenze in `node_modules`. Installali come dipendenze peer/dev per il type-checking e i test locali,
invece di includerli nel bundle del plugin.

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

Esporta un plugin Effect da `.opencode/plugins/` per caricarlo automaticamente.

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

I pacchetti pubblicati e le directory di plugin fuori da `.opencode/plugins/` usano la stessa configurazione `plugins` degli altri plugin
server.

```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 },
    },
  ],
}
```

Vedi [Configurare i plugin](/it/docs/plugins) per abilitazione, risoluzione dei pacchetti e precedenza della configurazione.

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

## Ciclo di vita

L'`effect` parte al caricamento del plugin. Quando OpenCode ricarica o scarica il plugin, lo scope si chiude: le registrazioni
vengono annullate, i fiber associati allo scope si interrompono e i finalizer vengono eseguiti, tutti nello stesso ciclo di chiusura.

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

Usa fiber con scope per il lavoro in background. Lo scope del plugin interrompe il fiber durante la pulizia.

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

### Contesto

Il contesto espone il client Effect per il server OpenCode collegato, più trasformazioni, hook, archiviazione,
ricaricamenti e opzioni specifici del plugin. Non espone i servizi Core privati di 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 })
  }),
```

La definizione del plugin e il contesto completo sono dichiarati così.

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

### Opzioni

Passa le opzioni con la forma a oggetto in `opencode.json(c)`.

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

Leggi le opzioni da `ctx.options`. Restringi i valori sconosciuti prima dell'uso.

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

## Trasformazioni

Le trasformazioni modificano sincronicamente lo stato tramite un editor. OpenCode applica le trasformazioni nell'ordine di registrazione dentro ogni
dominio. Le fonti contribuiscono prima con provider e definizioni immutabili dei modelli; poi le trasformazioni dei modelli modificano i candidati
dei provider attivi. Eseguendo lo yield della registrazione, la mantieni nello scope del plugin.

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

Una trasformazione dei modelli può applicare una policy all'intera raccolta di candidati dei provider attivi.

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

Chiama `reload` quando cambia lo stato esterno usato da una trasformazione. Qui `loadFromSource()` restituisce
voci `{ info: Provider.Info, models: readonly Model.Info[] }`; il ricaricamento dei provider invalida anche l'intero risultato dei modelli.

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

### Agente

Leggi tutti gli agenti o recuperane uno per ID. Le risposte del client includono la location risolta e i dati dello schema.

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

Trasforma o ricarica gli agenti.

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

Schema: [`Agent.Info`](/it/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>
}
```

### Provider

Leggi i provider disponibili o ispeziona i metadati di un provider per 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,
    })
  }),
```

Le trasformazioni dei provider modificano impostazioni e definizioni delle fonti. Le letture dell'editor includono i provider inattivi ed espongono
definizioni immutabili; `models.update` modifica una copia di proprietà di un modello della fonte.

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

Sostituisci un inventario di fonte con `models.set`, poi ricarica dopo che le definizioni acquisite cambiano.

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

Per rilevare i modelli specifici di un account, passa come `sourceConnection` la connessione usata per caricare l'inventario. OpenCode esclude
quel provider mentre è selezionata un'altra connessione, finché il tuo plugin non pubblica il suo inventario aggiornato.

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

Schema: [`Provider.Info`](/it/docs/api#schema-Provider.Info), [`Model.Info`](/it/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>
}
```

### Modelli

Leggi i modelli disponibili e la selezione predefinita.

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

Le trasformazioni dei modelli modificano l'intera raccolta di candidati dei provider attivi. I candidati disabilitati restano modificabili finché tutte
le trasformazioni finiscono; `update` può aggiungere un modello solo sotto un provider disponibile.

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

I callback modificano le sostituzioni grezze dei modelli. I valori predefiniti del provider vengono uniti una volta quando OpenCode conferma il risultato; le letture
invariate riusano quel risultato. `editor.provider` legge le definizioni immutabili delle fonti, compresi i template inattivi, invece
dell'output delle trasformazioni dei modelli.

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

Schema: [`Model.Info`](/it/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>
}
```

### Comandi

Leggi i comandi disponibili nella location corrente.

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

La trasformazione dei comandi attuale è solo di aggiunta. Un executor riceve la sessione, gli allegati del prompt e la modalità di consegna.

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

Schema: [`Command.Info`](/it/docs/api#schema-Command.Info),
[`Session.Inbox.Delivery`](/it/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>
}
```

### Integrazioni

Leggi le integrazioni e risolvi la credenziale attiva quando esiste.

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

Collegati con una chiave o gestisci un tentativo OAuth tramite l'API della connessione.

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

Trasforma integrazioni e metodi di autenticazione. I callback dei metodi OAuth sono Effect e possono acquisire risorse
con scope.

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

Schema: [`Integration.Info`](/it/docs/api#schema-Integration.Info), [`Integration.Method`](/it/docs/api#schema-Integration.Method),
[`Connection.Info`](/it/docs/api#schema-Connection.Info), [`Form.Answer`](/it/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

Elenca i server MCP e il loro stato di connessione attuale.

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

I plugin gestiscono i server MCP solo tramite trasformazioni. Usa `editor.set` per aggiungere o sostituire un server, `editor.update` per
cambiarne la configurazione ed `editor.remove` per rimuoverlo. Ispeziona la configurazione con `editor.list` e `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")
    })
  }),
```

Imposta `disabled: true` in una trasformazione per disabilitare un server e disconnetterlo, o `disabled: false` per abilitarlo e permettere
a OpenCode di collegarsi. OpenCode riconcilia il ciclo di vita dei server dalla configurazione trasformata.

Chiama `reload()` dopo che lo stato esterno usato da una trasformazione cambia, per riapplicare le trasformazioni e riconciliare i server.

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

Schema: [`Mcp.Server`](/it/docs/api#schema-Mcp.Server), [`Mcp.LocalConfigEncoded`](/it/docs/api#schema-Mcp.LocalConfigEncoded),
[`Mcp.RemoteConfigEncoded`](/it/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>
}
```

### Plugin

Elenca i plugin attivi, falliti e risolti nella location corrente.

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

Filtra i valori dello schema in una pipeline Effect quando contano solo i plugin attivi.

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

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

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

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

### Riferimenti

Leggi i riferimenti disponibili nella location corrente.

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

Aggiungi o rimuovi riferimenti locali e Git, poi ricarica dopo che lo stato esterno cambia. `get(name)` restituisce la fonte configurata
corrente, o `undefined` quando il nome è assente.

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

Schema: [`Reference.Info`](/it/docs/api#schema-Reference.Info), [`Reference.LocalSource`](/it/docs/api#schema-Reference.LocalSource),
[`Reference.GitSource`](/it/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>
}
```

### Sessioni

Crea o leggi una sessione, poi seleziona l'agente e il modello usati dal lavoro successivo.

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

Invia prompt, richieste di generazione temporanee, comandi o messaggi sintetici.

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

Elenca le sessioni una pagina alla volta. Per ottenere la pagina successiva, passa `cursor.next` come `cursor`. Il cursore ricorda i tuoi
filtri, quindi non devi ripeterli.

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

Rimuovi una sessione temporanea con `remove`. La rimozione ferma l'esecuzione attiva ed elimina ricorsivamente le sessioni figlie.

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

Richiedi la compattazione con `compact`. Il metodo restituisce l'elemento accettato nella inbox, non il riassunto finale.
Per impostazione predefinita, la compattazione parte al successivo confine tra due passi. Passa `delivery: "queue"` per rispettare l'ordine della coda.

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

Allega, elenca o rimuovi voci di istruzioni della sessione con chiave tramite `instructions.entry`. Le voci vengono renderizzate come blocchi `<context key="...">` nelle istruzioni della sessione, e aggiornamenti o rimozioni vengono annunciati al confine del passo successivo senza accodare un turno di messaggio.

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

Schema: [`Session.Info`](/it/docs/api#schema-Session.Info), [`Model.Ref`](/it/docs/api#schema-Model.Ref),
[`Session.Inbox.User`](/it/docs/api#schema-Session.Inbox.User),
[`Session.Inbox.Synthetic`](/it/docs/api#schema-Session.Inbox.Synthetic),
[`InstructionEntry.Info`](/it/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"
>
```

### Skill

Leggi le skill nella location corrente.

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

Trasforma e ricarica le skill. Usa i costruttori dello schema Effect riesportati per i valori branded. `get(id)` restituisce la
voce corrente dell'editor, o `undefined` quando la skill è assente.

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

Schema: [`Skill.Info`](/it/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>
}
```

### Archiviazione

Archivia, leggi e rimuovi valori JSON persistenti associati all'ID del plugin.

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

Scansiona le chiavi per prefisso con paginazione a cursore.

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

L'archiviazione accetta il tipo JSON di Effect e restituisce direttamente Effect.

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

### Strumenti

Registra strumenti tipizzati con `Schema` di Effect. L'executor riceve l'input decodificato e restituisce un Effect contenente output tipizzato,
contenuto di visualizzazione o metadati.

L'editor supporta `add`, `update` e `remove`. Il callback della trasformazione è sincrono: non deve restituire un Effect o una Promise. Carica
i dati esterni prima di registrare o ricaricare. OpenCode riproduce le trasformazioni attive nell'ordine di registrazione su un
editor nuovo; per lo stesso nome effettivo dello strumento, una registrazione valida successiva sovrascrive quella precedente.

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

Chiama `yield* ctx.tool.reload()` dopo aver cambiato i dati di origine acquisiti dal callback. Il ricaricamento riproduce le trasformazioni attive
senza cambiarne l'ordine e senza rieseguire l'effect del plugin.

Gli strumenti Effect accettano la stessa [dichiarazione di input freeform](/it/docs/build/plugins/server#freeform-tool-input) degli strumenti Promise. Se il modello non annuncia quel formato, lo strumento mantiene il suo normale input a oggetto.

Gli strumenti hanno un `id` che contiene il loro nome effettivo, e `get()` restituisce `undefined` quando quell'ID non è presente. Usa
`update` e `remove` con il nome effettivo dello strumento, compreso il suo namespace (`acme_greeting` sopra). I punti nei
namespace diventano `_`. Nei nomi degli strumenti, ogni carattere diverso da lettere, cifre, `_` e `-` diventa `_`.
L'editor ignora i nomi mancanti. Per creare uno strumento, usa `add` con una definizione completa.
Gli aggiornamenti preservano nome e namespace. Assegna nuovi schemi o opzioni per sostituirli
invece di modificare i valori annidati. Gli aggiornamenti non validi vengono registrati e lasciano intatta la definizione precedente.

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

Aggiornamenti e rimozioni vengono riprodotti in ordine con le aggiunte, anche dopo gli aggiornamenti del catalogo MCP.

`transform` restituisce una registrazione con scope. Esegui `yield* registration.dispose` per rimuovere la sua trasformazione e ricostruire
dalle trasformazioni rimanenti, rivelando l'eventuale definizione precedente che aveva sovrascritto. L'eliminazione è idempotente, e la chiusura
dello scope del plugin elimina anche le sue registrazioni.

Ogni richiesta al modello acquisisce uno snapshot degli strumenti. Il ricaricamento e l'eliminazione influiscono sugli snapshot futuri, non sulle definizioni o sugli
executor già acquisiti da una richiesta esistente. Gli executor che chiudono su dati mutabili del plugin osservano comunque
quei dati; acquisisci un valore dentro la trasformazione quando deve restare legato a quella definizione.

Schema: [`Tool.Content`](/it/docs/api#schema-Tool.Content), [`Tool.TextContent`](/it/docs/api#schema-Tool.TextContent),
[`Tool.FileContent`](/it/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

Leggi informazioni del repository, stato della copia di lavoro o diff dei file.

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

Registra un provider con ambito Location tramite una trasformazione con scope. I provider che corrispondono al tipo di repository rilevato vengono
selezionati automaticamente; usa `editor.default.set` per selezionare un provider diverso.

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

I callback dei provider ricevono la location corrente, la radice della copia di lavoro, la radice canonica del progetto e l'eventuale repository
store. I callback dei diff ricevono anche la modalità selezionata, il contesto richiesto e il limite di byte dell'output. Il rilevamento automatico dei repository
continua a usare i rilevatori Git e Mercurial integrati di OpenCode.

I provider possono facoltativamente implementare `init(scope)` per creare un repository in `scope.worktree`. L'inizializzazione seleziona
il provider per ID (Git per impostazione predefinita), non per il tipo di repository rilevato. Registra un provider con `init` anche quando
la location non ha ancora un repository; OpenCode controlla che la directory esista e non abbia un repository prima di chiamarlo,
poi individua di nuovo il progetto. Per i nuovi formati di repository serve comunque il supporto al rilevamento automatico, oltre a questo callback.

Schema: [`Vcs.Info`](/it/docs/api#schema-Vcs.Info), [`Vcs.FileStatus`](/it/docs/api#schema-Vcs.FileStatus),
[`FileDiff.Info`](/it/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.
}
```

### Ricerca web

Elenca i provider o esegui una query tramite il provider selezionato.

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

Registra un executor Effect e seleziona il provider predefinito. Imposta il valore predefinito su `false` per disattivare la ricerca web.

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

Schema: [`WebSearch.Provider`](/it/docs/api#schema-WebSearch.Provider),
[`WebSearch.Result`](/it/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>
}
```

### Eventi

La sottoscrizione pubblica agli eventi del server è uno `Stream` di Effect. Avvia la lettura in un fiber separato nello scope del plugin,
così si interrompe automaticamente alla chiusura dello scope.

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

Passa `types` per ricevere solo i tipi di evento che ti servono. Lo stream è tipizzato di conseguenza, quindi non serve un type guard.

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

Schema: [`V2EventEncoded`](/it/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>
}
```

## Hook

Gli hook intercettano operazioni live. Più plugin possono registrare lo stesso hook; OpenCode li esegue nell'ordine dei plugin, così
gli hook successivi vedono le modifiche precedenti. Le registrazioni restano attive per lo scope del plugin.

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

### Sessioni

Modifica istruzioni di sistema, messaggi o strumenti assemblati subito prima dell'invio al modello. `context` viene eseguito per
il ciclo dell'agente; `compaction`, `generate` e `title` vengono eseguiti per quelle richieste ausiliarie. `compaction` e `title` accettano un
`result` che salta la chiamata al modello.

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

I messaggi negli hook `context`, `compaction` e `generate` portano i `metadata` del messaggio archiviato, in sola lettura
(ad esempio ciò che ha impostato un hook `prompt`). Non vengono inviati al modello.

La parte `system` che contiene le istruzioni di OpenCode elenca anche ogni fonte in `metadata.experimental.instructions` come
`{ key, text }`, ad esempio `core/date` o `core/environment`, così un hook può distinguere le fonti. L'elenco è una copia:
modificare il `text` della parte non lo aggiorna. È sperimentale e può cambiare.

Modifica le impostazioni delle richieste ai modelli e, facoltativamente, limita l'hook a un provider. L'evento porta lo stesso `kind` degli
hook HTTP qui sotto.

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

Modifica le richieste o risposte native del provider. I loro corpi sono stream monouso; clona o sostituisci un corpo prima di leggerlo.
Entrambi gli hook vengono eseguiti per ogni richiesta emessa da una sessione; `event.kind` è `"primary"`, `"compaction"`, `"title"` o
`"generate"` a seconda del flusso che l'ha emessa.

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

I provider che trasmettono su WebSocket riusano una connessione per sessione, quindi gli hook HTTP non vedono mai quel traffico. L'
hook sperimentale `experimental.ws.handshake` viene eseguito una volta per chiamata al modello prima che venga selezionata la connessione ed espone
`url` e `headers` della connessione; cambiare l'uno o l'altro riapre il socket. Gli hook HTTP vengono comunque eseguiti per le richieste
inviate tramite HTTP come alternativa al WebSocket.

```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` e `experimental.ws.receive` espongono i frame stessi: `send` viene eseguito dopo che il driver del provider
costruisce un frame in uscita, mentre `receive` parte per ogni frame in entrata prima che il driver lo legga. Il contenuto di `frame` al termine dell'hook è quello inviato sulla rete o consegnato al driver;
OpenCode non lo valida.

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

Decidi se riprovare dopo un errore del provider o modifica l'attesa in millisecondi. L'hook interviene dopo che OpenCode
classifica l'errore e propone la propria policy, ma prima di pianificare un nuovo tentativo. L'hook non dà accesso
al modo in cui OpenCode esegue internamente il tentativo successivo.

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

La `decision` iniziale è la policy di OpenCode, quindi gli hook possono rendere ripetibile un fallimento del provider normalmente terminale o porre il veto a un
retry proposto. Più hook vengono eseguiti nell'ordine di registrazione e gli hook successivi vedono la decisione corrente. Il numero massimo
di tentativi integrato resta un limite rigido. `attempt` è il tentativo fisico proposto; la richiesta iniziale è il tentativo `1`,
quindi il primo retry è il tentativo `2`. I ritardi non validi (`NaN`, infinito o valori negativi) ricadono sul ritardo calcolato.
Il recupero dall'overflow di contesto resta separato perché compatta la conversazione invece di riprovare la stessa richiesta.

#### Riferimento

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

### Shell

Modifica comandi shell, directory di lavoro, timeout, eseguibili o variabili d'ambiente prima dell'esecuzione.

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

#### Riferimento

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

### Strumenti

Gli hook before possono sostituire l'input o fallire con `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 }),
    )
  }),
```

Gli hook after possono ispezionare o sostituire risultati riusciti e fallimenti.

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

#### Riferimento

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

I tipi di registrazione condivisi mostrano quali operazioni richiedono lo scope del plugin.

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

## Pubblicazione

Un plugin di un pacchetto usa lo stesso default export di un plugin Effect locale. Esporta l'implementazione Effect dall'entrypoint principale
e dichiara `effect` come `peerDependency`. In `devDependencies`, fissa la versione usata da `@opencode/plugin`
così le installazioni di sviluppo usano una sola copia.

```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 reindirizza gli import di `effect`, dei sottopercorsi esportati `effect/*` e di `@opencode/plugin` (compresi gli import dalle
dipendenze in `node_modules` del plugin) alle istanze runtime dell'host, così fiber, logger e parser `Schema`
condividono una sola copia del runtime.

- Non includere `effect` nel bundle dell'artefatto pubblicato del plugin. Se usi un bundler, segna `effect` e `effect/*`
  come external.
- I plugin e le loro dipendenze in `node_modules` vengono sempre eseguiti contro l'istanza `effect` della release OpenCode host.
  Usa API e percorsi di modulo `effect` compatibili con la release OpenCode a cui miri; le dipendenze costruite su un'altra
  major di `effect` (come Effect 3) ricevono anch'esse l'`effect` dell'host e non sono supportate.
- Sono forniti solo i sottopercorsi pubblici di `effect`. Un plugin che importa uno dei moduli `internal` privati di Effect non riesce a
  caricarsi, con un errore che nomina il percorso.
- Il binario OpenCode compilato non include gli asset di Scalar e Swagger UI usati dalle pagine della documentazione HTTP API di Effect;
  servire quelle pagine da un plugin mostra invece un avviso.

L'entrypoint del pacchetto esporta `Plugin.define` con una funzione `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)
    }),
})
```

Usa versioni compatibili con la release OpenCode a cui miri e prova il pacchetto installato, non solo una
copia collegata nello spazio di lavoro.

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