Compare commits

..

9 Commits

Author SHA1 Message Date
Kit Langton 6ff4da5639 Merge branch 'dev' into kit/effectify-command 2026-03-20 15:14:01 -04:00
Kit Langton b6e94fd2a8 Merge branch 'dev' into kit/effectify-command 2026-03-20 09:17:34 -04:00
Kit Langton 3d5c041129 Merge branch 'dev' into kit/effectify-command 2026-03-19 21:16:40 -04:00
Kit Langton 3af557512b Merge branch 'dev' into kit/effectify-command 2026-03-19 19:27:53 -04:00
Kit Langton b53a95fd81 log errors in catchCause instead of silently swallowing 2026-03-19 16:23:07 -04:00
Kit Langton 8e11a46fe0 use forkScoped + Fiber.join for lazy init (match old Instance.state behavior) 2026-03-19 16:03:38 -04:00
Kit Langton 8ab4d84057 handle undefined command in session prompt 2026-03-19 15:17:00 -04:00
Kit Langton 4066247988 effectify Command service: migrate from Instance.state to Effect service pattern 2026-03-19 15:14:54 -04:00
Kit Langton b9de3ad370 fix(bus): tighten GlobalBus payload and BusEvent.define types
Constrain BusEvent.define to ZodObject instead of ZodType so TS knows
event properties are always a record. Type GlobalBus payload as
{ type: string; properties: Record<string, unknown> } instead of any.

