ملحقات Effect
@opencode/plugin/effect هو الإصدار الأصلي في Effect من API ملحقات OpenCode. تعيد عمليات السياق
Effects أو Streams، وتعيد دوال ردّ النداء Effects، ويمثّل Scope مدّة عمل الملحق.
ويوفّر OpenCode effect (بما في ذلك المسارات الفرعية المصدّرة effect/*) و@opencode/plugin وقت التشغيل عند تحميل
الملحقات وتبعياتها في node_modules. ثبّتهما ضمن التبعيات النظيرة وتبعيات التطوير للتحقّق من الأنواع والاختبار محليًا
بدل تضمينهما في ملحقك.
bun add --peer @opencode/plugin effect@4.0.1وصدّر ملحق Effect من .opencode/plugins/ ليُحمَّل تلقائيًا.
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 نفسه الذي تستخدمه ملحقات
الخادم الأخرى.
{
"$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 },
},
],
}راجع إعداد الملحقات للتفعيل وتحليل الحزم وأسبقية الإعداد.
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)
المرتبطة به وتشغيل دوال الإنهاء، ضمن عملية التنظيف نفسها.
import { Plugin } from "@opencode/plugin/effect"
import { Effect } from "effect"
export default Plugin.define({
id: "lifecycle",
effect: (ctx) =>
Effect.gen(function* () {
yield* Effect.logInfo("loaded", { version: ctx.app.version })
yield* Effect.addFinalizer(() => Effect.logInfo("unloaded"))
}),
})استخدم وحدات تنفيذ خفيفة مرتبطة بنطاق لتشغيل المهام في الخلفية. ويوقف نطاق الملحق هذه الوحدات أثناء تحرير موارده.
effect: (ctx) =>
Effect.gen(function* () {
const storage = ctx.storage
yield* Effect.repeat(
storage.set("heartbeat", { time: Date.now() }),
{ schedule: Schedule.spaced("1 minute") },
).pipe(Effect.forkScoped)
}),ويعرض السياق عميل Effect لخادم OpenCode المرتبط، إضافة إلى تحويلات وخطافات وتخزين وإعادات تحميل وخيارات خاصة بالملحقات. ولا يعرض خدمات Core الخاصة في OpenCode.
effect: (ctx) =>
Effect.gen(function* () {
const plugins = ctx.plugin
const active = yield* plugins.list().pipe(Effect.orDie)
yield* Effect.logInfo("active plugins", { count: active.data.length })
}),ويُعلن تعريف الملحق وسياقه الكامل كما يلي.
interface Context {
readonly app: App
readonly location: Location.Info
readonly options: PluginOptions
readonly agent: AgentDomain
readonly aisdk: AISDKDomain
readonly command: CommandDomain
readonly event: EventDomain
readonly experimental: {
readonly terminal: Pick<ExperimentalApi<unknown>["persistentPty"], "read">
readonly generate: GenerateApi<unknown>
}
readonly integration: IntegrationDomain
readonly mcp: MCPDomain
readonly model: ModelDomain
/** @deprecated Use `experimental.generate.text`. */
readonly generate: Pick<ExperimentalGenerateApi<unknown>, "text">
readonly permission: PermissionDomain
readonly plugin: Pick<PluginApi<unknown>, "list">
readonly provider: ProviderDomain
readonly reference: ReferenceDomain
readonly rpc: RpcDomain
readonly session: SessionDomain
readonly shell: ShellDomain
readonly skill: SkillDomain
readonly storage: StorageDomain
readonly tool: ToolDomain
readonly vcs: VcsDomain
readonly websearch: WebSearchDomain
readonly worktree: WorktreeDomain
}
interface Plugin<R = Scope.Scope> {
readonly id: string
readonly effect: (context: Context) => Effect.Effect<void, never, R>
}مرّر الخيارات بصيغة الكائن في opencode.json(c).
{
"plugins": [
{
"package": "./plugins/company-effect",
"options": { "strict": true },
},
],
}واقرأ الخيارات من ctx.options. وضيِّق القيم غير المعروفة قبل استخدامها.
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 عبر المُولِّد.
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,
})
})
}),
})يمكن لتحويل النماذج فرض سياسة تسري على جميع النماذج المرشّحة لدى المزوّدين النشطين.
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[] }؛ كما تُبطل إعادات تحميل المزوّد نتيجة النماذج كاملة.
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)
}),اقرأ كل الوكلاء أو اجلب وكيلًا بمعرّفه. وتضم استجابات العميل الموقع المحلول وبيانات المخطط.
effect: (ctx) =>
Effect.gen(function* () {
const agent = ctx.agent
const agents = yield* agent.list().pipe(Effect.orDie)
const build = yield* agent.get({ agentID: Agent.ID.make("build") }).pipe(Effect.orDie)
yield* Effect.logInfo("agents", { count: agents.data.length, build: build.data.name })
}),حوّل الوكلاء أو أعد تحميلهم.
effect: (ctx) =>
Effect.gen(function* () {
const agent = ctx.agent
yield* agent.transform((editor) => {
editor.default("build")
editor.update("build", (item) => (item.description = "Builds features and fixes bugs"))
editor.remove("legacy")
})
yield* agent.reload()
}),Schema: Agent.Info.
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>
}اقرأ المزوّدين المتاحين أو افحص بيانات مزوّد واحد الوصفية بمعرّفه.
effect: (ctx) =>
Effect.gen(function* () {
const provider = ctx.provider
const providers = yield* provider.list().pipe(Effect.orDie)
const anthropic = yield* provider.get({ providerID: Provider.ID.make("anthropic") }).pipe(Effect.orDie)
yield* Effect.logInfo("providers", {
providers: providers.data.length,
anthropic: anthropic.data.name,
})
}),وتعدّل تحويلات المزوّد إعدادات المزوّد وتعريفات المصادر. وتضم قراءات المحرّر المزوّدين غير النشطين وتعرض
تعريفات غير قابلة للتغيير؛ ويعدّل models.update نسخة مملوكة من نموذج مصدر.
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.provider.transform((editor) => {
editor.update("anthropic", (provider) => {
provider.headers = { ...provider.headers, "x-company": "engineering" }
})
editor.models.update("anthropic", "claude-sonnet-5-5", (model) => (model.name = "Team Sonnet"))
editor.models.remove("anthropic", "legacy-model")
editor.remove("legacy-provider")
})
}),واستبدل جرد مصدر بـmodels.set، ثم أعد التحميل بعد تغيّر تعريفاته الملتقطة.
effect: (ctx) =>
Effect.gen(function* () {
const provider = ctx.provider
const source = { models: yield* loadModels() }
yield* provider.transform((editor) => editor.models.set("acme", source.models))
source.models = yield* loadModels()
yield* provider.reload()
}),وللاكتشاف الخاص بحساب، مرّر الاتصال المستخدم لتحميل الجرد كـsourceConnection. ويستبعد OpenCode
ذلك المزوّد ما دام اتصال آخر مختارًا، حتى ينشر ملحقك جرده المحدّث.
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, Model.Info.
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>
}اقرأ النماذج المتاحة والاختيار الافتراضي.
effect: (ctx) =>
Effect.gen(function* () {
const model = ctx.model
const models = yield* model.list().pipe(Effect.orDie)
const selected = yield* model.default().pipe(Effect.orDie)
yield* Effect.logInfo("models", { count: models.data.length, selected: selected.data?.name })
}),تعدّل تحويلات النماذج المجموعة الكاملة للنماذج المرشّحة لدى المزوّدين النشطين. ويمكن تعديل النماذج المعطّلة إلى أن تنتهي كل
التحويلات، ولا يستطيع update إضافة نموذج إلا إلى مزوّد متاح.
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.model.transform((editor) => {
editor.list("anthropic").forEach((model) => {
editor.update(model.providerID, model.id, (draft) => {
draft.enabled = draft.capabilities.tools
})
})
editor.default.set("anthropic", "claude-sonnet-5-5")
editor.remove("anthropic", "legacy-model")
})
}),وتعدّل ردود النداء تجاوزات النموذج الخام. وتُدمج افتراضيات المزوّد مرة واحدة عندما يثبّت OpenCode النتيجة؛ وتعيد القراءات غير المتغيّرة
استخدام تلك النتيجة. ويقرأ editor.provider تعريفات المصادر غير القابلة للتغيير، بما في ذلك القوالب غير النشطة، لا
مخرجات تحويل النموذج.
effect: (ctx) =>
Effect.gen(function* () {
const model = ctx.model
yield* model.transform((editor) => {
const source = editor.provider.get("anthropic")?.models.get("claude-sonnet-5-5")
if (!source) return
editor.update("anthropic", source.id, (draft) => {
draft.limit.context = Math.min(draft.limit.context, source.limit.context)
})
})
yield* model.reload()
}),Schema: Model.Info.
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>
}اقرأ الأوامر المتاحة في الموقع الحالي.
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) })
}),وتحويل الأوامر الحالي للإضافة فقط. ويتلقى المنفّذ الجلسة ومرفقات المطالبة ووضع التسليم.
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,
Session.Inbox.Delivery.
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>
}اقرأ التكاملات وحلّ بيانات الاعتماد النشطة عندما توجد.
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 عبر الواجهة المرتبطة.
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 وقد تحصل على موارد محدودة النطاق.
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, Integration.Method,
Connection.Info, Form.Answer.
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 وحالة اتصالها الحالية.
effect: (ctx) =>
Effect.gen(function* () {
const mcp = ctx.mcp
const servers = yield* mcp.list().pipe(Effect.orDie)
yield* Effect.logInfo("MCP servers", { count: servers.data.length })
}),ولا تدير الملحقات خوادم MCP إلا عبر التحويلات. واستخدم editor.set لإضافة خادم أو استبداله، وeditor.update
لتغيير إعداده، وeditor.remove لإزالته. وافحص الإعداد بـeditor.list وeditor.get.
effect: (ctx) =>
Effect.gen(function* () {
const mcp = ctx.mcp
yield* mcp.transform((editor) => {
const servers = editor.list()
const docs = editor.get("docs")
editor.set("docs", { type: "remote", url: "https://mcp.example.com" })
editor.update("docs", (server) => (server.disabled = false))
editor.remove("legacy")
})
}),واضبط disabled: true في تحويل لتعطيل خادم وقطع اتصاله، أو disabled: false لتفعيله والسماح
لـOpenCode بالاتصال. ويوائم OpenCode دورة حياة الخادم من الإعداد المحوّل.
واستدعِ reload() بعد تغيّر حالة خارجية يستخدمها تحويل لإعادة تطبيق التحويلات ومواءمة الخوادم.
effect: (ctx) =>
Effect.gen(function* () {
const mcp = ctx.mcp
yield* mcp.reload()
}),Schemas: Mcp.Server, Mcp.LocalConfigEncoded,
Mcp.RemoteConfigEncoded.
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>
}اسرد الملحقات النشطة والفاشلة والمحلولة في الموقع الحالي.
effect: (ctx) =>
Effect.gen(function* () {
const plugin = ctx.plugin
const plugins = yield* plugin.list().pipe(Effect.orDie)
yield* Effect.forEach(plugins.data, (item) => Effect.logInfo("plugin", item), { discard: true })
}),وصفِّ قيم المخطط في خط أنابيب Effect عندما تهمّ الملحقات النشطة وحدها.
effect: (ctx) =>
Effect.gen(function* () {
const plugin = ctx.plugin
const active = yield* plugin.list().pipe(
Effect.orDie,
Effect.map((result) => result.data.filter((item) => item.state.status === "active")),
)
yield* Effect.logInfo("active plugin count", { count: active.length })
}),Schemas: Plugin.Info, Plugin.Source.
interface PluginApi<E = never> {
readonly list: PluginListOperation<E>
}
interface Context {
readonly plugin: PluginApi<unknown>
}اقرأ المراجع المتاحة في الموقع الحالي.
effect: (ctx) =>
Effect.gen(function* () {
const reference = ctx.reference
const references = yield* reference.list().pipe(Effect.orDie)
yield* Effect.logInfo("references", { count: references.data.length })
}),أضف المراجع المحلية ومراجع Git أو أزلها، ثم أعد التحميل بعد تغيّر الحالة الخارجية. ويعيد get(name) المصدر المضبوط
الحالي، أو undefined عندما يغيب الاسم.
effect: (ctx) =>
Effect.gen(function* () {
const reference = ctx.reference
yield* reference.transform((editor) => {
editor.add("handbook", { type: "local", path: "/workspace/docs/handbook" })
editor.add("standards", { type: "git", repository: "https://github.com/acme/standards", branch: "main" })
const handbook = editor.get("handbook")
editor.remove("legacy")
})
yield* reference.reload()
}),Schemas: Reference.Info, Reference.LocalSource,
Reference.GitSource.
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>
}أنشئ جلسة أو اقرأها، ثم اختر الوكيل والنموذج اللذين يستخدمهما العمل اللاحق.
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)
}),أرسل مطالبات أو طلبات توليد عابرة أو أوامر أو رسائل تركيبية.
effect: (ctx) =>
Effect.gen(function* () {
const session = ctx.session
const created = yield* session.create({ title: "Automation" }).pipe(Effect.orDie)
yield* session.prompt({ sessionID: created.id, text: "Review the current changes" }).pipe(Effect.orDie)
const summary = yield* session
.generate({ sessionID: created.id, prompt: "Summarize this project" })
.pipe(Effect.orDie)
yield* session.command({ sessionID: created.id, name: "review", text: "--staged" }).pipe(Effect.orDie)
yield* session
.synthetic({ sessionID: created.id, text: `Summary generated: ${summary.text}`, resume: false })
.pipe(Effect.orDie)
}),اسرد الجلسات صفحةً صفحة. وللحصول على الصفحة التالية، مرّر cursor.next مجددًا كـcursor. ويتذكّر المؤشر
مرشّحاتك، فلا تحتاج إلى تكرارها.
effect: (ctx) =>
Effect.gen(function* () {
const page = yield* ctx.session.list({ directory: ctx.location.directory, limit: 20 }).pipe(Effect.orDie)
const next = page.cursor.next
? yield* ctx.session.list({ cursor: page.cursor.next, limit: 20 }).pipe(Effect.orDie)
: undefined
}),وأزل جلسة مؤقتة بـremove. فالإزالة توقف التنفيذ النشط وتحذف الجلسات الفرعية تكراريًا.
effect: (ctx) =>
Effect.gen(function* () {
const created = yield* ctx.session.create({ title: "Temporary worker" }).pipe(Effect.orDie)
yield* ctx.session.remove({ sessionID: created.id }).pipe(Effect.orDie)
}),واطلب ضغط السياق بـcompact. فهو يعيد عنصر صندوق الوارد المقبول، لا ملخصًا مكتملًا؛ ويعمل الضغط عند
حدّ الخطوة التالي افتراضيًا. ومرّر delivery: "queue" للحفاظ على ترتيب قائمة الانتظار بدلًا من ذلك.
effect: (ctx) =>
Effect.gen(function* () {
const created = yield* ctx.session.create({ title: "Review" }).pipe(Effect.orDie)
const compaction = yield* ctx.session.compact({ sessionID: created.id }).pipe(Effect.orDie)
}),وأرفق إدخالات تعليمات الجلسة المفتاحية أو اسردها أو أزلها بـinstructions.entry. وتُعرض الإدخالات ككتل <context key="..."> في تعليمات الجلسة، وتُعلن التحديثات أو الإزالات عند حدّ الخطوة التالي دون وضع دورة رسالة في قائمة الانتظار.
effect: (ctx) =>
Effect.gen(function* () {
const created = yield* ctx.session.create({ title: "Review" }).pipe(Effect.orDie)
yield* ctx.session.instructions.entry
.put({ sessionID: created.id, key: "deploy-target", value: "production" })
.pipe(Effect.orDie)
const entries = yield* ctx.session.instructions.entry.list({ sessionID: created.id }).pipe(Effect.orDie)
yield* ctx.session.instructions.entry.remove({ sessionID: created.id, key: "deploy-target" }).pipe(Effect.orDie)
}),Schemas: Session.Info, Model.Ref,
Session.Inbox.User,
Session.Inbox.Synthetic,
InstructionEntry.Info.
type SessionDomain = Pick<
SessionApi<unknown>,
| "list"
| "create"
| "get"
| "remove"
| "switchAgent"
| "switchModel"
| "prompt"
| "generate"
| "command"
| "compact"
| "synthetic"
| "interrupt"
| "update"
| "move"
| "wait"
| "context"
| "instructions"
>اقرأ المهارات في الموقع الحالي.
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 عندما تغيب المهارة.
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.
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 دائمة محدودة النطاق بمعرّف الملحق واقرأها وأزلها.
effect: (ctx) =>
Effect.gen(function* () {
const storage = ctx.storage
yield* storage.set("settings", { strict: true })
const settings = yield* storage.get("settings")
yield* Effect.logInfo("settings", { settings })
yield* storage.remove("settings")
}),استعرض المفاتيح المطابقة لبادئة معيّنة على صفحات تتنقّل بينها باستخدام المؤشّر.
effect: (ctx) =>
Effect.gen(function* () {
const storage = ctx.storage
const first = yield* storage.scan({ prefix: "cache/", limit: 100 })
const second = first.next
? yield* storage.scan({ prefix: "cache/", after: first.next, limit: 100 })
: { entries: [] }
yield* Effect.logInfo("cache entries", { count: first.entries.length + second.entries.length })
}),ويقبل التخزين نوع JSON في Effect ويعيد Effects مباشرةً.
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 تشغيل التحويلات النشطة بترتيب التسجيل على محرّر
جديد؛ ولاسم الأداة الفعّال نفسه، يسود تسجيل صالح لاحق على تسجيل سابق.
effect: (ctx) =>
Effect.gen(function* () {
const tool = ctx.tool
yield* tool.transform((editor) => {
editor.namespace({
name: "acme",
description: "Customer account tools",
})
editor.add({
name: "greeting",
description: "Create a greeting",
input: Schema.Struct({ name: Schema.String }),
output: Schema.Struct({ greeting: Schema.String }),
options: { namespace: "acme", codemode: true },
execute: ({ name }, context) =>
Effect.gen(function* () {
yield* context.progress({ status: "greeting" })
return { output: { greeting: `Hello ${name}!` } }
}),
})
})
}),واستدعِ yield* ctx.tool.reload() بعد تغيير بيانات المصدر التي التقطها رد النداء. فإعادة التحميل تعيد تشغيل التحويلات النشطة
دون تغيير ترتيبها؛ وهي لا تعيد تشغيل Effect الخاص بالملحق.
وتقبل أدوات Effect إعلان الإدخال الحر نفسه الذي تقبله أدوات Promise. وإذا لم يعلن النموذج تلك الصيغة، تحتفظ الأداة بإدخالها الكائني العادي.
وللأدوات id يحتوي اسمها الفعّال، ويعيد get() القيمة undefined عندما يغيب ذلك المعرّف. واستخدم
update وremove باسم الأداة الفعّال، بما في ذلك نطاقها (acme_greeting أعلاه). تُستبدل النقاط في النطاقات بـ_. وفي أسماء الأدوات، تبقى الحروف والأرقام و_ و- كما هي، ويُستبدل أي محرف آخر بـ_. وتُتجاهل الأسماء الغائبة؛ وإنشاء أداة يحتاج
add بتعريف كامل. وتحفظ التحديثات الاسم والنطاق. وعيّن مخططات أو خيارات جديدة لتستبدلها
بدل تعديل القيم المتداخلة. وتُسجّل التحديثات غير الصالحة وتُبقي التعريف السابق سليمًا.
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, Tool.TextContent,
Tool.FileContent.
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>
}اقرأ معلومات المستودع أو حالة نسخة العمل أو فروق الملفات.
effect: (ctx) =>
Effect.gen(function* () {
const vcs = ctx.vcs
const info = yield* vcs.get().pipe(Effect.orDie)
const branches = yield* vcs.branch.list({ search: "feature", limit: 10 }).pipe(Effect.orDie)
const changes = yield* vcs.status().pipe(Effect.orDie)
const diff = yield* vcs.diff({ mode: "working", context: 3 }).pipe(Effect.orDie)
yield* Effect.logInfo("vcs", { branch: info.data.branch.current, files: changes.data.length })
}),وسجّل مزوّدًا محدود النطاق بالموقع عبر تحويل محدود النطاق. ويُختار المزوّد المطابق لنوع المستودع المكتشف
تلقائيًا؛ واستخدم editor.default.set لاختيار مزوّد آخر.
effect: (ctx) =>
Effect.gen(function* () {
const vcs = ctx.vcs
yield* vcs.transform((editor) => {
editor.add({
id: "custom",
name: "Custom VCS",
info: () => Effect.succeed({ branch: { current: "feature", default: "main" } }),
branches: (input) => readBranches(input),
status: (scope) => readStatus(scope.worktree),
diff: (input) => readDiff(input),
})
editor.default.set("custom")
})
}),وتتلقى ردود نداء المزوّد الموقع الحالي وجذر نسخة العمل وجذر المشروع الأساسي ومخزن المستودع الاختياري. وتتلقى ردود نداء الفروق أيضًا الوضع المختار والسياق المطلوب وميزانية بايتات الإخراج. ويواصل اكتشاف المستودع استخدام أدوات كشف Git وMercurial المدمجة في OpenCode.
ويمكن للمزوّدين اختياريًا تطبيق init(scope) لإنشاء مستودع في scope.worktree. وتختار التهيئة
المزوّد بمعرّفه (Git افتراضيًا)، لا بنوع المستودع المكتشف. وسجّل مزوّدًا فيه init حتى عندما
لا يكون للموقع مستودع بعد؛ فيتحقق OpenCode من وجود المجلد وخلوّه من مستودع قبل استدعائه،
ثم يعيد اكتشاف المشروع. ولا تزال صيغ المستودعات الجديدة تحتاج دعم اكتشاف يتجاوز رد النداء هذا.
Schemas: Vcs.Info, Vcs.FileStatus,
FileDiff.Info.
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.
}اسرد المزوّدين أو نفّذ استعلامًا عبر المزوّد المختار.
effect: (ctx) =>
Effect.gen(function* () {
const websearch = ctx.websearch
const providers = yield* websearch.providers().pipe(Effect.orDie)
const results = yield* websearch
.query({ query: "OpenCode plugins", providerID: WebSearch.ID.make("internal") })
.pipe(Effect.orDie)
yield* Effect.logInfo("websearch", { providers: providers.data.length, results: results.data.results.length })
}),وسجّل منفّذ Effect واختر المزوّد الافتراضي. واضبط الافتراضي على false لتعطيل البحث على الويب.
effect: (ctx) =>
Effect.gen(function* () {
const websearch = ctx.websearch
yield* websearch.transform((editor) => {
editor.add({
id: "internal",
name: "Internal search",
execute: ({ query }) => searchInternal(query),
})
editor.default.set("internal")
})
yield* websearch.reload()
}),Schemas: WebSearch.Provider,
WebSearch.Result.
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. شغّل قارئ البثّ بالتوازي داخل نطاق الملحق ليتوقّف
تلقائيًا عند إغلاق النطاق.
effect: (ctx) =>
Effect.gen(function* () {
const event = ctx.event
yield* event.subscribe().pipe(
Stream.tap((item) => Effect.logDebug("OpenCode event", { type: item.type })),
Stream.runDrain,
Effect.forkScoped,
)
}),ومرّر types لتلقي أنواع الأحداث التي تحتاجها فقط. ويُحدَّد نوع التدفق وفقًا لذلك، فلا حاجة إلى حارس نوع.
effect: (ctx) =>
Effect.gen(function* () {
const event = ctx.event
yield* event.subscribe({ types: ["config.updated"] }).pipe(
Stream.runForEach(() => Effect.logInfo("configuration changed")),
Effect.forkScoped,
)
}),Schema: V2EventEncoded.
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 بترتيب الملحقات فترى الخطافات اللاحقة التغييرات السابقة. وتبقى التسجيلات نشطة طوال نطاق الملحق.
effect: (ctx) =>
Effect.gen(function* () {
const session = ctx.session
yield* session.hook("context", () => Effect.void)
}),عدّل تعليمات النظام المجمّعة أو الرسائل أو الأدوات قبل إرسال الطلب إلى النموذج مباشرةً. ويعمل context في حلقة
الوكيل؛ ويعمل compaction وgenerate وtitle لتلك الطلبات المساعدة. ويقبل compaction وtitle
result يتخطى استدعاء النموذج.
effect: (ctx) =>
Effect.gen(function* () {
const session = ctx.session
yield* session.hook("context", (event) =>
Effect.sync(() => {
event.system.push({ type: "text", text: "Keep the review focused on correctness." })
delete event.tools.write
}),
)
yield* session.hook("compaction", (event) =>
Effect.map(summarize(event.messages), (summary) => {
event.result = { summary }
}),
)
}),وتحمل الرسائل في خطافات context وcompaction وgenerate بيانات metadata لرسالتها المخزّنة، للقراءة فقط
(مثلًا ما ضبطه خطاف prompt). ولا تُرسل إلى النموذج.
ويسرد جزء system الذي يحمل تعليمات OpenCode كل مصدر أيضًا في metadata.experimental.instructions كـ
{ key, text }، مثل core/date أو core/environment، ليستطيع الخطاف تمييز المصادر. والقائمة نسخة:
فتعديل text في الجزء لا يحدّثها. وهذه ميزة تجريبية قد تتغيّر.
عدّل إعدادات طلب النموذج وحدّد نطاق الخطاف لمزوّد واحد اختياريًا. ويحمل الحدث kind نفسه
الذي تحمله خطافات HTTP أدناه.
effect: (ctx) =>
Effect.gen(function* () {
const session = ctx.session
yield* session.hook(
"model.request",
(event) => Effect.sync(() => (event.headers["x-plugin"] = "review")),
{ providerID: "anthropic" },
)
}),عدّل طلبات المزوّد الأصلية أو استجاباته. فأجسامها تدفقات تُقرأ مرة واحدة؛ فانسخ الجسم أو استبدله قبل
قراءته. ويعمل الخطافان لكل طلب تصدره الجلسة؛ وevent.kind هو "primary" أو "compaction" أو "title" أو
"generate" حسب التدفق الذي أصدره.
effect: (ctx) =>
Effect.gen(function* () {
const session = ctx.session
yield* session.hook("http.request", (event) =>
Effect.sync(() => {
event.request.headers.set("x-session-id", event.sessionID)
if (event.kind === "title") event.request.headers.set("x-priority", "background")
}),
)
yield* session.hook("http.response", (event) =>
Effect.sync(() => {
event.response = new Response(event.response.body, {
status: event.response.status,
headers: { ...Object.fromEntries(event.response.headers), "x-plugin": "review" },
})
}),
)
}),والمزوّدون الذين يبثّون عبر WebSocket يعيدون استخدام اتصال واحد لكل جلسة، فلا ترى خطافات HTTP تلك الحركة أبدًا. ويعمل
خطاف experimental.ws.handshake التجريبي مرة لكل استدعاء نموذج قبل اختيار الاتصال ويعرض
url وheaders للاتصال؛ وتغيير أي منهما يعيد فتح المقبس. ولا تزال خطافات HTTP تعمل لأي طلب
يعود إليه مسار WebSocket.
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.session.hook(
"experimental.ws.handshake",
(event) =>
Effect.gen(function* () {
event.headers.authorization = `Bearer ${yield* mintToken(event.url)}`
delete event.headers["api-key"]
}),
{ providerID: "azure" },
)
}),ويعرض experimental.ws.send وexperimental.ws.receive الإطارات نفسها: فيعمل send بعد بناء سائق
المزوّد إطارًا صادرًا، ويعمل receive على كل إطار وارد قبل أن يلاحظه السائق. وما يحمله frame عند إرجاع الخطاف هو ما يعبر السلك أو يصل إلى السائق؛
ولا يتحقق منه OpenCode.
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.session.hook(
"experimental.ws.send",
(event) =>
Effect.sync(() => {
const body = JSON.parse(event.frame)
if (body.type === "response.create") body.metadata = { ...body.metadata, session: event.sessionID }
event.frame = JSON.stringify(body)
}),
{ providerID: "openai" },
)
}),تجاوز قرار إعادة المحاولة لفشل مزوّد أو استبدل مهلة التأخير بالمللي ثانية. ويعمل الخطاف بعد أن يصنّف OpenCode الفشل ويقترح سياسته، لكن قبل جدولة أي إعادة محاولة. ولا يعرض كيفية إجراء OpenCode للمحاولة التالية داخليًا.
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.session.hook("retry", (event) =>
Effect.sync(() => {
if (event.error.status === 429) {
event.decision = { retry: true, delay: 10_000 }
return
}
if (event.error.type === "provider.invalid-request" && event.attempt === 2) {
event.decision = { retry: true, delay: 0 }
return
}
if (event.attempt >= 3) event.decision = { retry: false }
}),
)
}),وdecision الأولي هو سياسة OpenCode، فيمكن للخطافات جعل فشل مزوّد نهائي عادةً قابلًا لإعادة المحاولة أو نقض
إعادة محاولة مقترحة. وتعمل عدة خطافات بترتيب التسجيل وترى الخطافات اللاحقة القرار الحالي. ويبقى الحد الأقصى المدمج
لعدد المحاولات حدًّا صارمًا. وattempt المحاولة الفعلية المقترحة؛ فالطلب الأولي المحاولة 1،
وأول إعادة محاولة المحاولة 2. والتأخيرات غير الصالحة (NaN أو اللانهاية أو القيم السالبة) تعود إلى التأخير المحسوب.
ويبقى التعافي من فائض السياق منفصلًا لأنه يضغط المحادثة بدل إعادة محاولة الطلب نفسه.
Reference
interface SessionHooks {
readonly context: SessionContext
readonly compaction: SessionCompaction
readonly generate: SessionGenerate
readonly title: SessionTitle
readonly "model.request": SessionModelRequest
readonly "http.request": SessionHttpRequest
readonly "http.response": SessionHttpResponse
readonly "experimental.ws.handshake": SessionWebSocketHandshake
readonly "experimental.ws.send": SessionWebSocketSend
readonly "experimental.ws.receive": SessionWebSocketReceive
readonly retry: SessionRetry
}
type RetryDecision = { retry: false } | { retry: true; delay: number }
interface SessionRetry {
readonly sessionID: string
readonly agent: string
readonly model: { providerID: string; id: string; variant?: string }
readonly error: { type: string; message: string; status?: number }
readonly attempt: number
decision: RetryDecision
}
interface SessionHookDomain {
readonly hook: ModelHooks<SessionHooks>
}عدّل أوامر shell أو مجلدات العمل أو المهل أو الملفات التنفيذية أو متغيّرات البيئة قبل التنفيذ.
effect: (ctx) =>
Effect.gen(function* () {
const shell = ctx.shell
yield* shell.hook("create.before", (event) =>
Effect.sync(() => {
if (event.command === "npm") event.command = "bun"
event.timeout = Math.min(event.timeout, 60_000)
event.env.COMPANY_ENV = "development"
}),
)
}),Reference
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.
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 }),
)
}),يمكن للخطافات التي تعمل بعد التنفيذ فحص النتائج الناجحة والأخطاء أو استبدالها.
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
interface ToolHooks {
readonly "execute.before": ToolExecuteBefore
readonly "execute.after": ToolExecuteAfter
}
interface ToolFailures extends Record<keyof ToolHooks, unknown> {
readonly "execute.before": Tool.Error
readonly "execute.after": never
}
interface ToolHookDomain {
readonly hook: Hooks<ToolHooks, ToolFailures>
}وتوضّح أنواع التسجيل المشتركة أي العمليات تشترط نطاق الملحق.
interface Registration {
readonly dispose: Effect.Effect<void>
}
type Hooks<Spec, Failures extends Record<keyof Spec, unknown> = Record<keyof Spec, never>> = <Name extends keyof Spec>(
name: Name,
callback: (input: Spec[Name]) => Effect.Effect<void, Failures[Name]>,
) => Effect.Effect<Registration, never, Scope.Scope>
type Transform<Input> = (callback: (input: Input) => void) => Effect.Effect<Registration, never, Scope.Scope>ويستخدم ملحق الحزمة التصدير الافتراضي نفسه الذي يستخدمه ملحق Effect محلي. فصدّر تطبيق Effect من نقطة الدخول
الرئيسية وأعلن effect كـpeerDependency. وتحت devDependencies، ثبّت الإصدار الذي يستخدمه @opencode/plugin
ليثبّت التطوير نسخة واحدة فقط.
{
"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.
import { Plugin } from "@opencode/plugin/effect"
import { Effect } from "effect"
export default Plugin.define({
id: "acme.published",
effect: (ctx) =>
Effect.gen(function* () {
const storage = ctx.storage
yield* storage.set("installed", true)
}),
})واستخدم إصدارات متوافقة مع إصدار OpenCode الذي تستهدفه واختبر الحزمة المثبّتة لا نسخة مرتبطة بمساحة عمل فقط.
bun pm pack
bun add ./opencode-acme-effect-plugin-1.0.0.tgz