# ملحقات Effect

`@opencode/plugin/effect` هو الإصدار الأصلي في Effect من API ملحقات OpenCode. تعيد عمليات السياق
Effects أو Streams، وتعيد دوال ردّ النداء Effects، ويمثّل `Scope` مدّة عمل الملحق.

ويوفّر OpenCode `effect` (بما في ذلك المسارات الفرعية المصدّرة `effect/*`) و`@opencode/plugin` وقت التشغيل عند تحميل
الملحقات وتبعياتها في `node_modules`. ثبّتهما ضمن التبعيات النظيرة وتبعيات التطوير للتحقّق من الأنواع والاختبار محليًا
بدل تضمينهما في ملحقك.

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

وصدّر ملحق Effect من `.opencode/plugins/` ليُحمَّل تلقائيًا.

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

وتستخدم الحزم المنشورة ومجلدات الملحقات خارج `.opencode/plugins/` إعداد `plugins` نفسه الذي تستخدمه ملحقات
الخادم الأخرى.

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

راجع [إعداد الملحقات](/ar/docs/plugins) للتفعيل وتحليل الحزم وأسبقية الإعداد.

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

## دورة الحياة

يعمل `effect` عند تحميل الملحق. ويُغلق نطاقه عند إعادة تحميل الملحق أو إلغاء تحميله، فيتولّى النطاق إلغاء التسجيلات وإيقاف وحدات التنفيذ الخفيفة (fibers)
المرتبطة به وتشغيل دوال الإنهاء، ضمن عملية التنظيف نفسها.

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

استخدم وحدات تنفيذ خفيفة مرتبطة بنطاق لتشغيل المهام في الخلفية. ويوقف نطاق الملحق هذه الوحدات أثناء تحرير موارده.

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

### السياق

ويعرض السياق عميل Effect لخادم OpenCode المرتبط، إضافة إلى تحويلات وخطافات وتخزين وإعادات تحميل وخيارات
خاصة بالملحقات. ولا يعرض خدمات 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 })
  }),
```

ويُعلن تعريف الملحق وسياقه الكامل كما يلي.

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

### الخيارات

مرّر الخيارات بصيغة الكائن في `opencode.json(c)`.

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

واقرأ الخيارات من `ctx.options`. وضيِّق القيم غير المعروفة قبل استخدامها.

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

## التحويلات

تعدّل التحويلات الحالة تزامنيًا عبر محرّر. ويطبّق OpenCode التحويلات بترتيب التسجيل داخل كل
نطاق. وتوفّر المصادر أولًا المزوّدين وتعريفات النماذج غير القابلة للتغيير، ثم تعدّل تحويلات النماذج قائمة النماذج المرشّحة لدى
المزوّدين النشطين. ويبقى التسجيل في نطاق الملحق عند إرجاعه إلى Effect عبر المُولِّد.

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

يمكن لتحويل النماذج فرض سياسة تسري على جميع النماذج المرشّحة لدى المزوّدين النشطين.

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

واستدعِ `reload` عندما تتغيّر حالة خارجية يستخدمها تحويل. وهنا، تعيد `loadFromSource()`
إدخالات `{ info: Provider.Info, models: readonly Model.Info[] }`؛ كما تُبطل إعادات تحميل المزوّد نتيجة النماذج كاملة.

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

### الوكيل

اقرأ كل الوكلاء أو اجلب وكيلًا بمعرّفه. وتضم استجابات العميل الموقع المحلول وبيانات المخطط.

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

حوّل الوكلاء أو أعد تحميلهم.

```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`](/ar/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>
}
```

### المزوّدون

اقرأ المزوّدين المتاحين أو افحص بيانات مزوّد واحد الوصفية بمعرّفه.

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

وتعدّل تحويلات المزوّد إعدادات المزوّد وتعريفات المصادر. وتضم قراءات المحرّر المزوّدين غير النشطين وتعرض
تعريفات غير قابلة للتغيير؛ ويعدّل `models.update` نسخة مملوكة من نموذج مصدر.

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

واستبدل جرد مصدر بـ`models.set`، ثم أعد التحميل بعد تغيّر تعريفاته الملتقطة.

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

وللاكتشاف الخاص بحساب، مرّر الاتصال المستخدم لتحميل الجرد كـ`sourceConnection`. ويستبعد OpenCode
ذلك المزوّد ما دام اتصال آخر مختارًا، حتى ينشر ملحقك جرده المحدّث.

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

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

