Skip to content

DetachedAgent

Sessions that outlive the process that started them. Each session runs in its own host process, started detached; clients talk to it over a unix socket, and any process can attach to it again by session id, catch up on the events it missed, and keep controlling it.

The host process runs your own entry point, which runs SessionHost.run (see SessionHost.ts); host says how to start it:

const layer = DetachedAgent.layer({
provider: "claude",
host: {
command: process.execPath,
args: [fileURLToPath(new URL("./host.ts", import.meta.url))],
},
onScopeClose: "detach",
}).pipe(Layer.provide(NodeServices.layer))
// process A
const session = yield * (yield * Agent).open({ cwd })
yield * session.send("long task") // A may now exit; the session keeps running
// process B
const session = yield * (yield * AgentHosts).attach(sessionId)
yield * session.subscribeFrom(0).pipe(Stream.runForEach(persist))

DetachedAgent.layer provides Agent (so existing programs work unchanged) and AgentHosts (open typed as DetachedSession, attach, list, events). Hooks stay in the client: the host forwards each hook call to an attached client that has hooks (see AttachOptions).

Platform: the layer needs a ChildProcessSpawner (for status and history, which run locally), so provide NodeServices.layer or BunServices.layer. It talks to hosts over unix sockets through @effect/platform-node-shared, as both of those platforms do.

Hosts are started with detached: true and survive their caller, but a service manager may still kill them. A runner under systemd with the default KillMode=control-group has every process in its cgroup killed when it restarts, hosts included.

To prevent that, provide a Launcher that wraps the host in its own scope (systemd-run --user --scope ..., see Launcher.ts). It applies to the host command, so the host and the agent CLI it runs share that scope.

Since v0.1.0

Backoff from 100 ms, doubling, capped at 2 s between attempts; gives up after 30 s.

Signature

declare const defaultReconnect: Schedule.Schedule<
Duration.Duration,
unknown,
never,
never
>

Source

Since v0.1.0

Session id helper for ids read from elsewhere (e.g. a database).

Signature

declare const sessionId: (
input: string,
options?: Schema.MakeOptions,
) => string & Brand<"effect-agent/SessionId">

Source

Since v0.1.0

Agent and AgentHosts, running each session in its own host process.

Signature

declare const layer: (
options: DetachedAgentOptions,
) => Layer.Layer<Agent | AgentHosts, never, ChildProcessSpawner.ChildProcessSpawner>

Source

Since v0.1.0

Options for AgentHosts.attach.

Signature

export interface AttachOptions {
/**
* Answer the session's hook calls with these, whatever it was opened with
* (where the provider has hooks, a session registers all of them). Of the
* attached clients with a hook, the one that attached most recently answers
* it; a client attached without hooks never does. Fails if the session opened
* without hooks because a policy stops them (`info.capabilities.hooks`).
*/
readonly hooks?: Hooks
/** Override `DetachedAgentOptions.hookTimeout` for the calls this client answers. */
readonly hookTimeout?: Duration.Input
}

Source

Since v0.1.0

Options for layer.

Signature

