Files
Kilo-Org_kilocode/packages/opencode/specs/effect-migration.md
T
Johnny Eric Amancio 7ea50aac14 OpenCode v1.3.3 (#8790)
* tweak: use theme tokens for debug bar surface

* chore: update nix node_modules hashes

* feat(tui): add heap snapshot functionality for TUI and server (#19028)

* ci

* change model for changelog

* release: v1.3.2

* fix(opencode): skip typechecking generated models snapshot (#19018)

* Revert "fix(app): more startup efficiency (#18985)"

This reverts commit 98b3340cee.

* Revert "fix(app): startup efficiency (#18854)"

This reverts commit 546748a461.

* effectify Worktree service (#18679)

* fix: increase operations-per-run to 1000 and pin stale action to v10.2.0

The stale-issues workflow was hitting the default 30 operations limit,
preventing it from processing all 2900+ issues/PRs. Increased to 1000
to handle the full backlog. Also pinned to exact v10.2.0 for reproducibility.

* Add close-issues script and GitHub Action

- Create script/github/close-issues.ts to close stale issues after 60 days
- Add GitHub Action workflow to run daily at 2 AM
- Remove old stale-issues workflow to avoid conflicts

* Fix close-issues workflow permissions

- Add contents: read permission for checkout
- Use github.token instead of secrets.GITHUB_TOKEN

* Process issues sequentially to avoid rate limits

* Change issue close reason from not_planned to completed

* fix(opencode): avoid snapshotting files over 2MB (#19043)

* fix: provide merge context to beta conflict resolver (#19055)

* tweak: only spawn lsp servers for files in current instance (or cwd if instance is global) (#19058)

* fix: beta resolver typecheck + build smoke check (#19060)

* fix: unblock beta conflict recovery (#19068)

* electron: add createDirectory to open directory picker (#19071)

* electron: remove file extension from electron-store wrapper (#19082)

* app: pre-warm project globalSync state when navigate project via keybind (#19088)

* fix(app): move message navigation off cmd+arrow (#18728)

* Reapply "fix(app): startup efficiency (#18854)"

This reverts commit a379eb3867.

* Reapply "fix(app): more startup efficiency (#18985)"

This reverts commit cbe1337f24.

* fix(app): hash inline script for csp

* Revert "fix(app): startup efficiency"

* Reapply "fix(app): startup efficiency"

This reverts commit 898456a25c.

* fix(app): opencode web server url

* chore(app): markdown playground in storyboard

* chore(app): markdown playground in storyboard

* feat(core): initial implementation of syncing (#17814)

* chore: generate

* chore: bump modelcontextprotocol/sdk to 1.27.1 (#19064)

* chore: storybook tweaks

* feat: restore git-backed review modes with effectful git service (#18900)

* chore: generate

* chore: update nix node_modules hashes

* chore: cleanup

* chore: remove dead code for todoread tool (#19128)

* chore: storybook tweaks

* fix(opencode): classify ZlibError from Bun fetch as retryable instead of unknown (#19104)

Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>

* fix(task): respect agent permission config for todowrite tool (#19125)

* fix(app): agent normalization (#19169)

* fix: Windows e2e stability (CrossSpawnSpawner, snapshot isolation, session race guards) (#19163)

* fix+refactor(mcp): lifecycle tests, cancelPending fix, Effect migration (#19042)

* effectify Bus service: migrate to Effect PubSub + InstanceState (#18579)

* file: use Effect.cached for scan deduplication (#19164)

* ignore: update disavowed list (#19184)

* skill: use Effect.cached for load deduplication (#19165)

* chore: generate

* fix: bump gitlab-ai-provider to 5.3.3 for DWS tool approval support (#19185)

* test: restore 5 workers on Windows e2e (#19188)

* fix(opencode): image paste on Windows Terminal 1.25+ with kitty keyboard (#17674)

* chore: update nix node_modules hashes

* wip: zen

* wip: zen

* go: do not respect disabled zen models

* fix: ensure enterprise url is set properly during auth flow (#19212)

* revert: roll back git-backed review modes (#19295)

* chore: generate

* tui: bypass local SSE event streaming in worker (#19183)

* feat: embed WebUI in binary with proxy flags (#19299)

Co-authored-by: BlankParticle <blankparticle@gmail.com>

* release: v1.3.3

* refactor: kilo compat for v1.3.3

* fix: Typecheck issues

* fix(build): normalize backslashes in web UI bundle import paths

Replace backslashes with forward slashes in embedded web UI file import
paths to ensure correct module resolution on Windows.

* fix: Add mcp reconnect error handling

* chore(script): use forward slashes in web UI bundle export keys

Ensure embedded file map keys use POSIX-style paths so lookups are
consistent across platforms.

* chore: regenerate source links

---------

Co-authored-by: Jay V <air@live.ca>
Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com>
Co-authored-by: Dax <mail@thdxr.com>
Co-authored-by: Dax Raad <d@ironbay.co>
Co-authored-by: opencode <opencode@sst.dev>
Co-authored-by: Kit Langton <kit.langton@gmail.com>
Co-authored-by: Adam <2363879+adamdotdevin@users.noreply.github.com>
Co-authored-by: Luke Parker <10430890+Hona@users.noreply.github.com>
Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
Co-authored-by: Brendan Allan <brendonovich@outlook.com>
Co-authored-by: Shoubhit Dash <shoubhit2005@gmail.com>
Co-authored-by: James Long <longster@gmail.com>
Co-authored-by: André Cruz <acruz@cloudflare.com>
Co-authored-by: Ariane Emory <97994360+ariane-emory@users.noreply.github.com>
Co-authored-by: Vladimir Glafirov <vglafirov@gitlab.com>
Co-authored-by: Frank <frank@anoma.ly>
Co-authored-by: BlankParticle <blankparticle@gmail.com>
Co-authored-by: Imanol Maiztegui <imanol.mzd@gmail.com>
2026-04-12 01:00:50 +02:00

6.7 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, Installation, Truncate
  • Instance-scoped (per-directory state via InstanceState): File, FileTime, FileWatcher, Format, Permission, Question, Skill, Snapshot, Vcs, ProviderAuth

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.ts split
  • runPromise goes inside the namespace (not exported unless tests need it)
  • Facade functions are plain async function — no fn() 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.Service at the layer level, then use Stream + forkScoped inside 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.acquireRelease or Effect.addFinalizer for 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, 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.

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.FileSystem instead of raw fs/promises for effectful file I/O
  • ChildProcessSpawner.ChildProcessSpawner with ChildProcess.make(...) instead of custom process wrappers
  • HttpClient.HttpClient instead of raw fetch
  • Path.Path instead of mixing path helpers into service code when you already need a path service
  • Config for effect-native configuration reads
  • Clock / DateTime for 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):

  • Accountaccount/index.ts
  • Authauth/index.ts (uses zod() helper for Schema→Zod interop)
  • Filefile/index.ts
  • FileTimefile/time.ts
  • FileWatcherfile/watcher.ts
  • Formatformat/index.ts
  • Installationinstallation/index.ts
  • Permissionpermission/index.ts
  • ProviderAuthprovider/auth.ts
  • Questionquestion/index.ts
  • Skillskill/index.ts
  • Snapshotsnapshot/index.ts
  • Truncatetool/truncate.ts
  • Vcsproject/vcs.ts
  • Discoveryskill/discovery.ts
  • SessionStatus

Still open and likely worth migrating:

  • Plugin
  • ToolRegistry
  • Pty
  • Worktree
  • Bus
  • Command
  • Config
  • Session
  • SessionProcessor
  • SessionPrompt
  • SessionCompaction
  • Provider
  • Project
  • LSP
  • MCP