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
12 changes: 6 additions & 6 deletions packages/cli/src/commands/handlers/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default Runtime.handler(
return yield* Effect.scoped(
Effect.gen(function* () {
const daemon = yield* Daemon.Service
const address = yield* listen(input.hostname, input.port, yield* daemon.password())
const address = yield* listen(input.hostname, input.port, yield* daemon.password(), input.register)
if (input.register) yield* daemon.register(address)
console.log(`server listening on ${HttpServer.formatAddress(address)}`)
return yield* Effect.never
Expand All @@ -27,18 +27,18 @@ export default Runtime.handler(
}),
)

function listen(hostname: string, port: Option.Option<number>, password: string) {
if (Option.isSome(port)) return bind(hostname, port.value, password)
function listen(hostname: string, port: Option.Option<number>, password: string, register: boolean) {
if (Option.isSome(port)) return bind(hostname, port.value, password, register)
const next = (port: number): ReturnType<typeof bind> =>
bind(hostname, port, password).pipe(
bind(hostname, port, password, register).pipe(
Effect.catch((error) => (port === 65_535 ? Effect.fail(error) : next(port + 1))),
)
return next(4096)
}

function bind(hostname: string, port: number, password: string) {
function bind(hostname: string, port: number, password: string, register: boolean) {
return Layer.build(
HttpRouter.serve(createRoutes(password), { disableListenLog: true, disableLogger: true }).pipe(
HttpRouter.serve(createRoutes(password, { daemon: register }), { disableListenLog: true, disableLogger: true }).pipe(
Layer.provideMerge(NodeHttpServer.layer(() => createServer(), { port, host: hostname })),
Layer.provide(AppNodeBuilder.build(LayerNode.group([Credential.node, PermissionSaved.node]))),
),
Expand Down
664 changes: 593 additions & 71 deletions packages/cli/src/services/daemon.ts

Large diffs are not rendered by default.

1,264 changes: 1,146 additions & 118 deletions packages/cli/test/services/daemon.test.ts

Large diffs are not rendered by default.

15 changes: 15 additions & 0 deletions packages/cli/test/services/fixtures/registration-worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Isolated process: register's ownership watcher can signal this worker,
// never the test runner. A sentinel requests normal scoped finalization.
import { Effect, Layer } from "effect"
import { existsSync } from "node:fs"
const awaitClose = () => existsSync(process.argv[3])
import { NodeFileSystem } from "@effect/platform-node"
const { Service, layer } = await import("../../../src/services/daemon")
await Effect.runPromise(
Effect.gen(function* () {
const daemon = yield* Service
yield* daemon.register({ _tag: "TcpAddress", hostname: "127.0.0.1", port: Number(process.argv[2]) })
process.stdout.write("ready\n")
while (!awaitClose()) yield* Effect.sleep("20 millis")
}).pipe(Effect.scoped, Effect.provide(layer.pipe(Layer.provide(NodeFileSystem.layer)))),
)
3 changes: 3 additions & 0 deletions packages/core/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ export interface Interface {
readonly compact: (input: CompactInput) => Effect.Effect<void, NotFoundError | OperationUnavailableError>
readonly wait: (id: SessionSchema.ID) => Effect.Effect<void, NotFoundError | OperationUnavailableError>
readonly active: Effect.Effect<ReadonlySet<SessionSchema.ID>>
/** Atomically stops accepting new runs when nothing is active. */
readonly stopIfIdle: Effect.Effect<SessionExecution.IdleStop>
readonly resume: (sessionID: SessionSchema.ID) => Effect.Effect<void, NotFoundError | SessionRunner.RunError>
readonly interrupt: (sessionID: SessionSchema.ID) => Effect.Effect<void>
readonly revert: {
Expand Down Expand Up @@ -444,6 +446,7 @@ const layer = Layer.effect(
return yield* new OperationUnavailableError({ operation: "wait" })
}),
active: execution.active,
stopIfIdle: execution.stopIfIdle,
resume: Effect.fn("V2Session.resume")(function* (sessionID) {
yield* result.get(sessionID)
yield* execution.resume(sessionID)
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/session/execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ export * as SessionExecution from "./execution"
import { Context, Effect, Layer } from "effect"
import { LayerNode } from "../effect/layer-node"
import { Node } from "../effect/app-node"
import { SessionRunCoordinator } from "./run-coordinator"
import { SessionRunner } from "./runner/index"
import { SessionSchema } from "./schema"

export type IdleStop = SessionRunCoordinator.IdleStop

export interface Interface {
/** Snapshots active execution owned by this process. */
readonly active: Effect.Effect<ReadonlySet<SessionSchema.ID>>
Expand All @@ -15,6 +18,12 @@ export interface Interface {
readonly wake: (sessionID: SessionSchema.ID) => Effect.Effect<void>
/** Interrupt active work owned by this process. Idle interruption is a no-op. */
readonly interrupt: (sessionID: SessionSchema.ID) => Effect.Effect<void>
/**
* Atomically stops this process from accepting new runs when nothing is
* active. `stopping` is a commitment: no run starts after it, so the caller
* can terminate the process without interrupting one.
*/
readonly stopIfIdle: Effect.Effect<IdleStop>
}

/** Routes execution from a Session ID to the runner owned by that Session's Location. */
Expand All @@ -30,5 +39,6 @@ export const noopLayer = Layer.succeed(
resume: () => Effect.void,
wake: () => Effect.void,
interrupt: () => Effect.void,
stopIfIdle: Effect.succeed({ status: "stopping" }),
}),
)
1 change: 1 addition & 0 deletions packages/core/src/session/execution/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const layer = Layer.effect(
interrupt: coordinator.interrupt,
resume: coordinator.run,
wake: coordinator.wake,
stopIfIdle: coordinator.stopIfIdle,
})
}),
)
Expand Down
28 changes: 27 additions & 1 deletion packages/core/src/session/run-coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ export * as SessionRunCoordinator from "./run-coordinator"

import { Deferred, Effect, Exit, Fiber, FiberSet, Scope } from "effect"

/** Outcome of an atomic idle-stop claim. */
export type IdleStop =
/** Nothing is active; new runs are refused from now on. */
| { readonly status: "stopping" }
/** Something is active, so the claim is refused. */
| { readonly status: "busy"; readonly activeRuns: number }

/** Serializes execution for each key while allowing different keys to run concurrently. */
export interface Coordinator<Key, E> {
/** Snapshots keys with an execution owned by this coordinator. */
Expand All @@ -12,6 +19,13 @@ export interface Coordinator<Key, E> {
readonly wake: (key: Key) => Effect.Effect<void>
/** Stops active execution and waits for its cleanup. */
readonly interrupt: (key: Key) => Effect.Effect<void>
/**
* Claims a stop while nothing is active. The check and the refusal of new
* runs happen in one synchronous step, so no execution can begin between
* them. Once claimed, `run` and `wake` are inert: recorded work stays
* durable and is picked up by whoever owns execution next.
*/
readonly stopIfIdle: Effect.Effect<IdleStop>
}

type Entry<E> = {
Expand All @@ -27,6 +41,7 @@ export const make = <Key, E>(options: {
Effect.gen(function* () {
const active = new Map<Key, Entry<E>>()
const fork = yield* FiberSet.makeRuntime<never, void, never>()
let stopping = false

const makeEntry = (): Entry<E> => ({
done: Deferred.makeUnsafe<void, E>(),
Expand Down Expand Up @@ -66,6 +81,10 @@ export const make = <Key, E>(options: {

const run = (key: Key): Effect.Effect<void, E> =>
Effect.uninterruptibleMask((restore) => {
// A claimed idle stop owns the rest of this process' lifetime, so a
// resume arriving after it is dropped instead of starting work that
// the stop would interrupt.
if (stopping) return Effect.void
const entry = active.get(key)
if (entry !== undefined) {
if (entry.stopping) return restore(Deferred.await(entry.done).pipe(Effect.andThen(run(key))))
Expand All @@ -80,6 +99,7 @@ export const make = <Key, E>(options: {

const wake = (key: Key) =>
Effect.sync(() => {
if (stopping) return
const entry = active.get(key)
if (entry !== undefined) {
entry.pendingWake = true
Expand All @@ -100,5 +120,11 @@ export const make = <Key, E>(options: {
return Fiber.interrupt(entry.owner)
})

return { active: Effect.sync(() => new Set(active.keys())), run, wake, interrupt }
const stopIfIdle: Effect.Effect<IdleStop> = Effect.sync(() => {
if (active.size > 0) return { status: "busy", activeRuns: active.size }
stopping = true
return { status: "stopping" }
})

return { active: Effect.sync(() => new Set(active.keys())), run, wake, interrupt, stopIfIdle }
})
1 change: 1 addition & 0 deletions packages/core/test/session-prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const execution = Layer.succeed(
Effect.sync(() => {
wakeCalls.push(sessionID)
}),
stopIfIdle: Effect.succeed({ status: "stopping" }),
}),
)
const it = testEffect(
Expand Down
71 changes: 71 additions & 0 deletions packages/core/test/session-run-coordinator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,77 @@ describe("SessionRunCoordinator", () => {
),
)

it.effect("claims an idle stop and then refuses every new run", () =>
Effect.scoped(
Effect.gen(function* () {
let runs = 0
const gate = yield* Deferred.make<void>()
const coordinator = yield* SessionRunCoordinator.make<string, never>({
drain: () => Effect.sync(() => runs++).pipe(Effect.andThen(Deferred.await(gate))),
})

expect(yield* coordinator.stopIfIdle).toEqual({ status: "stopping" })

yield* coordinator.wake("session")
yield* coordinator.run("session")
yield* Effect.yieldNow

expect(runs).toBe(0)
expect(Array.from(yield* coordinator.active)).toEqual([])
// A claimed stop stays claimed: no run may start behind the caller's
// shutdown, and a second claim is still granted rather than retried.
expect(yield* coordinator.stopIfIdle).toEqual({ status: "stopping" })
}),
),
)

it.effect("refuses the claim while a run is active", () =>
Effect.scoped(
Effect.gen(function* () {
const started = yield* Deferred.make<void>()
const gate = yield* Deferred.make<void>()
const coordinator = yield* SessionRunCoordinator.make<string, never>({
drain: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(gate))),
})

const running = yield* coordinator.run("session").pipe(Effect.forkChild)
yield* Deferred.await(started)

expect(yield* coordinator.stopIfIdle).toEqual({ status: "busy", activeRuns: 1 })
expect(Array.from(yield* coordinator.active)).toEqual(["session"])

yield* Deferred.succeed(gate, undefined)
yield* Fiber.join(running)

expect(yield* coordinator.stopIfIdle).toEqual({ status: "stopping" })
}),
),
)

it.effect("counts every active run in a refused claim", () =>
Effect.scoped(
Effect.gen(function* () {
const started = yield* Deferred.make<void>()
const gate = yield* Deferred.make<void>()
let active = 0
const coordinator = yield* SessionRunCoordinator.make<string, never>({
drain: () =>
Effect.sync(() => ++active).pipe(
Effect.andThen(Deferred.succeed(started, undefined)),
Effect.andThen(Deferred.await(gate)),
),
})

yield* coordinator.wake("first")
yield* Deferred.await(started)
yield* coordinator.wake("second")
yield* Effect.yieldNow

expect(yield* coordinator.stopIfIdle).toEqual({ status: "busy", activeRuns: 2 })
}),
),
)

it.effect("does nothing when interrupted while idle", () =>
Effect.scoped(
Effect.gen(function* () {
Expand Down
1 change: 1 addition & 0 deletions packages/core/test/session-runner-recorded.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ const execution = Layer.effect(
resume: coordinator.run,
wake: coordinator.wake,
interrupt: coordinator.interrupt,
stopIfIdle: coordinator.stopIfIdle,
})
}),
).pipe(Layer.provide(runnerLayer))
Expand Down
1 change: 1 addition & 0 deletions packages/core/test/session-runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ const execution = Layer.effect(
resume: coordinator.run,
wake: coordinator.wake,
interrupt: coordinator.interrupt,
stopIfIdle: coordinator.stopIfIdle,
})
}),
).pipe(Layer.provide(runnerLayer))
Expand Down
1 change: 1 addition & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"./*": "./src/*.ts"
},
"scripts": {
"test": "bun test --timeout 30000",
"typecheck": "tsgo --noEmit"
},
"dependencies": {
Expand Down
11 changes: 11 additions & 0 deletions packages/server/src/api.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import { HttpApi } from "effect/unstable/httpapi"
import { makeDefaultApi } from "@opencode-ai/protocol/api"
import { Authorization } from "@opencode-ai/protocol/middleware/authorization"
import { SchemaErrorMiddleware } from "@opencode-ai/protocol/middleware/schema-error"
import { LocationMiddleware } from "./location"
import { SessionLocationMiddleware } from "./middleware/session-location"
import { DaemonGroup } from "./groups/daemon"

export const Api = makeDefaultApi({
locationMiddleware: LocationMiddleware,
sessionLocationMiddleware: SessionLocationMiddleware,
})

// Separate from `Api` on purpose: the daemon endpoints are process controls for
// the background service, not part of the shared Protocol surface.
export const DaemonApi = HttpApi.make("server-daemon")
.add(DaemonGroup)
.middleware(Authorization)
.middleware(SchemaErrorMiddleware)
22 changes: 22 additions & 0 deletions packages/server/src/daemon-runs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export * as DaemonRuns from "./daemon-runs"

import { SessionV2 } from "@opencode-ai/core/session"
import { SessionExecution } from "@opencode-ai/core/session/execution"
import { Context, Effect, Layer } from "effect"

export interface Interface {
/** Atomically stops accepting new runs when nothing is active. */
readonly stopIfIdle: Effect.Effect<SessionExecution.IdleStop>
}

export class Service extends Context.Service<Service, Interface>()("@opencode/server/DaemonRuns") {}

// Reads the run state through the Session service that owns execution, so a
// claim is decided by the same coordinator that starts runs.
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const session = yield* SessionV2.Service
return Service.of({ stopIfIdle: session.stopIfIdle })
}),
)
29 changes: 29 additions & 0 deletions packages/server/src/daemon-stop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export * as DaemonStop from "./daemon-stop"

import { Context, Effect, Layer } from "effect"

export interface Interface {
/** Terminates the server process after an idle stop has been granted. */
readonly terminate: Effect.Effect<void>
}

export class Service extends Context.Service<Service, Interface>()("@opencode/server/DaemonStop") {}

/**
* Real teardown. The delay lets the granted response reach the client before
* the signal lands; the run gate is already closed by then, so nothing can
* start behind the response. SIGTERM matches how `service stop` ends the
* process, so registration cleanup behaves the same either way.
*/
export const layer = Layer.succeed(
Service,
Service.of({
terminate: Effect.sleep("250 millis").pipe(
Effect.andThen(
Effect.sync(() => {
process.kill(process.pid, "SIGTERM")
}),
),
),
}),
)
37 changes: 37 additions & 0 deletions packages/server/src/groups/daemon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi"

/**
* Daemon control surface. This group is intentionally not part of the shared
* Protocol API: it stops a server process, so only the background service
* started by `service start` (which owns its own process) mounts it.
*/
export class ActiveRunsError extends Schema.TaggedErrorClass<ActiveRunsError>()(
"ActiveRunsError",
{
message: Schema.String,
activeRuns: Schema.Number,
},
{ httpApiStatus: 409 },
) {}

/** The server could not verify its active-run state, so it refuses to stop. */
export class ActiveRunsUnknownError extends Schema.TaggedErrorClass<ActiveRunsUnknownError>()(
"ActiveRunsUnknownError",
{ message: Schema.String },
{ httpApiStatus: 503 },
) {}

export const DaemonGroup = HttpApiGroup.make("server.daemon").add(
HttpApiEndpoint.post("daemon.stopIfIdle", "/api/daemon/stop-if-idle", {
success: Schema.Struct({ data: Schema.Struct({ status: Schema.Literal("stopping") }) }),
error: [ActiveRunsError, ActiveRunsUnknownError],
}).annotateMerge(
OpenApi.annotations({
identifier: "daemon.stopIfIdle",
summary: "Stop the server when idle",
description:
"Stops this server process only when no run is active at request time. The idle check and the refusal of every later run are one atomic step, so the server cannot begin a run after it has accepted a stop. Responds 409 with the active run count while runs are active and 503 when the active-run state cannot be verified. Granted stops terminate the process after the response is written.",
}),
),
)
Loading
Loading