### النماذج

اقرأ النماذج المتاحة والاختيار الافتراضي.

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

تعدّل تحويلات النماذج المجموعة الكاملة للنماذج المرشّحة لدى المزوّدين النشطين. ويمكن تعديل النماذج المعطّلة إلى أن تنتهي كل
التحويلات، ولا يستطيع `update` إضافة نموذج إلا إلى مزوّد متاح.

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

وتعدّل ردود النداء تجاوزات النموذج الخام. وتُدمج افتراضيات المزوّد مرة واحدة عندما يثبّت OpenCode النتيجة؛ وتعيد القراءات غير المتغيّرة
استخدام تلك النتيجة. ويقرأ `editor.provider` تعريفات المصادر غير القابلة للتغيير، بما في ذلك القوالب غير النشطة، لا
مخرجات تحويل النموذج.

```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`](/ar/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>
}
```

### الأوامر

اقرأ الأوامر المتاحة في الموقع الحالي.

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

وتحويل الأوامر الحالي للإضافة فقط. ويتلقى المنفّذ الجلسة ومرفقات المطالبة ووضع التسليم.

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

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

### التكاملات

اقرأ التكاملات وحلّ بيانات الاعتماد النشطة عندما توجد.

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

واتصل بمفتاح أو أدر محاولة OAuth عبر الواجهة المرتبطة.

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

حوّل التكاملات وطرق المصادقة. وردود نداء طرق OAuth هي Effects وقد تحصل على موارد
محدودة النطاق.

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

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

اسرد خوادم MCP وحالة اتصالها الحالية.

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

ولا تدير الملحقات خوادم MCP إلا عبر التحويلات. واستخدم `editor.set` لإضافة خادم أو استبداله، و`editor.update`
لتغيير إعداده، و`editor.remove` لإزالته. وافحص الإعداد بـ`editor.list` و`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")
    })
  }),
```

واضبط `disabled: true` في تحويل لتعطيل خادم وقطع اتصاله، أو `disabled: false` لتفعيله والسماح
لـOpenCode بالاتصال. ويوائم OpenCode دورة حياة الخادم من الإعداد المحوّل.

واستدعِ `reload()` بعد تغيّر حالة خارجية يستخدمها تحويل لإعادة تطبيق التحويلات ومواءمة الخوادم.

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

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

### الملحقات

اسرد الملحقات النشطة والفاشلة والمحلولة في الموقع الحالي.

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

وصفِّ قيم المخطط في خط أنابيب Effect عندما تهمّ الملحقات النشطة وحدها.

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

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

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

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

### المراجع

اقرأ المراجع المتاحة في الموقع الحالي.

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

أضف المراجع المحلية ومراجع Git أو أزلها، ثم أعد التحميل بعد تغيّر الحالة الخارجية. ويعيد `get(name)` المصدر المضبوط
الحالي، أو `undefined` عندما يغيب الاسم.

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

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

### الجلسات

أنشئ جلسة أو اقرأها، ثم اختر الوكيل والنموذج اللذين يستخدمهما العمل اللاحق.

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

أرسل مطالبات أو طلبات توليد عابرة أو أوامر أو رسائل تركيبية.

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

اسرد الجلسات صفحةً صفحة. وللحصول على الصفحة التالية، مرّر `cursor.next` مجددًا كـ`cursor`. ويتذكّر المؤشر
مرشّحاتك، فلا تحتاج إلى تكرارها.

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

وأزل جلسة مؤقتة بـ`remove`. فالإزالة توقف التنفيذ النشط وتحذف الجلسات الفرعية تكراريًا.

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

واطلب ضغط السياق بـ`compact`. فهو يعيد عنصر صندوق الوارد المقبول، لا ملخصًا مكتملًا؛ ويعمل الضغط عند
حدّ الخطوة التالي افتراضيًا. ومرّر `delivery: "queue"` للحفاظ على ترتيب قائمة الانتظار بدلًا من ذلك.

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

وأرفق إدخالات تعليمات الجلسة المفتاحية أو اسردها أو أزلها بـ`instructions.entry`. وتُعرض الإدخالات ككتل `<context key="...">` في تعليمات الجلسة، وتُعلن التحديثات أو الإزالات عند حدّ الخطوة التالي دون وضع دورة رسالة في قائمة الانتظار.

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

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

### المهارات

اقرأ المهارات في الموقع الحالي.

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

حوّل المهارات وأعد تحميلها. واستخدم بواني مخطط Effect المعاد تصديرها للقيم الموسومة. ويعيد `get(id)`
إدخال المحرّر الحالي، أو `undefined` عندما تغيب المهارة.

```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`](/ar/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>
}
```

