Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions packages/opencode/specs/effect-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ Use `InstanceState` (from `src/effect/instance-state.ts`) for services that need

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

Expand Down Expand Up @@ -181,36 +181,39 @@ That is fine for leaf files like `schema.ts`. Keep the service surface in the ow
Fully migrated (single namespace, InstanceState where needed, flattened facade):

- [x] `Account` — `account/index.ts`
- [x] `Agent` — `agent/agent.ts`
- [x] `AppFileSystem` — `filesystem/index.ts`
- [x] `Auth` — `auth/index.ts` (uses `zod()` helper for Schema→Zod interop)
- [x] `Bus` — `bus/index.ts`
- [x] `Command` — `command/index.ts`
- [x] `Config` — `config/config.ts`
- [x] `Discovery` — `skill/discovery.ts` (dependency-only layer, no standalone runtime)
- [x] `File` — `file/index.ts`
- [x] `FileTime` — `file/time.ts`
- [x] `FileWatcher` — `file/watcher.ts`
- [x] `Format` — `format/index.ts`
- [x] `Installation` — `installation/index.ts`
- [x] `LSP` — `lsp/index.ts`
- [x] `MCP` — `mcp/index.ts`
- [x] `McpAuth` — `mcp/auth.ts`
- [x] `Permission` — `permission/index.ts`
- [x] `Plugin` — `plugin/index.ts`
- [x] `Project` — `project/project.ts`
- [x] `ProviderAuth` — `provider/auth.ts`
- [x] `Pty` — `pty/index.ts`
- [x] `Question` — `question/index.ts`
- [x] `SessionStatus` — `session/status.ts`
- [x] `Skill` — `skill/index.ts`
- [x] `Snapshot` — `snapshot/index.ts`
- [x] `ToolRegistry` — `tool/registry.ts`
- [x] `Truncate` — `tool/truncate.ts`
- [x] `Vcs` — `project/vcs.ts`
- [x] `Discovery` — `skill/discovery.ts`
- [x] `SessionStatus`
- [x] `Worktree` — `worktree/index.ts`

Still open and likely worth migrating:

