# How to Monitor PrimeAgent's Activity: Real-Time Health, Workload, and Token Tracking

> Learn how to monitor PrimeAgent activity effectively. Track real-time health, workload, and token usage with CLI commands, RPC endpoints, logs, and the activity tracker class.

- Repository: [Prime Intellect/prime-agent](https://github.com/PrimeIntellect-ai/prime-agent)
- Tags: how-to-guide
- Published: 2026-09-08

---

**PrimeAgent exposes real-time health, workload, and token usage through a combination of CLI commands, RPC endpoints, rotating log files, and an activity tracker class that reports status to both the TUI and programmatic interfaces.**

PrimeAgent (from the `PrimeIntellect-ai/prime-agent` repository) continuously monitors its own operational state through several tightly-coupled TypeScript components. Whether you need a quick health check from the command line or deep programmatic integration via RPC, the codebase provides multiple observability layers that track everything from supervisor socket presence to cumulative token consumption.

## Core Monitoring Components

PrimeAgent's monitoring architecture consists of six primary components that work together to provide full visibility into the system:

| Component | Monitors | Source Location | Reporting Method |
|---|---|---|---|
| **Daemon Supervisor** | Public supervisor socket presence, worker heartbeats, supervisor lease ownership | [`daemon-supervisor.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor.ts) | Emits log lines via `appendRotatingLog` and updates `SupervisorOwnershipRecord` |
| **Supervisor Ownership** | Generation, PID, and token identifying the current supervisor instance | [`daemon-supervisor-ownership.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor-ownership.ts) | Throws errors like `supervisor_generation_stale` caught during startup |
| **Agent Activity Tracker** | Token count, flow direction (↑/↓), and activity labels (*thinking*, *working*) | [`agent-activity.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/agent-activity.ts) | Provides `AgentActivityStatus` objects to UI and RPC layers |
| **RPC / TUI Status Events** | Real-time connection state and session status | [`rpc-client.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/rpc-client.ts) and [`interactive-mode.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/interactive-mode.ts) | Exposes `agent_messages_status` command and renders colored badges |
| **CLI Status Command** | Daemon state snapshot including socket path, PID, and active sessions | [`package-manager-cli.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/package-manager-cli.ts) | `prime-agent status` with optional `--json` output |
| **Rotating Log Files** | Full chronological trace of daemon and supervisor actions | `daemon.log` in agent directory | File system logs accessed via `tail` or `prime-agent doctor --full` |

## Real-Time Daemon Health Monitoring

### Supervisor Socket and Lease Management

The `DaemonSupervisor` class in [`packages/coding-agent/src/modes/daemon/daemon-supervisor.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts) maintains the primary health loop for the system. When the daemon starts, `DaemonSupervisor.start()` creates a Unix-socket listener at `this.socketPath` and writes a **supervisor config** file containing the generation, PID, and token (lines 1034–1038).

The supervisor continuously validates socket presence and worker heartbeats. If the socket disappears, the event loop logs the loss via `appendRotatingLog` and triggers a supervisor restart (see the recovery logic referenced in [`daemon.md`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon.md) at line 36). The internal `SupervisorOwnershipRecord` tracks lease ownership state throughout this process.

### Ownership Validation and Error Handling

The [`daemon-supervisor-ownership.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor-ownership.ts) module stores the unique identifiers (generation, PID, token) that distinguish legitimate supervisor instances. When workers connect, they receive the supervisor's authentication claim via `supervisorAuthenticationClaim()` and validate it against the registry entry.

If validation fails—such as when a stale supervisor attempts to claim ownership—the system throws a **`supervisor_generation_stale`** error. The supervisor's startup routine catches these exceptions to prevent split-brain scenarios and ensure only one supervisor manages the worker pool at a time.

## Tracking Agent Activity and Token Usage

### The Agent Activity Tracker Class

Located in [`packages/coding-agent/src/modes/interactive/agent-activity.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/interactive/agent-activity.ts), the `AgentActivityTracker` class maintains granular visibility into session-level operations. `InteractiveMode` instantiates this tracker when a session begins, routing all incoming events through `activityTracker.handleEvent(event)`.

The tracker maintains rolling statistics including:

- **Token count**: Cumulative tokens used in the current session
- **Direction**: Token flow indicator (↑ for output, ↓ for input)
- **Activity labels**: High-level states like *"thinking"*, *"working"*, or *"idle"*

Access the current status programmatically by calling `activityTracker.getStatus()`, which returns an `AgentActivityStatus` object containing these fields.

## Accessing Status via CLI and Logs

### The `prime-agent status` Command

For operational health checks, the CLI entry point (implemented in [`package-manager-cli.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/package-manager-cli.ts)) provides the `prime-agent status` command. This outputs a concise human-readable table showing socket path, supervisor PID, active sessions, and heartbeat health.

For automation and monitoring systems, append the `--json` flag to receive structured data:

```bash
prime-agent status --json

```

This produces machine-readable output including:

```json
{
  "socketPath": "/tmp/prime-agent-12345.sock",
  "supervisorPid": 12345,
  "supervisorGeneration": "1",
  "activeSessions": 2,
  "heartbeat": { "lastSeen": "2026-08-14T13:42:10.123Z" }
}

```

### Rotating Log Files

PrimeAgent writes persistent logs to `daemon.log` within the agent directory using the `appendRotatingLog` function from [`daemon-supervisor.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor.ts). For real-time debugging or post-mortem analysis, tail this file:

```bash
tail -f $(prime-agent status --json | jq -r .socketPath | sed 's/.sock/.log/')

```

Alternatively, use the built-in diagnostic command:

```bash
prime-agent doctor --full

```

## Programmatic Monitoring via RPC

The RPC layer in [`packages/coding-agent/src/modes/rpc/rpc-client.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/modes/rpc/rpc-client.ts) exposes the same status data available in the TUI through programmatic interfaces. The key command is **`agent_messages_status`** (implemented around line 446), which returns the current activity state.

Monitor PrimeAgent programmatically using Node.js:

```typescript
import { RpcClient } from "prime-agent/rpc-client";

async function monitor() {
  const client = await RpcClient.connect("/tmp/prime-agent-12345.sock");
  
  // Subscribe to live status updates
  client.on("agent_messages_status", (payload) => {
    const { statusKey, statusText } = payload;
    console.log(`Status [${statusKey}]: ${statusText}`);
  });
  
  // Monitor connection state changes
  client.on("connection_status", (status) => {
    console.log(`Connection: ${status}`);
  });
}

monitor();

```

The RPC client also emits `session_status` events for tracking running/idle states and error conditions, enabling you to build custom dashboards or alerting systems.

## How the Monitoring Pipeline Works

Understanding the data flow helps troubleshoot gaps in observability:

1. **Supervisor startup**: `DaemonSupervisor.start()` initializes the Unix socket and writes the supervisor config file with generation, PID, and token identifiers.

2. **Worker admission**: Workers connecting to the supervisor socket validate the `supervisorAuthenticationClaim()` against the registry. Stale or missing sockets trigger election of a new supervisor.

3. **Activity tracking**: During active sessions, `InteractiveMode` routes events through `AgentActivityTracker.handleEvent()`, maintaining token counts and activity labels.

4. **Status propagation**: The tracker's `getStatus()` method feeds two pathways simultaneously—the TUI renders this in the `statusContainer` (showing strings like "↓ 123 tokens thinking"), while the RPC server maps identical data to `agent_messages_status` for external consumers.

## Summary

- **`prime-agent status --json`** provides immediate, machine-readable health snapshots including socket paths, PIDs, and session counts.
- **`AgentActivityTracker`** in [`agent-activity.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/agent-activity.ts) tracks real-time token usage and activity states, accessible via both TUI and RPC.
- **Supervisor health** is monitored through [`daemon-supervisor.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor.ts), which validates socket presence and manages ownership claims through [`daemon-supervisor-ownership.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor-ownership.ts).
- **Log files** at `daemon.log` provide persistent audit trails via `appendRotatingLog`, accessible through standard Unix tools or `prime-agent doctor --full`.
- **RPC integration** via [`rpc-client.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/rpc-client.ts) enables subscription to `agent_messages_status` events for building custom monitoring solutions.

## Frequently Asked Questions

### How do I check if the PrimeAgent daemon is running?

Run `prime-agent status` in your terminal. If the daemon is active, it displays the supervisor PID, socket path, and active session count. Use the `--json` flag for programmatic parsing. If the daemon is down, the command exits with an error indicating it cannot connect to the supervisor socket.

### Where does PrimeAgent store its activity logs?

Logs are written to `daemon.log` within the agent directory, managed by the `appendRotatingLog` function in [`daemon-supervisor.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor.ts). You can locate the exact path by checking the socket path from `prime-agent status --json` and replacing `.sock` with `.log`, or by running `prime-agent doctor --full` to see all log locations.

### Can I monitor PrimeAgent token usage programmatically?

Yes. Import the `AgentActivityTracker` class from [`agent-activity.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/agent-activity.ts) to track tokens directly in custom extensions, or connect via the RPC client to subscribe to `agent_messages_status` events. The RPC payload includes `statusKey` and `statusText` fields showing current activity and token flow direction (↑/↓).

### What does the `supervisor_generation_stale` error indicate?

This error originates in [`daemon-supervisor-ownership.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/daemon-supervisor-ownership.ts) when a worker detects that the supervisor's generation identifier does not match the registry entry. This typically occurs during supervisor failover or when multiple daemon processes attempt to claim the same lease. The system catches this error during the startup routine to prevent split-brain scenarios and trigger election of a new supervisor.