Practical reference for new and migrated Effect code in packages/opencode.
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 makeRunPromise (from src/effect/run-service.ts) to create a per-service ManagedRuntime that lazily initializes and shares layers via a global memoMap.
Rule of thumb: if two open directories should not share one copy of the service, it needs InstanceState.
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 = makeRunPromise(Service, defaultLayer)
// Async facade functions
export async function get(id: FooID) {
return runPromise((svc) => svc.get(id))
}
}
Rules:
service.ts / index.ts splitrunPromise goes inside the namespace (not exported unless tests need it)async function — no fn() wrappersEffect.fn("Namespace.method") for all Effect functions (for tracing)Layer.fresh — InstanceState handles per-directory isolationWhen 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.
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:
Effect.acquireRelease to subscribe and auto-unsubscribe:const cache =
yield *
InstanceState.make<State>(
Effect.fn("Foo.state")(function* (ctx) {
// ... load state ...
yield* Effect.acquireRelease(
Effect.sync(() =>
Bus.subscribeAll((event) => {
/* handle */
}),
),
(unsub) => Effect.sync(unsub),
)
return {
/* state */
}
}),
)
Effect.forkScoped — the fiber is interrupted on disposal.InstanceState.get(cache) to trigger everything, and ScopedCache deduplicates 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.
For loops or periodic work, use Effect.repeat or Effect.schedule with Effect.forkScoped in the layer definition.
In effectified services, prefer yielding existing Effect services over dropping down to ad hoc platform APIs.
Prefer these first:
FileSystem.FileSystem instead of raw fs/promises for effectful file I/OChildProcessSpawner.ChildProcessSpawner with ChildProcess.make(...) instead of custom process wrappersHttpClient.HttpClient instead of raw fetchPath.Path instead of mixing path helpers into service code when you already need a path serviceConfig for effect-native configuration readsClock / DateTime for time reads inside effectsFor 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 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.
Fully migrated (single namespace, InstanceState where needed, flattened facade):
Account — account/index.tsAuth — auth/index.ts (uses zod() helper for Schema→Zod interop)File — file/index.tsFileTime — file/time.tsFileWatcher — file/watcher.tsFormat — format/index.tsInstallation — installation/index.tsPermission — permission/index.tsProviderAuth — provider/auth.tsQuestion — question/index.tsSkill — skill/index.tsSnapshot — snapshot/index.tsTruncate — tool/truncate.tsVcs — project/vcs.tsDiscovery — skill/discovery.tsSessionStatusStill open and likely worth migrating:
PluginToolRegistryPtyWorktreeBusCommandConfigSessionSessionProcessorSessionPromptSessionCompactionProviderProjectLSPMCP