### التخزين

خزّن قيم JSON دائمة محدودة النطاق بمعرّف الملحق واقرأها وأزلها.

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

استعرض المفاتيح المطابقة لبادئة معيّنة على صفحات تتنقّل بينها باستخدام المؤشّر.

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

ويقبل التخزين نوع JSON في Effect ويعيد Effects مباشرةً.

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

### الأدوات

سجّل أدوات محدّدة النوع بـ`Schema` في Effect. ويتلقى المنفّذ إدخالًا مفكوك الترميز ويعيد Effectًا يحتوي مخرجات
محدّدة النوع أو محتوى عرض أو بيانات وصفية.

ويدعم المحرّر `add` و`update` و`remove`. ورد نداء التحويل متزامن: فلا يجوز أن يعيد Effect أو Promise. وحمّل
البيانات الخارجية قبل التسجيل أو إعادة التحميل. ويعيد OpenCode تشغيل التحويلات النشطة بترتيب التسجيل على محرّر
جديد؛ ولاسم الأداة الفعّال نفسه، يسود تسجيل صالح لاحق على تسجيل سابق.

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

واستدعِ `yield* ctx.tool.reload()` بعد تغيير بيانات المصدر التي التقطها رد النداء. فإعادة التحميل تعيد تشغيل التحويلات النشطة
دون تغيير ترتيبها؛ وهي لا تعيد تشغيل Effect الخاص بالملحق.

