8.4 KiB
Effect patterns
Practical reference for new and migrated Effect code in packages/opencode.
Choose scope
Use InstanceState (from src/effect/instance-state.ts) for services that need per-directory state, per-instance cleanup, or project-bound background work. InstanceState uses a ScopedCache keyed by directory, so each open project gets its own copy of the state that is automatically cleaned up on disposal.
Use makeRuntime (from src/effect/run-service.ts) to create a per-service ManagedRuntime that lazily initializes and shares layers via a global memoMap. Returns { runPromise, runFork, runCallback }.
- Global services (no per-directory state): Account, Auth, AppFileSystem, Installation, Truncate, Worktree
- Instance-scoped (per-directory state via InstanceState): Agent, Bus, Command, Config, File, FileTime, FileWatcher, Format, LSP, MCP, Permission, Plugin, ProviderAuth, Pty, Question, SessionStatus, Skill, Snapshot, ToolRegistry, Vcs
Rule of thumb: if two open directories should not share one copy of the service, it needs InstanceState.
Service shape
Every service follows the same pattern — a single namespace with the service definition, layer, runPromise, and async facade functions:
export namespace Foo {
export interface Interface {
readonly get: (id: FooID) => Effect.Effect<FooInfo, FooError>
}
export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Foo") {}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
// For instance-scoped services:
const state = yield* InstanceState.make<State>(
Effect.fn("Foo.state")(() => Effect.succeed({ ... })),
)
const get = Effect.fn("Foo.get")(function* (id: FooID) {
const s = yield* InstanceState.get(state)
// ...
})
return Service.of({ get })
}),
)
// Optional: wire dependencies
export const defaultLayer = layer.pipe(Layer.provide(FooDep.layer))
// Per-service runtime (inside the namespace)
const { runPromise } = makeRuntime(Service, defaultLayer)
// Async facade functions
export async function get(id: FooID) {
return runPromise((svc) => svc.get(id))
}
}
Rules:
- Keep everything in one namespace, one file — no separate
service.ts/index.tssplit runPromisegoes inside the namespace (not exported unless tests need it)- Facade functions are plain
async function— nofn()wrappers - Use
Effect.fn("Namespace.method")for all Effect functions (for tracing) - No
Layer.fresh— InstanceState handles per-directory isolation
Schema → Zod interop
When a service uses Effect Schema internally but needs Zod schemas for the HTTP layer, derive Zod from Schema using the zod() helper from @/util/effect-zod:
import { zod } from "@/util/effect-zod"
export const ZodInfo = zod(Info) // derives z.ZodType from Schema.Union
See Auth.ZodInfo for the canonical example.
InstanceState init patterns
The InstanceState.make init callback receives a Scope, so you can use Effect.acquireRelease, Effect.addFinalizer, and Effect.forkScoped inside it. Resources acquired this way are automatically cleaned up when the instance is disposed or invalidated by ScopedCache. This makes it the right place for:
- Subscriptions: Yield
Bus.Serviceat the layer level, then useStream+forkScopedinside the init closure. The fiber is automatically interrupted when the instance scope closes:
const bus = yield * Bus.Service
const cache =
yield *
InstanceState.make<State>(
Effect.fn("Foo.state")(function* (ctx) {
// ... load state ...
yield* bus.subscribeAll().pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
/* handle */
}),
),
Effect.forkScoped,
)
return {
/* state */
}
}),
)
- Resource cleanup: Use
Effect.acquireReleaseorEffect.addFinalizerfor resources that need teardown (native watchers, process handles, etc.):
yield *
Effect.acquireRelease(
Effect.sync(() => nativeAddon.watch(dir)),
(watcher) => Effect.sync(() => watcher.close()),
)
- Background fibers: Use
Effect.forkScoped— the fiber is interrupted on disposal. - Side effects at init: Config notification, event wiring, etc. all belong in the init closure. Callers just do
InstanceState.get(cache)to trigger everything, andScopedCachededuplicates automatically.
The key insight: don't split init into a separate method with a started flag. Put everything in the InstanceState.make closure and let ScopedCache handle the run-once semantics.
Effect.cached for deduplication
Use Effect.cached when multiple concurrent callers should share a single in-flight computation. It memoizes the result and deduplicates concurrent fibers — second caller joins the first caller's fiber instead of starting a new one.
// Inside the layer — yield* to initialize the memo
let cached = yield * Effect.cached(loadExpensive())
const get = Effect.fn("Foo.get")(function* () {
return yield* cached // concurrent callers share the same fiber
})
// To invalidate: swap in a fresh memo
const invalidate = Effect.fn("Foo.invalidate")(function* () {
cached = yield* Effect.cached(loadExpensive())
})
Prefer Effect.cached over these patterns:
- Storing a
Fiber.Fiber | undefinedwith manual check-and-fork (e.g.file/index.tsensure) - Storing a
Promise<void>task for deduplication (e.g.skill/index.tsensure) let cached: X | undefinedwith check-and-load (races when two callers seeundefinedbefore either resolves)
Effect.cached handles the run-once + concurrent-join semantics automatically. For invalidatable caches, reassign with yield* Effect.cached(...) — the old memo is discarded.
Scheduled Tasks
For loops or periodic work, use Effect.repeat or Effect.schedule with Effect.forkScoped in the layer definition.
Preferred Effect services
In effectified services, prefer yielding existing Effect services over dropping down to ad hoc platform APIs.
Prefer these first:
FileSystem.FileSysteminstead of rawfs/promisesfor effectful file I/OChildProcessSpawner.ChildProcessSpawnerwithChildProcess.make(...)instead of custom process wrappersHttpClient.HttpClientinstead of rawfetchPath.Pathinstead of mixing path helpers into service code when you already need a path serviceConfigfor effect-native configuration readsClock/DateTimefor time reads inside effects
Child processes
For child process work in services, yield ChildProcessSpawner.ChildProcessSpawner in the layer and use ChildProcess.make(...).
Keep shelling-out code inside the service, not in callers.
Shared leaf models
Shared schema or model files can stay outside the service namespace when lower layers also depend on them.
That is fine for leaf files like schema.ts. Keep the service surface in the owning namespace.
Migration checklist
Fully migrated (single namespace, InstanceState where needed, flattened facade):
Account—account/index.tsAgent—agent/agent.tsAppFileSystem—filesystem/index.tsAuth—auth/index.ts(useszod()helper for Schema→Zod interop)Bus—bus/index.tsCommand—command/index.tsConfig—config/config.tsDiscovery—skill/discovery.ts(dependency-only layer, no standalone runtime)File—file/index.tsFileTime—file/time.tsFileWatcher—file/watcher.tsFormat—format/index.tsInstallation—installation/index.tsLSP—lsp/index.tsMCP—mcp/index.tsMcpAuth—mcp/auth.tsPermission—permission/index.tsPlugin—plugin/index.tsProject—project/project.tsProviderAuth—provider/auth.tsPty—pty/index.tsQuestion—question/index.tsSessionStatus—session/status.tsSkill—skill/index.tsSnapshot—snapshot/index.tsToolRegistry—tool/registry.tsTruncate—tool/truncate.tsVcs—project/vcs.tsWorktree—worktree/index.ts
Still open and likely worth migrating:
SessionSessionProcessorSessionPromptSessionCompactionProvider