Refactor watcher test to use Bus.subscribe instead of raw GlobalBus
listener, removing hand-rolled event types and unnecessary casts.
2026-03-19 15:12:21 -04:00
10 changed files with 342 additions and 373 deletions
+2 -2
View File
@@ -128,11 +128,11 @@ Still open and likely worth migrating:
- [ ] `Plugin` - [ ] `Plugin`
- [ ] `ToolRegistry` - [ ] `ToolRegistry`
- [x] `Pty` - [ ] `Pty`
- [ ] `Worktree` - [ ] `Worktree`
- [ ] `Installation` - [ ] `Installation`
- [ ] `Bus` - [ ] `Bus`
- [ ] `Command` - [x] `Command`
- [ ] `Config` - [ ] `Config`
- [ ] `Session` - [ ] `Session`
- [ ] `SessionProcessor` - [ ] `SessionProcessor`
+2 -2
View File
@@ -1,5 +1,5 @@
import z from "zod" import z from "zod"
import type { ZodType } from "zod" import type { ZodObject, ZodRawShape } from "zod"
import { Log } from "../util/log" import { Log } from "../util/log"
export namespace BusEvent { export namespace BusEvent {
@@ -9,7 +9,7 @@ export namespace BusEvent {
const registry = new Map<string, Definition>() const registry = new Map<string, Definition>()
export function define<Type extends string, Properties extends ZodType>(type: Type, properties: Properties) { export function define<Type extends string, Properties extends ZodObject<ZodRawShape>>(type: Type, properties: Properties) {
const result = { const result = {
type, type,
properties, properties,
+1 -1
View File
@@ -4,7 +4,7 @@ export const GlobalBus = new EventEmitter<{
event: [ event: [
{ {
directory?: string directory?: string
payload: any payload: { type: string; properties: Record<string, unknown> }
}, },
] ]
}>() }>()
+52 -18
View File
@@ -1,15 +1,18 @@
import { BusEvent } from "@/bus/bus-event" import { BusEvent } from "@/bus/bus-event"
import { InstanceContext } from "@/effect/instance-context"
import { runPromiseInstance } from "@/effect/runtime"
import { SessionID, MessageID } from "@/session/schema" import { SessionID, MessageID } from "@/session/schema"
import { Effect, Fiber, Layer, ServiceMap } from "effect"
import z from "zod" import z from "zod"
import { Config } from "../config/config" import { Config } from "../config/config"
import { Instance } from "../project/instance"
import { Identifier } from "../id/id"
import PROMPT_INITIALIZE from "./template/initialize.txt" import PROMPT_INITIALIZE from "./template/initialize.txt"
import PROMPT_REVIEW from "./template/review.txt" import PROMPT_REVIEW from "./template/review.txt"
import { MCP } from "../mcp" import { MCP } from "../mcp"
import { Skill } from "../skill" import { Skill } from "../skill"
import { Log } from "../util/log"
export namespace Command { export namespace Command {
const log = Log.create({ service: "command" })
export const Event = { export const Event = {
Executed: BusEvent.define( Executed: BusEvent.define(
"command.executed", "command.executed",
@@ -57,33 +60,46 @@ export namespace Command {
REVIEW: "review", REVIEW: "review",
} as const } as const
const state = Instance.state(async () => { export interface Interface {
readonly get: (name: string) => Effect.Effect<Info | undefined>
readonly list: () => Effect.Effect<Info[]>
}
export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Command") {}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const instance = yield* InstanceContext
const commands: Record<string, Info> = {}
const load = Effect.fn("Command.load")(function* () {
yield* Effect.promise(async () => {
const cfg = await Config.get() const cfg = await Config.get()
const result: Record<string, Info> = { commands[Default.INIT] = {
[Default.INIT]: {
name: Default.INIT, name: Default.INIT,
description: "create/update AGENTS.md", description: "create/update AGENTS.md",
source: "command", source: "command",
get template() { get template() {
return PROMPT_INITIALIZE.replace("${path}", Instance.worktree) return PROMPT_INITIALIZE.replace("${path}", instance.worktree)
}, },
hints: hints(PROMPT_INITIALIZE), hints: hints(PROMPT_INITIALIZE),
}, }
[Default.REVIEW]: { commands[Default.REVIEW] = {
name: Default.REVIEW, name: Default.REVIEW,
description: "review changes [commit|branch|pr], defaults to uncommitted", description: "review changes [commit|branch|pr], defaults to uncommitted",
source: "command", source: "command",
get template() { get template() {
return PROMPT_REVIEW.replace("${path}", Instance.worktree) return PROMPT_REVIEW.replace("${path}", instance.worktree)
}, },
subtask: true, subtask: true,
hints: hints(PROMPT_REVIEW), hints: hints(PROMPT_REVIEW),
},
} }
for (const [name, command] of Object.entries(cfg.command ?? {})) { for (const [name, command] of Object.entries(cfg.command ?? {})) {
result[name] = { commands[name] = {
name, name,
agent: command.agent, agent: command.agent,
model: command.model, model: command.model,
@@ -97,7 +113,7 @@ export namespace Command {
} }
} }
for (const [name, prompt] of Object.entries(await MCP.prompts())) { for (const [name, prompt] of Object.entries(await MCP.prompts())) {
result[name] = { commands[name] = {
name, name,
source: "mcp", source: "mcp",
description: prompt.description, description: prompt.description,
@@ -126,8 +142,8 @@ export namespace Command {
// Add skills as invokable commands // Add skills as invokable commands
for (const skill of await Skill.all()) { for (const skill of await Skill.all()) {
// Skip if a command with this name already exists // Skip if a command with this name already exists
if (result[skill.name]) continue if (commands[skill.name]) continue
result[skill.name] = { commands[skill.name] = {
name: skill.name, name: skill.name,
description: skill.description, description: skill.description,
source: "skill", source: "skill",
@@ -137,15 +153,33 @@ export namespace Command {
hints: [], hints: [],
} }
} }
})
return result
}) })
const loadFiber = yield* load().pipe(
Effect.catchCause((cause) => Effect.sync(() => log.error("init failed", { cause }))),
Effect.forkScoped,
)
const get = Effect.fn("Command.get")(function* (name: string) {
yield* Fiber.join(loadFiber)
return commands[name]
})
const list = Effect.fn("Command.list")(function* () {
yield* Fiber.join(loadFiber)
return Object.values(commands)
})
return Service.of({ get, list })
}),
)
export async function get(name: string) { export async function get(name: string) {
return state().then((x) => x[name]) return runPromiseInstance(Service.use((svc) => svc.get(name)))
} }
export async function list() { export async function list() {
return state().then((x) => Object.values(x)) return runPromiseInstance(Service.use((svc) => svc.list()))
} }
} }
@@ -124,7 +124,7 @@ export namespace Workspace {
await parseSSE(res.body, stop, (event) => { await parseSSE(res.body, stop, (event) => {
GlobalBus.emit("event", { GlobalBus.emit("event", {
directory: space.id, directory: space.id,
payload: event, payload: event as { type: string; properties: Record<string, unknown> },
}) })
}) })
// Wait 250ms and retry if SSE connection fails // Wait 250ms and retry if SSE connection fails
+3 -3
View File
@@ -1,10 +1,10 @@
import { Effect, Layer, LayerMap, ServiceMap } from "effect" import { Effect, Layer, LayerMap, ServiceMap } from "effect"
import { Command } from "@/command"
import { File } from "@/file/service" import { File } from "@/file/service"
import { FileTime } from "@/file/time-service" import { FileTime } from "@/file/time-service"
import { FileWatcher } from "@/file/watcher" import { FileWatcher } from "@/file/watcher"
import { Format } from "@/format/service" import { Format } from "@/format/service"
import { Permission } from "@/permission/service" import { Permission } from "@/permission/service"
import { Pty } from "@/pty"
import { Instance } from "@/project/instance" import { Instance } from "@/project/instance"
import { Vcs } from "@/project/vcs" import { Vcs } from "@/project/vcs"
import { ProviderAuth } from "@/provider/auth-service" import { ProviderAuth } from "@/provider/auth-service"
@@ -17,6 +17,7 @@ import { registerDisposer } from "./instance-registry"
export { InstanceContext } from "./instance-context" export { InstanceContext } from "./instance-context"
export type InstanceServices = export type InstanceServices =
| Command.Service
| Question.Service | Question.Service
| Permission.Service | Permission.Service
| ProviderAuth.Service | ProviderAuth.Service
@@ -25,7 +26,6 @@ export type InstanceServices =
| FileTime.Service | FileTime.Service
| Format.Service | Format.Service
| File.Service | File.Service
| Pty.Service
| Skill.Service | Skill.Service
| Snapshot.Service | Snapshot.Service
@@ -38,6 +38,7 @@ export type InstanceServices =
function lookup(_key: string) { function lookup(_key: string) {
const ctx = Layer.sync(InstanceContext, () => InstanceContext.of(Instance.current)) const ctx = Layer.sync(InstanceContext, () => InstanceContext.of(Instance.current))
return Layer.mergeAll( return Layer.mergeAll(
Command.layer,
Question.layer, Question.layer,
Permission.layer, Permission.layer,
ProviderAuth.defaultLayer, ProviderAuth.defaultLayer,
@@ -46,7 +47,6 @@ function lookup(_key: string) {
FileTime.layer, FileTime.layer,
Format.layer, Format.layer,
File.layer, File.layer,
Pty.layer,
Skill.defaultLayer, Skill.defaultLayer,
Snapshot.defaultLayer, Snapshot.defaultLayer,
).pipe(Layer.provide(ctx)) ).pipe(Layer.provide(ctx))
-4
View File
@@ -20,10 +20,6 @@ export function runPromiseInstance<A, E>(effect: Effect.Effect<A, E, InstanceSer
return runtime.runPromise(effect.pipe(Effect.provide(Instances.get(Instance.directory)))) return runtime.runPromise(effect.pipe(Effect.provide(Instances.get(Instance.directory))))
} }
export function runSyncInstance<A, E>(effect: Effect.Effect<A, E, InstanceServices>) {
return runtime.runSync(effect.pipe(Effect.provide(Instances.get(Instance.directory))))
}
export function disposeRuntime() { export function disposeRuntime() {
return runtime.dispose() return runtime.dispose()
} }
+63 -127
View File
@@ -1,12 +1,13 @@
import { BusEvent } from "@/bus/bus-event" import { BusEvent } from "@/bus/bus-event"
import { Bus } from "@/bus" import { Bus } from "@/bus"
import { InstanceContext } from "@/effect/instance-context"
import { type IPty } from "bun-pty" import { type IPty } from "bun-pty"
import z from "zod" import z from "zod"
import { Log } from "../util/log" import { Log } from "../util/log"
import { Instance } from "../project/instance"
import { lazy } from "@opencode-ai/util/lazy" import { lazy } from "@opencode-ai/util/lazy"
import { Shell } from "@/shell/shell"
import { Plugin } from "@/plugin"
import { PtyID } from "./schema" import { PtyID } from "./schema"
import { Effect, Layer, ServiceMap } from "effect"
export namespace Pty { export namespace Pty {
const log = Log.create({ service: "pty" }) const log = Log.create({ service: "pty" })
@@ -89,31 +90,9 @@ export namespace Pty {
subscribers: Map<unknown, Socket> subscribers: Map<unknown, Socket>
} }
export interface Interface { const state = Instance.state(
readonly list: () => Effect.Effect<Info[]> () => new Map<PtyID, ActiveSession>(),
readonly get: (id: PtyID) => Effect.Effect<Info | undefined> async (sessions) => {
readonly create: (input: CreateInput) => Effect.Effect<Info>
readonly update: (id: PtyID, input: UpdateInput) => Effect.Effect<Info | undefined>
readonly remove: (id: PtyID) => Effect.Effect<void>
readonly resize: (id: PtyID, cols: number, rows: number) => Effect.Effect<void>
readonly write: (id: PtyID, data: string) => Effect.Effect<void>
readonly connect: (
id: PtyID,
ws: Socket,
cursor?: number,
) => Effect.Effect<{ onMessage: (message: string | ArrayBuffer) => void; onClose: () => void } | undefined>
}
export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Pty") {}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const instance = yield* InstanceContext
const sessions = new Map<PtyID, ActiveSession>()
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
for (const session of sessions.values()) { for (const session of sessions.values()) {
try { try {
session.process.kill() session.process.kill()
@@ -121,41 +100,24 @@ export namespace Pty {
for (const [key, ws] of session.subscribers.entries()) { for (const [key, ws] of session.subscribers.entries()) {
try { try {
if (ws.data === key) ws.close() if (ws.data === key) ws.close()
} catch {} } catch {
// ignore
}
} }
} }
sessions.clear() sessions.clear()
}), },
) )
const removeSession = (id: PtyID) => { export function list() {
const session = sessions.get(id) return Array.from(state().values()).map((s) => s.info)
if (!session) return
sessions.delete(id)
log.info("removing session", { id })
try {
session.process.kill()
} catch {}
for (const [key, ws] of session.subscribers.entries()) {
try {
if (ws.data === key) ws.close()
} catch {}
}
session.subscribers.clear()
Bus.publish(Event.Deleted, { id: session.info.id })
} }
const list = Effect.fn("Pty.list")(function* () { export function get(id: PtyID) {
return Array.from(sessions.values()).map((s) => s.info) return state().get(id)?.info
}) }
const get = Effect.fn("Pty.get")(function* (id: PtyID) { export async function create(input: CreateInput) {
return sessions.get(id)?.info
})
const create = Effect.fn("Pty.create")(function* (input: CreateInput) {
return yield* Effect.promise(async () => {
const [{ Shell }, { Plugin }] = await Promise.all([import("@/shell/shell"), import("@/plugin")])
const id = PtyID.ascending() const id = PtyID.ascending()
const command = input.command || Shell.preferred() const command = input.command || Shell.preferred()
const args = input.args || [] const args = input.args || []
@@ -163,7 +125,7 @@ export namespace Pty {
args.push("-l") args.push("-l")
} }
const cwd = input.cwd || instance.directory const cwd = input.cwd || Instance.directory
const shellEnv = await Plugin.trigger("shell.env", { cwd }, { env: {} }) const shellEnv = await Plugin.trigger("shell.env", { cwd }, { env: {} })
const env = { const env = {
...process.env, ...process.env,
@@ -204,8 +166,9 @@ export namespace Pty {
cursor: 0, cursor: 0,
subscribers: new Map(), subscribers: new Map(),
} }
sessions.set(id, session) state().set(id, session)
ptyProcess.onData((chunk) => { ptyProcess.onData(
Instance.bind((chunk) => {
session.cursor += chunk.length session.cursor += chunk.length
for (const [key, ws] of session.subscribers.entries()) { for (const [key, ws] of session.subscribers.entries()) {
@@ -213,10 +176,12 @@ export namespace Pty {
session.subscribers.delete(key) session.subscribers.delete(key)
continue continue
} }
if (ws.data !== key) { if (ws.data !== key) {
session.subscribers.delete(key) session.subscribers.delete(key)
continue continue
} }
try { try {
ws.send(chunk) ws.send(chunk)
} catch { } catch {
@@ -229,21 +194,23 @@ export namespace Pty {
const excess = session.buffer.length - BUFFER_LIMIT const excess = session.buffer.length - BUFFER_LIMIT
session.buffer = session.buffer.slice(excess) session.buffer = session.buffer.slice(excess)
session.bufferCursor += excess session.bufferCursor += excess
}) }),
ptyProcess.onExit(({ exitCode }) => { )
ptyProcess.onExit(
Instance.bind(({ exitCode }) => {
if (session.info.status === "exited") return if (session.info.status === "exited") return
log.info("session exited", { id, exitCode }) log.info("session exited", { id, exitCode })
session.info.status = "exited" session.info.status = "exited"
Bus.publish(Event.Exited, { id, exitCode }) Bus.publish(Event.Exited, { id, exitCode })
removeSession(id) remove(id)
}) }),
)
Bus.publish(Event.Created, { info }) Bus.publish(Event.Created, { info })
return info return info
}) }
})
const update = Effect.fn("Pty.update")(function* (id: PtyID, input: UpdateInput) { export async function update(id: PtyID, input: UpdateInput) {
const session = sessions.get(id) const session = state().get(id)
if (!session) return if (!session) return
if (input.title) { if (input.title) {
session.info.title = input.title session.info.title = input.title
@@ -253,35 +220,54 @@ export namespace Pty {
} }
Bus.publish(Event.Updated, { info: session.info }) Bus.publish(Event.Updated, { info: session.info })
return session.info return session.info
}) }
const remove = Effect.fn("Pty.remove")(function* (id: PtyID) { export async function remove(id: PtyID) {
removeSession(id) const session = state().get(id)
}) if (!session) return
state().delete(id)
log.info("removing session", { id })
try {
session.process.kill()
} catch {}
for (const [key, ws] of session.subscribers.entries()) {
try {
if (ws.data === key) ws.close()
} catch {
// ignore
}
}
session.subscribers.clear()
Bus.publish(Event.Deleted, { id: session.info.id })
}
const resize = Effect.fn("Pty.resize")(function* (id: PtyID, cols: number, rows: number) { export function resize(id: PtyID, cols: number, rows: number) {
const session = sessions.get(id) const session = state().get(id)
if (session && session.info.status === "running") { if (session && session.info.status === "running") {
session.process.resize(cols, rows) session.process.resize(cols, rows)
} }
}) }
const write = Effect.fn("Pty.write")(function* (id: PtyID, data: string) { export function write(id: PtyID, data: string) {
const session = sessions.get(id) const session = state().get(id)
if (session && session.info.status === "running") { if (session && session.info.status === "running") {
session.process.write(data) session.process.write(data)
} }
}) }
const connect = Effect.fn("Pty.connect")(function* (id: PtyID, ws: Socket, cursor?: number) { export function connect(id: PtyID, ws: Socket, cursor?: number) {
const session = sessions.get(id) const session = state().get(id)
if (!session) { if (!session) {
ws.close() ws.close()
return return
} }
log.info("client connected to session", { id }) log.info("client connected to session", { id })
// Use ws.data as the unique key for this connection lifecycle.
// If ws.data is undefined, fallback to ws object.
const connectionKey = ws.data && typeof ws.data === "object" ? ws.data : ws const connectionKey = ws.data && typeof ws.data === "object" ? ws.data : ws
// Optionally cleanup if the key somehow exists
session.subscribers.delete(connectionKey) session.subscribers.delete(connectionKey)
session.subscribers.set(connectionKey, ws) session.subscribers.set(connectionKey, ws)
@@ -331,55 +317,5 @@ export namespace Pty {
cleanup() cleanup()
}, },
} }
})
return Service.of({ list, get, create, update, remove, resize, write, connect })
}),
)
function runtime() {
return require("@/effect/runtime") as typeof import("@/effect/runtime")
}
function run<A, E>(effect: Effect.Effect<A, E, Service>) {
return runtime().runPromiseInstance(effect)
}
function runSync<A, E>(effect: Effect.Effect<A, E, Service>) {
return runtime().runSyncInstance(effect)
}
// Sync facades
export function list() {
return runSync(Service.use((svc) => svc.list()))
}
export function get(id: PtyID) {
return runSync(Service.use((svc) => svc.get(id)))
}
export function resize(id: PtyID, cols: number, rows: number) {
runSync(Service.use((svc) => svc.resize(id, cols, rows)))
}
export function write(id: PtyID, data: string) {
runSync(Service.use((svc) => svc.write(id, data)))
}
export function connect(id: PtyID, ws: Socket, cursor?: number) {
return runSync(Service.use((svc) => svc.connect(id, ws, cursor)))
}
// Async facades
export async function create(input: CreateInput) {
return run(Service.use((svc) => svc.create(input)))
}
export async function update(id: PtyID, input: UpdateInput) {
return run(Service.use((svc) => svc.update(id, input)))
}
export async function remove(id: PtyID) {
return run(Service.use((svc) => svc.remove(id)))
} }
} }
+3
View File
@@ -1782,6 +1782,9 @@ NOTE: At any point in time through this workflow you should feel free to ask the
export async function command(input: CommandInput) { export async function command(input: CommandInput) {
log.info("command", input) log.info("command", input)
const command = await Command.get(input.command) const command = await Command.get(input.command)
if (!command) {
throw new NamedError.Unknown({ message: `Command not found: "${input.command}"` })
}
const agentName = command.agent ?? input.agent ?? (await Agent.defaultAgent()) const agentName = command.agent ?? input.agent ?? (await Agent.defaultAgent())
const raw = input.arguments.match(argsRegex) ?? [] const raw = input.arguments.match(argsRegex) ?? []
+7 -7
View File
@@ -16,7 +16,7 @@ const describeWatcher = FileWatcher.hasNativeBinding() && !process.env.CI ? desc
// Helpers // Helpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
type BusUpdate = { directory?: string; payload: { type: string; properties: WatcherEvent } } type BusUpdate = { directory?: string; payload: { type: string; properties: Record<string, unknown> } }
type WatcherEvent = { file: string; event: "add" | "change" | "unlink" } type WatcherEvent = { file: string; event: "add" | "change" | "unlink" }
/** Run `body` with a live FileWatcher service. */ /** Run `body` with a live FileWatcher service. */
@@ -40,18 +40,18 @@ function listen(directory: string, check: (evt: WatcherEvent) => boolean, hit: (
if (done) return if (done) return
if (evt.directory !== directory) return if (evt.directory !== directory) return
if (evt.payload.type !== FileWatcher.Event.Updated.type) return if (evt.payload.type !== FileWatcher.Event.Updated.type) return
if (!check(evt.payload.properties)) return const props = evt.payload.properties as WatcherEvent
hit(evt.payload.properties) if (!check(props)) return
hit(props)
} }
function cleanup() { GlobalBus.on("event", on)
return () => {
if (done) return if (done) return
done = true done = true
GlobalBus.off("event", on) GlobalBus.off("event", on)
} }
GlobalBus.on("event", on)
return cleanup
} }
function wait(directory: string, check: (evt: WatcherEvent) => boolean) { function wait(directory: string, check: (evt: WatcherEvent) => boolean) {