- [x] `Plugin`
- [x] `ToolRegistry`
- [ ] `Pty`
- [x] `Worktree`
- [x] `Bus`
- [x] `Command`
- [x] `Config`
- [ ] `Session`
- [ ] `SessionProcessor`
- [ ] `SessionPrompt`
- [ ] `SessionCompaction`
- [ ] `Provider`
- [x] `Project`
- [x] `LSP`
- [x] `MCP`
19 changes: 12 additions & 7 deletions packages/opencode/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,14 @@ export namespace Agent {
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const config = () => Effect.promise(() => Config.get())
const config = yield* Config.Service
const auth = yield* Auth.Service
const skill = yield* Skill.Service

const state = yield* InstanceState.make<State>(
Effect.fn("Agent.state")(function* (ctx) {
const cfg = yield* config()
const skillDirs = yield* Effect.promise(() => Skill.dirs())
const cfg = yield* config.get()
const skillDirs = yield* skill.dirs()
const whitelistedDirs = [Truncate.GLOB, ...skillDirs.map((dir) => path.join(dir, "*"))]

const defaults = Permission.fromConfig({
Expand Down Expand Up @@ -281,7 +282,7 @@ export namespace Agent {
})

const list = Effect.fnUntraced(function* () {
const cfg = yield* config()
const cfg = yield* config.get()
return pipe(
agents,
values(),
Expand All @@ -293,7 +294,7 @@ export namespace Agent {
})

const defaultAgent = Effect.fnUntraced(function* () {
const c = yield* config()
const c = yield* config.get()
if (c.default_agent) {
const agent = agents[c.default_agent]
if (!agent) throw new Error(`default agent "${c.default_agent}" not found`)
Expand Down Expand Up @@ -328,7 +329,7 @@ export namespace Agent {
description: string
model?: { providerID: ProviderID; modelID: ModelID }
}) {
const cfg = yield* config()
const cfg = yield* config.get()
const model = input.model ?? (yield* Effect.promise(() => Provider.defaultModel()))
const resolved = yield* Effect.promise(() => Provider.getModel(model.providerID, model.modelID))
const language = yield* Effect.promise(() => Provider.getLanguage(resolved))
Expand Down Expand Up @@ -391,7 +392,11 @@ export namespace Agent {
}),
)

export const defaultLayer = layer.pipe(Layer.provide(Auth.layer))
export const defaultLayer = layer.pipe(
Layer.provide(Auth.layer),
Layer.provide(Config.defaultLayer),
Layer.provide(Skill.defaultLayer),
)

const { runPromise } = makeRuntime(Service, defaultLayer)

Expand Down
28 changes: 19 additions & 9 deletions packages/opencode/src/command/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,12 @@ export namespace Command {
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service
const mcp = yield* MCP.Service
const skill = yield* Skill.Service

const init = Effect.fn("Command.state")(function* (ctx) {
const cfg = yield* Effect.promise(() => Config.get())
const cfg = yield* config.get()
const commands: Record<string, Info> = {}

commands[Default.INIT] = {
Expand Down Expand Up @@ -114,7 +118,7 @@ export namespace Command {
}
}

for (const [name, prompt] of Object.entries(yield* Effect.promise(() => MCP.prompts()))) {
for (const [name, prompt] of Object.entries(yield* mcp.prompts())) {
commands[name] = {
name,
source: "mcp",
Expand All @@ -139,14 +143,14 @@ export namespace Command {
}
}

for (const skill of yield* Effect.promise(() => Skill.all())) {
if (commands[skill.name]) continue
commands[skill.name] = {
name: skill.name,
description: skill.description,
for (const item of yield* skill.all()) {
if (commands[item.name]) continue
commands[item.name] = {
name: item.name,
description: item.description,
source: "skill",
get template() {
return skill.content
return item.content
},
hints: [],
}
Expand All @@ -173,7 +177,13 @@ export namespace Command {
}),
)

const { runPromise } = makeRuntime(Service, layer)
export const defaultLayer = layer.pipe(
Layer.provide(Config.defaultLayer),
Layer.provide(MCP.defaultLayer),
Layer.provide(Skill.defaultLayer),
)

const { runPromise } = makeRuntime(Service, defaultLayer)

export async function get(name: string) {
return runPromise((svc) => svc.get(name))
Expand Down
25 changes: 17 additions & 8 deletions packages/opencode/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import { Lock } from "@/util/lock"
import { AppFileSystem } from "@/filesystem"
import { InstanceState } from "@/effect/instance-state"
import { makeRuntime } from "@/effect/run-service"
import { Duration, Effect, Layer, ServiceMap } from "effect"
import { Duration, Effect, Layer, Option, ServiceMap } from "effect"

export namespace Config {
const ModelId = z.string().meta({ $ref: "https://models.dev/model-schema.json#/$defs/Model" })
Expand Down Expand Up @@ -1136,10 +1136,12 @@ export namespace Config {
}),
)

export const layer: Layer.Layer<Service, never, AppFileSystem.Service> = Layer.effect(
export const layer: Layer.Layer<Service, never, AppFileSystem.Service | Auth.Service | Account.Service> = Layer.effect(
Service,
Effect.gen(function* () {
const fs = yield* AppFileSystem.Service
const authSvc = yield* Auth.Service
const accountSvc = yield* Account.Service

const readConfigFile = Effect.fnUntraced(function* (filepath: string) {
return yield* fs.readFileString(filepath).pipe(
Expand Down Expand Up @@ -1256,7 +1258,7 @@ export namespace Config {
})

const loadInstanceState = Effect.fnUntraced(function* (ctx: InstanceContext) {
const auth = yield* Effect.promise(() => Auth.all())
const auth = yield* authSvc.all().pipe(Effect.orDie)

let result: Info = {}
for (const [key, value] of Object.entries(auth)) {
Expand Down Expand Up @@ -1344,17 +1346,20 @@ export namespace Config {
log.debug("loaded custom config from OPENCODE_CONFIG_CONTENT")
}

const active = yield* Effect.promise(() => Account.active())
const active = Option.getOrUndefined(yield* accountSvc.active().pipe(Effect.orDie))
if (active?.active_org_id) {
yield* Effect.gen(function* () {
const [config, token] = yield* Effect.promise(() =>
Promise.all([Account.config(active.id, active.active_org_id!), Account.token(active.id)]),
const [configOpt, tokenOpt] = yield* Effect.all(
[accountSvc.config(active.id, active.active_org_id!), accountSvc.token(active.id)],
{ concurrency: 2 },
)
const token = Option.getOrUndefined(tokenOpt)
if (token) {
process.env["OPENCODE_CONSOLE_TOKEN"] = token
Env.set("OPENCODE_CONSOLE_TOKEN", token)
}

const config = Option.getOrUndefined(configOpt)
if (config) {
result = mergeConfigConcatArrays(
result,
Expand All @@ -1365,7 +1370,7 @@ export namespace Config {
)
}
}).pipe(
Effect.catchDefect((err) => {
Effect.catch((err) => {
log.debug("failed to fetch remote account config", {
error: err instanceof Error ? err.message : String(err),
})
Expand Down Expand Up @@ -1502,7 +1507,11 @@ export namespace Config {
}),
)

export const defaultLayer = layer.pipe(Layer.provide(AppFileSystem.defaultLayer))
export const defaultLayer = layer.pipe(
Layer.provide(AppFileSystem.defaultLayer),
Layer.provide(Auth.layer),
Layer.provide(Account.defaultLayer),
)

const { runPromise } = makeRuntime(Service, defaultLayer)

Expand Down
5 changes: 4 additions & 1 deletion packages/opencode/src/effect/cross-spawn-spawner.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type * as Arr from "effect/Array"
import { NodeSink, NodeStream } from "@effect/platform-node"
import { NodeFileSystem, NodeSink, NodeStream } from "@effect/platform-node"
import * as NodePath from "@effect/platform-node/NodePath"
import * as Deferred from "effect/Deferred"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
Expand Down Expand Up @@ -474,3 +475,5 @@ export const layer: Layer.Layer<ChildProcessSpawner, never, FileSystem.FileSyste
ChildProcessSpawner,
make,
)

export const defaultLayer = layer.pipe(Layer.provide(NodeFileSystem.layer), Layer.provide(NodePath.layer))
8 changes: 6 additions & 2 deletions packages/opencode/src/file/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ export namespace FileWatcher {
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service

const state = yield* InstanceState.make(
Effect.fn("FileWatcher.state")(
function* () {
Expand Down Expand Up @@ -117,7 +119,7 @@ export namespace FileWatcher {
)
}

const cfg = yield* Effect.promise(() => Config.get())
const cfg = yield* config.get()
const cfgIgnores = cfg.watcher?.ignore ?? []

if (yield* Flag.OPENCODE_EXPERIMENTAL_FILEWATCHER) {
Expand Down Expand Up @@ -159,7 +161,9 @@ export namespace FileWatcher {
}),
)

const { runPromise } = makeRuntime(Service, layer)
export const defaultLayer = layer.pipe(Layer.provide(Config.defaultLayer))

const { runPromise } = makeRuntime(Service, defaultLayer)

export function init() {
return runPromise((svc) => svc.init())
Expand Down
8 changes: 6 additions & 2 deletions packages/opencode/src/format/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ export namespace Format {
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service

const state = yield* InstanceState.make(
Effect.fn("Format.state")(function* (_ctx) {
const enabled: Record<string, boolean> = {}
const formatters: Record<string, Formatter.Info> = {}

const cfg = yield* Effect.promise(() => Config.get())
const cfg = yield* config.get()

if (cfg.formatter !== false) {
for (const item of Object.values(Formatter)) {
Expand Down Expand Up @@ -167,7 +169,9 @@ export namespace Format {
}),
)

const { runPromise } = makeRuntime(Service, layer)
export const defaultLayer = layer.pipe(Layer.provide(Config.defaultLayer))

const { runPromise } = makeRuntime(Service, defaultLayer)

export async function init() {
return runPromise((s) => s.init())
Expand Down
5 changes: 1 addition & 4 deletions packages/opencode/src/installation/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { NodeFileSystem, NodePath } from "@effect/platform-node"
import { Effect, Layer, Schema, ServiceMap, Stream } from "effect"
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
Expand Down Expand Up @@ -341,9 +340,7 @@ export namespace Installation {

export const defaultLayer = layer.pipe(
Layer.provide(FetchHttpClient.layer),
Layer.provide(CrossSpawnSpawner.layer),
Layer.provide(NodeFileSystem.layer),
Layer.provide(NodePath.layer),
Layer.provide(CrossSpawnSpawner.defaultLayer),
)

const { runPromise } = makeRuntime(Service, defaultLayer)
Expand Down
8 changes: 6 additions & 2 deletions packages/opencode/src/lsp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,11 @@ export namespace LSP {
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service

const state = yield* InstanceState.make<State>(
Effect.fn("LSP.state")(function* () {
const cfg = yield* Effect.promise(() => Config.get())
const cfg = yield* config.get()

const servers: Record<string, LSPServer.Info> = {}

Expand Down Expand Up @@ -504,7 +506,9 @@ export namespace LSP {
}),
)

const { runPromise } = makeRuntime(Service, layer)
export const defaultLayer = layer.pipe(Layer.provide(Config.defaultLayer))

const { runPromise } = makeRuntime(Service, defaultLayer)

export const init = async () => runPromise((svc) => svc.init())

Expand Down
Loading
Loading