وتقبل أدوات Effect [إعلان الإدخال الحر](/ar/docs/build/plugins/server#freeform-tool-input) نفسه الذي تقبله أدوات Promise. وإذا لم يعلن النموذج تلك الصيغة، تحتفظ الأداة بإدخالها الكائني العادي.

وللأدوات `id` يحتوي اسمها الفعّال، ويعيد `get()` القيمة `undefined` عندما يغيب ذلك المعرّف. واستخدم
`update` و`remove` باسم الأداة الفعّال، بما في ذلك نطاقها (`acme_greeting` أعلاه). تُستبدل النقاط في النطاقات بـ`_`. وفي أسماء الأدوات، تبقى الحروف والأرقام و`_` و`-` كما هي، ويُستبدل أي محرف آخر بـ`_`. وتُتجاهل الأسماء الغائبة؛ وإنشاء أداة يحتاج
`add` بتعريف كامل. وتحفظ التحديثات الاسم والنطاق. وعيّن مخططات أو خيارات جديدة لتستبدلها
بدل تعديل القيم المتداخلة. وتُسجّل التحديثات غير الصالحة وتُبقي التعريف السابق سليمًا.

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

وتُعاد التحديثات والإزالات بالترتيب مع الإضافات، بما في ذلك بعد تحديثات كتالوج MCP.

ويعيد `transform` تسجيلًا محدود النطاق. وشغّل `yield* registration.dispose` لإزالة تحويله وإعادة البناء
من التحويلات المتبقية، فيعود أيّ تعريف سابق حلّ هذا التحويل محلّه. ولا يترتّب على تكرار الإلغاء أيّ أثر إضافي. ويؤدّي إغلاق
نطاق الملحق أيضًا إلى إلغاء تسجيلاته.

وكل طلب نموذج يلتقط لقطة أدوات. وتؤثر إعادة التحميل والتخلص في اللقطات المستقبلية، لا في التعريفات أو
المنفّذين الذين التقطهم طلب قائم أصلًا. والمنفّذون الذين يغلقون على بيانات ملحق متغيّرة يلاحظون
تلك البيانات مع ذلك؛ فالتقط قيمة داخل التحويل عندما يجب أن تبقى مرتبطة بذلك التعريف.

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

اقرأ معلومات المستودع أو حالة نسخة العمل أو فروق الملفات.

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

وسجّل مزوّدًا محدود النطاق بالموقع عبر تحويل محدود النطاق. ويُختار المزوّد المطابق لنوع المستودع المكتشف
تلقائيًا؛ واستخدم `editor.default.set` لاختيار مزوّد آخر.

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

وتتلقى ردود نداء المزوّد الموقع الحالي وجذر نسخة العمل وجذر المشروع الأساسي ومخزن المستودع
الاختياري. وتتلقى ردود نداء الفروق أيضًا الوضع المختار والسياق المطلوب وميزانية بايتات الإخراج. ويواصل اكتشاف المستودع
استخدام أدوات كشف Git وMercurial المدمجة في OpenCode.

ويمكن للمزوّدين اختياريًا تطبيق `init(scope)` لإنشاء مستودع في `scope.worktree`. وتختار التهيئة
المزوّد بمعرّفه (Git افتراضيًا)، لا بنوع المستودع المكتشف. وسجّل مزوّدًا فيه `init` حتى عندما
لا يكون للموقع مستودع بعد؛ فيتحقق OpenCode من وجود المجلد وخلوّه من مستودع قبل استدعائه،
ثم يعيد اكتشاف المشروع. ولا تزال صيغ المستودعات الجديدة تحتاج دعم اكتشاف يتجاوز رد النداء هذا.

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

### البحث على الويب

اسرد المزوّدين أو نفّذ استعلامًا عبر المزوّد المختار.

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

وسجّل منفّذ Effect واختر المزوّد الافتراضي. واضبط الافتراضي على `false` لتعطيل البحث على الويب.

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

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

### الأحداث

يأتي اشتراك أحداث الخادم العام في صورة `Stream` في Effect. شغّل قارئ البثّ بالتوازي داخل نطاق الملحق ليتوقّف
تلقائيًا عند إغلاق النطاق.

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

ومرّر `types` لتلقي أنواع الأحداث التي تحتاجها فقط. ويُحدَّد نوع التدفق وفقًا لذلك، فلا حاجة إلى حارس نوع.

```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`](/ar/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>
}
```

## الخطافات

تعترض الخطافات العمليات الجارية. ويمكن لعدة ملحقات تسجيل الخطاف نفسه؛ ويشغّلها OpenCode بترتيب الملحقات
فترى الخطافات اللاحقة التغييرات السابقة. وتبقى التسجيلات نشطة طوال نطاق الملحق.

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

### الجلسات

عدّل تعليمات النظام المجمّعة أو الرسائل أو الأدوات قبل إرسال الطلب إلى النموذج مباشرةً. ويعمل `context` في حلقة
الوكيل؛ ويعمل `compaction` و`generate` و`title` لتلك الطلبات المساعدة. ويقبل `compaction` و`title`
`result` يتخطى استدعاء النموذج.

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

وتحمل الرسائل في خطافات `context` و`compaction` و`generate` بيانات `metadata` لرسالتها المخزّنة، للقراءة فقط
(مثلًا ما ضبطه خطاف `prompt`). ولا تُرسل إلى النموذج.

ويسرد جزء `system` الذي يحمل تعليمات OpenCode كل مصدر أيضًا في `metadata.experimental.instructions` كـ
`{ key, text }`، مثل `core/date` أو `core/environment`، ليستطيع الخطاف تمييز المصادر. والقائمة نسخة:
فتعديل `text` في الجزء لا يحدّثها. وهذه ميزة تجريبية قد تتغيّر.

عدّل إعدادات طلب النموذج وحدّد نطاق الخطاف لمزوّد واحد اختياريًا. ويحمل الحدث `kind` نفسه
الذي تحمله خطافات 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" },
    )
  }),
```

عدّل طلبات المزوّد الأصلية أو استجاباته. فأجسامها تدفقات تُقرأ مرة واحدة؛ فانسخ الجسم أو استبدله قبل
قراءته. ويعمل الخطافان لكل طلب تصدره الجلسة؛ و`event.kind` هو `"primary"` أو `"compaction"` أو `"title"` أو
`"generate"` حسب التدفق الذي أصدره.

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

