# Prime Agent Daemon-Worker Protocol: Core Files and Architecture Explained

> Understand the Prime Agent daemon-worker protocol's core files and architecture. Learn about supervisor, TypeScript workers, Unix sockets, authentication, and recovery.

- Repository: [Prime Intellect/prime-agent](https://github.com/PrimeIntellect-ai/prime-agent)
- Tags: architecture
- Published: 2026-08-12

---

**The daemon-worker protocol in Prime Agent relies on a supervisor process managing TypeScript workers through line-delimited JSON over Unix sockets, with strict authentication, lifecycle state machines, and recovery journaling.**

Prime Agent's **daemon-worker protocol** enables resilient, multi-session AI interactions by separating client-facing orchestration from heavy LLM computation. The architecture uses a supervisor (daemon) that spawns and monitors worker processes, communicating via a framed JSON protocol defined in the `packages/coding-agent/src/modes/daemon` directory. Understanding these files is essential for anyone extending Prime Agent or debugging worker crashes.

## Key Files in the Daemon-Worker Protocol

### daemon-worker-protocol.ts — Core Type Definitions

This file defines the fundamental contracts governing worker behavior. The **`DaemonWorkerLifecycle`** type enumerates valid states: `starting`, `ready`, `recovering`, `stopping`, and `failed`. Every worker transition is tracked and validated against this state machine.

The **`DaemonWorkerFrameHeader`** discriminated union prefixes all socket communication:

```typescript
export type DaemonWorkerFrameHeader =
	| { kind: "command"; requestId: string; commandType: string }
	| {
			kind: "outbound";
			requestId?: string;
			outboundType: DaemonOutbound["type"];
			activeSessionId?: string;
			snapshotId?: string;
	  };

```

Environment-based authentication lives here too. The **`isDaemonWorkerProcess()`** helper (lines 14-16) checks for `PRIME_AGENT_INTERNAL_DAEMON_WORKER="1"`, while **`waitForDaemonWorkerStartupGate()`** (lines 19-36) implements a file-descriptor gate that prevents workers from starting until the supervisor explicitly signals readiness.

### daemon-protocol.ts — Public Command and Event Contracts

All JSON-L (line-delimited JSON) messages flow through types defined here. The **`createDaemonCommandEnvelope()`** function (lines 73-85) wraps commands with protocol metadata:

```typescript
export function createDaemonCommandEnvelope<TCommand extends DaemonCommand>(
	command: TCommand,
	id: DaemonCommandId,
	clientId?: DaemonClientId,
	protocolVersion: DaemonProtocolVersion = DAEMON_PROTOCOL_VERSION,
): DaemonCommandEnvelope<TCommand> {
	return {
		type: "command",
		id,
		protocol: { name: DAEMON_PROTOCOL_NAME, version: protocolVersion },
		...(clientId ? { clientId } : {}),
		command,
	};
}

```

This file also maintains **`DAEMON_SCHEMA_REVISION = 16`** and **`DAEMON_SUPPORTED_CLIENT_CAPABILITIES`** arrays (lines 22-30), enabling version-aware capability negotiation between clients and the daemon.

### daemon-supervisor.ts — Worker Orchestration

The supervisor owns the Unix socket, accepts client connections (from the TUI or other interfaces), and manages the worker lifecycle. It maintains a registry of **`DaemonWorkerDescriptor`** objects tracking socket paths, PIDs, versions, and ownership metadata.

When spawning workers, the supervisor injects authentication tokens and startup gate file descriptors. It routes commands from clients to appropriate workers and aggregates outbound events for broadcast.

### daemon-worker-client.ts — Framed Message Encoding

This thin wrapper handles the mechanical work of sending framed JSON. It serializes **`DaemonCommandEnvelope`** objects, prepends the correct **`DaemonWorkerFrameHeader`**, and handles backpressure on the Unix socket. The client also decodes worker responses and validates headers using **`isDaemonWorkerFrameHeader()`** (lines 47-70 in [`daemon-worker-protocol.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-worker-protocol.ts)).

### daemon-socket.ts — Transport Layer

Implements Unix-domain-socket creation, connection handshaking, heartbeat monitoring, and graceful shutdown sequences. This isolation lets the protocol layer remain transport-agnostic while ensuring reliable process-to-process communication.

### daemon-supervisor-ownership.ts — Client-to-Worker Mapping

Tracks **`ownerClientId`** associations, enabling exclusive access patterns and clean handoffs when clients disconnect or workers need restart. This file also implements the recovery journal path resolution that enables session continuity after crashes.

### daemon-session-summarizer.ts — Recovery Snapshots

Periodically writes session-summary JSON files that record conversation state. Workers read these on recovery to reconstruct context, while the supervisor uses them to validate recovery eligibility.

## Worker Authentication and Startup Sequence

The daemon-worker protocol enforces a strict three-phase startup:

1. **Environment validation**: Worker detects `PRIME_AGENT_INTERNAL_DAEMON_WORKER="1"` via `isDaemonWorkerProcess()`

2. **Gate synchronization**: Worker blocks on `waitForDaemonWorkerStartupGate()` until the supervisor writes `"start\n"` to the passed file descriptor

3. **Token authentication**: Worker retrieves its token via `requireDaemonWorkerAuthenticationToken()` and validates against subsequent `worker_auth` commands

This sequence prevents race conditions and ensures only supervisor-spawned workers join the pool.

## Message Framing and Flow

All communication uses **line-delimited JSON**. Each logical message comprises:

- One line containing the **`DaemonWorkerFrameHeader`** (discriminates command vs. outbound)
- One line containing the payload (envelope or raw event)

The supervisor sends **command** frames; workers emit **outbound** frames carrying session events, snapshots, and status updates.

## Recovery and Journaling

Worker crashes trigger recovery via the journal system. The **`recoveryJournalPath`** in `DaemonWorkerDescriptor` points to a JSON file recording:

- Last known worker descriptor state
- Pending outbound messages not yet acknowledged

On restart, the worker replays these events, allowing connected clients to resume sessions transparently.

## Capability Versioning

The protocol uses explicit capability declarations rather than version sniffing. Clients advertise supported features; the daemon consults **`getDaemonCommandCompatibilities()`** (lines 54-66 in [`daemon-protocol.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-protocol.ts)) before issuing commands requiring specific capabilities like `"attach_snapshot"` or `"extension_ui"`.

## Summary

- **daemon-worker-protocol.ts** defines the lifecycle state machine, frame headers, and authentication primitives
- **daemon-protocol.ts** specifies JSON-L envelopes, commands, events, and capability tables
- **daemon-supervisor.ts** orchestrates worker spawning, client routing, and session management
- **daemon-worker-client.ts** handles message framing and socket I/O mechanics
- **daemon-socket.ts** provides reliable Unix-domain transport with heartbeats
- Recovery works through session summaries and journals managed by **daemon-session-summarizer.ts** and **daemon-supervisor-ownership.ts**
- Authentication combines environment variables, file-descriptor gates, and token validation to prevent unauthorized worker attachment

## Frequently Asked Questions

### What is the difference between the daemon and supervisor in Prime Agent?

**The terms are interchangeable in this codebase.** The "daemon" refers to the long-running parent process that owns the Unix socket and manages client connections; "supervisor" emphasizes its role spawning and monitoring workers. Both describe [`daemon-supervisor.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor.ts).

### How does the daemon-worker protocol prevent unauthorized worker connections?

**Three mechanisms work together:** the `PRIME_AGENT_INTERNAL_DAEMON_WORKER` environment flag identifies legitimate worker processes; a file-descriptor startup gate ensures workers block until the supervisor explicitly releases them; and a random token injected at spawn time must be presented in the initial `worker_auth` command. Missing any step causes immediate termination.

### What happens when a worker crashes during an active session?

**The supervisor detects the exit via process monitoring**, consults the `recoveryJournalPath` in the worker's descriptor, and may spawn a replacement worker. The new worker reads the session summarizer's JSON files and replay journal to reconstruct conversation state, then re-emits pending outbound events so clients can resume seamlessly.

### Where are the socket paths and protocol constants defined?

**Socket paths derive from runtime configuration**, while protocol constants live in [`daemon-protocol.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-protocol.ts): `DAEMON_PROTOCOL_NAME`, `DAEMON_PROTOCOL_VERSION`, and `DAEMON_SCHEMA_REVISION` control versioning, and `DAEMON_SUPPORTED_CLIENT_CAPABILITIES` arrays gate feature availability. These are imported by both supervisor and worker code to maintain contract consistency.