export interface DetachedAgentOptions extends ProviderSpec {
/**
* Where hosts keep their sockets, manifests and logs. Default
* `HostSpec.defaultDir()`.
*/
readonly dir?: string
/**
* Events each host keeps in memory for `subscribeFrom`. With `persistEvents`
* this is a cache in front of the events file. Default 50 000.
*/
readonly maxEvents?: number
/**
* Hosts append every event to `<dir>/<sessionId>.events.jsonl` (mode 0600),
* so `subscribeFrom` can serve any seq, `awaitTurn` and `awaitMessage` any
* turn, and `AgentHosts.events` can read a session's log after its host has
* exited. Default true.
*/
readonly persistEvents?: boolean
/**
* How long an events file is kept after its host exits (from its mtime).
* Expired files are removed by `list`, `attach`, `events` and host startup.
* Default 24 hours.
*/
readonly retainEvents?: Duration.Input
/**
* When the connection to a host drops (other than by `detach`/`stop` or the
* session ending), re-dial it on this schedule: subscriptions resume from
* the last seq they delivered, and calls in flight are retried (`send`,
* `steer` and `turn` carry a request id, so the host acts on them once).
* Calls fail with `ConnectionLost` when the schedule gives up, or at once if the
* host is gone (manifest removed or pid dead). `false`: fail on the first
* drop. Default `defaultReconnect`.
*/
readonly reconnect?: Schedule.Schedule<unknown, AgentError> | false
/**
* How long a host waits for a client to answer a hook call before the hook
* adds nothing. Default 5 seconds. `open`/`attach` can override it per session.
*/
readonly hookTimeout?: Duration.Input
/** Internal, tests only (see `HostSpec.testDropBeforeReply`). */
readonly testDropBeforeReply?: ReadonlyArray<string>
/** Internal, tests only (see `HostSpec.testInvokeHook`). */
readonly testInvokeHook?: boolean
/**
* A host ends its session after this long idle with no client attached. Default 30
* minutes.
*/
readonly orphanTimeout?: Duration.Input
/** How long a host keeps serving after its session ends. Default 5 seconds. */
readonly linger?: Duration.Input
/**
* How to start a host process: a command that runs your entry point, which
* runs `SessionHost.run`. The `Launcher`, if any, wraps it.
*/
readonly host: Launcher.Command
/** How long `open` waits for the host to report it is ready. Default 60 seconds. */
readonly readyTimeout?: Duration.Input
/**
* What closing the Scope a session was opened (or attached) in does:
* `"stop"` (default) stops the session, as with a local session; `"detach"`
* only drops the connection, leaving the session running in its host.
*/
readonly onScopeClose?: "stop" | "detach"
}

Source

Since v0.1.0

AgentSession, plus what reattaching needs.

Signature

export interface DetachedSession extends AgentSession {
/** The host process's pid. */
readonly hostPid: number
readonly socket: string
/**
* Every event with `seq >= fromSeq`, then live ones, until the session
* ends. Survives reconnects with no gap or duplicate. Fails with
* `EventsTrimmed` rather than skipping events silently if `fromSeq` is older
* than the host's cache and the events file isn't there to read it from
* (`persistEvents: false`, or the file is missing or unreadable).
*/
readonly subscribeFrom: (
fromSeq: number,
) => Stream.Stream<SeqEvent, EventsTrimmed | SessionError>
/** The last event's sequence number (-1 before any). */
readonly lastSeq: Effect.Effect<number, SessionError>
readonly info: Effect.Effect<HostInfo, SessionError>
/**
* That turn's ending: at once if it already ended (even before a reattach),
* otherwise when it does. The host keeps the last 10 000 endings in memory
* and finds older ones in the events file; with `persistEvents: false`, an
* older one fails with `AgentError`.
*/
readonly awaitTurn: (
turnId: TurnId,
) => Effect.Effect<TurnSucceeded, TurnFailure | SessionError>
/**
* The ending of the turn a message landed in, by the `MessageId` that `send`
* returned: persist that, and a runner restarted mid-turn can pick the result
* up without knowing the turn id. Fails with `AgentError` if the message was
* dropped, never reached a turn, or wasn't sent through this host.
*/
readonly awaitMessage: (
messageId: MessageId,
) => Effect.Effect<TurnSucceeded, TurnFailure | SessionError>
/**
* Drop the connection and leave the session running. Calls made after it fail with
* `SessionClosed`.
*/
readonly detach: Effect.Effect<void>
/** Close the session now (killing its processes) and wait for the host to exit. */
readonly stop: Effect.Effect<void, SessionError>
}

Source

Since v0.1.0

What detached sessions add to Agent: open typed as DetachedSession, attach by session id, list of live hosts, and events for a session’s log.

Signature

declare class AgentHosts

Source

Since v0.1.0