والمزوّدون الذين يبثّون عبر WebSocket يعيدون استخدام اتصال واحد لكل جلسة، فلا ترى خطافات HTTP تلك الحركة أبدًا. ويعمل
خطاف `experimental.ws.handshake` التجريبي مرة لكل استدعاء نموذج قبل اختيار الاتصال ويعرض
`url` و`headers` للاتصال؛ وتغيير أي منهما يعيد فتح المقبس. ولا تزال خطافات HTTP تعمل لأي طلب
يعود إليه مسار 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` و`experimental.ws.receive` الإطارات نفسها: فيعمل `send` بعد بناء سائق
المزوّد إطارًا صادرًا، ويعمل `receive` على كل إطار وارد قبل أن يلاحظه السائق. وما يحمله `frame` عند إرجاع الخطاف هو ما يعبر السلك أو يصل إلى السائق؛
ولا يتحقق منه OpenCode.

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

تجاوز قرار إعادة المحاولة لفشل مزوّد أو استبدل مهلة التأخير بالمللي ثانية. ويعمل الخطاف بعد أن يصنّف OpenCode
الفشل ويقترح سياسته، لكن قبل جدولة أي إعادة محاولة. ولا يعرض كيفية إجراء OpenCode
للمحاولة التالية داخليًا.

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

و`decision` الأولي هو سياسة OpenCode، فيمكن للخطافات جعل فشل مزوّد نهائي عادةً قابلًا لإعادة المحاولة أو نقض
إعادة محاولة مقترحة. وتعمل عدة خطافات بترتيب التسجيل وترى الخطافات اللاحقة القرار الحالي. ويبقى الحد الأقصى المدمج
لعدد المحاولات حدًّا صارمًا. و`attempt` المحاولة الفعلية المقترحة؛ فالطلب الأولي المحاولة `1`،
وأول إعادة محاولة المحاولة `2`. والتأخيرات غير الصالحة (`NaN` أو اللانهاية أو القيم السالبة) تعود إلى التأخير المحسوب.
ويبقى التعافي من فائض السياق منفصلًا لأنه يضغط المحادثة بدل إعادة محاولة الطلب نفسه.

#### Reference

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

عدّل أوامر shell أو مجلدات العمل أو المهل أو الملفات التنفيذية أو متغيّرات البيئة قبل التنفيذ.

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

#### Reference

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

### الأدوات

يمكن للخطافات التي تعمل قبل التنفيذ استبدال الإدخال أو إيقاف التنفيذ بخطأ `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 }),
    )
  }),
```

يمكن للخطافات التي تعمل بعد التنفيذ فحص النتائج الناجحة والأخطاء أو استبدالها.

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

#### Reference

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

وتوضّح أنواع التسجيل المشتركة أي العمليات تشترط نطاق الملحق.

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

## النشر

ويستخدم ملحق الحزمة التصدير الافتراضي نفسه الذي يستخدمه ملحق Effect محلي. فصدّر تطبيق Effect من نقطة الدخول
الرئيسية وأعلن `effect` كـ`peerDependency`. وتحت `devDependencies`، ثبّت الإصدار الذي يستخدمه `@opencode/plugin`
ليثبّت التطوير نسخة واحدة فقط.

```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 توجيه استيرادات `effect` والمسارات الفرعية المصدّرة `effect/*` و`@opencode/plugin` (بما في ذلك الاستيرادات من
التبعيات في `node_modules` الخاصة بالملحق) إلى نسخ وقت التشغيل في المضيف، لكي تتشارك وحدات التنفيذ الخفيفة وأدوات التسجيل ومحلّلات `Schema`
نسخة وقت تشغيل واحدة.

- لا تضمّن `effect` في ناتج الملحق المنشور. وإذا استخدمت أداة تجميع أثناء البناء، فاجعل `effect` و`effect/*`
  خارجيين.
- تنفّذ الملحقات وتوابعها في `node_modules` دائمًا مقابل نسخة `effect` الخاصة بإصدار OpenCode المضيف.
  فاستخدم واجهات `effect` ومسارات وحداته المتوافقة مع إصدار OpenCode الذي تستهدفه؛ والتوابع المبنية على إصدار
  `effect` رئيسي آخر (مثل Effect 3) تتلقى `effect` المضيف أيضًا ولا تُدعم.
- ولا تُوفَّر إلا المسارات الفرعية العامة لـ`effect`. والملحق الذي يستورد أحد وحدات `internal` الخاصة في Effect يفشل في
  التحميل بخطأ يسمّي المسار.
- ولا يتضمن ملف OpenCode المترجم أصول Scalar وSwagger UI التي تستخدمها صفحات وثائق HTTP API في Effect؛
  وعرض تلك الصفحات من ملحق يُظهر إشعارًا بدلًا من ذلك.

وتصدّر نقطة دخول الحزمة `Plugin.define` بدالة `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)
    }),
})
```

واستخدم إصدارات متوافقة مع إصدار OpenCode الذي تستهدفه واختبر الحزمة المثبّتة لا
نسخة مرتبطة بمساحة عمل فقط.

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