Daemon Protocol Message Shapes for Session Attachment in Prime Agent

Prime Agent's daemon protocol defines three core message shapes for session attachment: the attach command, DaemonAttachResult response, and session_attached event.

The daemon protocol message shapes for session attachment govern how clients reconnect to active coding sessions in Prime Agent's architecture. These JSON‑L messages carry session state, snapshot data, and replay metadata across the daemon‑client boundary. This guide breaks down each message shape with exact TypeScript definitions from packages/coding-agent/src/modes/daemon/daemon-protocol.ts.

Attach Command Shape

The attachment flow begins with the client sending a command to the daemon. In daemon-protocol.ts lines 73‑84, the DaemonCommand union includes the attach entry:

{
  id?: string;                 // optional envelope id
  type: "attach";
  activeSessionId: string;     // target session identifier
  supportsExtensionUi?: boolean;
} & DaemonAttachClientMetadata &
    DaemonClientEnv &
    DaemonLaunchEnv;

Required and Optional Fields

  • activeSessionId — The unique session identifier the client wants to join.
  • id — Optional envelope identifier; the SDK auto‑generates a UUID when omitted.
  • supportsExtensionUi — Requests UI extension support from the daemon.

The command extends three additional interfaces for complete attachment metadata:

Extended Interface Purpose Key Fields
DaemonAttachClientMetadata Client capabilities and telemetry policy capabilities, resumeCursor, telemetryDisabled, recoveryConfig
DaemonClientEnv Forwarded environment variables env (whitelisted vars for the session)
DaemonLaunchEnv Launch‑time environment for subprocesses launchEnv

Telemetry and Capability Negotiation

The telemetryDisabled flag carries special semantics: if set, a telemetry‑enabled worker must reject the attach request. This enforces strict opt‑out compliance at the protocol level.

The capabilities array lists client‑side features such as attach_snapshot and event_sequence, which determine what data the daemon includes in its response.

Attach Result Shape

The daemon responds with a DaemonAttachResult structure (defined in daemon-protocol.ts lines 26‑46):

export interface DaemonAttachResult {
  protocol: DaemonProtocolInfo;          // { name: "prime-agent.daemon", version: 7 }
  activeSessionId: string;               // echoed from command
  state?: SessionSummary;                // omitted with "slim_attach" capability
  messages?: AgentMessage[];             // omitted with "slim_attach" capability
  snapshot: DaemonSessionSnapshot;       // full session state
  replay: DaemonReplayInfo;              // replay status and cursors
  lastEventSequence: DaemonEventSequence;
  lastEventCursor?: DaemonEventCursor;
  snapshotStream?: { 
    id: string; 
    messageCount: number; 
    targetChunkBytes: number 
  };
  client: {
    id: DaemonClientId;
    capabilities: DaemonClientCapability[];
  };
}

Protocol Version Confirmation

The protocol field confirms interoperability at version 7 with name prime-agent.daemon. Clients must validate this before processing the remaining payload.

Snapshot and Replay Semantics

  • snapshot — Contains the complete session state including message history, context tree, and environment.
  • replay — Indicates whether the client must replay missed events: values are complete, partial, or unavailable.
  • state and messages — Conditionally omitted when the client negotiated the slim_attach capability, reducing payload size for lightweight clients.

The snapshotStream property appears when the snapshot exceeds inline size limits, providing a chunked download handle.

Session‑Attached Event Shape

After processing the attach command, the daemon emits a session_attached event on the outbound channel (lines 140‑148):

{
  type: "session_attached",
  activeSessionId: string,
  state: SessionSummary,
  messages: AgentMessage[],
  snapshot?: DaemonSessionSnapshot,
  replay?: DaemonReplayInfo,
  lastEventSequence?: DaemonEventSequence
}

This asynchronous event mirrors DaemonAttachResult fields but follows the daemon's event‑driven architecture. Clients receive it through their socket listener rather than as a direct RPC response.

The dual delivery mechanism—synchronous result plus asynchronous event—enables both request‑response patterns and stream‑based session management.

Practical Implementation Examples

Sending an Attach Command

import {
  createDaemonCommandEnvelope,
  DAEMON_PROTOCOL_INFO,
  DaemonAttachClientMetadata,
  DaemonClientEnv,
} from '.../daemon-protocol';

const attachCmd = {
  type: 'attach',
  activeSessionId: 'session-123',
  supportsExtensionUi: true,
} as const;

const meta: DaemonAttachClientMetadata = {
  telemetryDisabled: true,
  capabilities: ['attach_snapshot', 'event_sequence'],
};

const clientEnv: DaemonClientEnv = { 
  env: { HERDR_PANE_ID: '42' } 
};

const envelope = createDaemonCommandEnvelope(
  { ...attachCmd, ...meta, ...clientEnv },
  'cmd-001',
  undefined,
  DAEMON_PROTOCOL_INFO.version
);

socket.write(JSON.stringify(envelope) + '\n');

Handling the Session‑Attached Event

socket.on('data', (chunk) => {
  const lines = chunk.toString()
    .split('\n')
    .filter(Boolean);
    
  for (const line of lines) {
    const event = JSON.parse(line);
    if (event.type === 'session_attached') {
      console.log('Attached to', event.activeSessionId);
      // event.snapshot holds full session state
      initializeSession(event.snapshot, event.replay);
    }
  }
});

Protocol Files and References

File Path Relevant Definitions
packages/coding-agent/src/modes/daemon/daemon-protocol.ts DaemonCommand attach variant, DaemonAttachResult, session_attached event type
packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts Worker‑side attach handling, session‑plane routing
packages/coding-agent/src/modes/daemon/daemon-protocol.test.ts Compatibility tests for attach commands and session_attached shape validation

Lines 71‑84 of daemon-worker-protocol.ts define DaemonAttachClientMetadata and the core attach‑command processing logic according to the Prime Agent source code.

Summary

  • Three message shapes implement session attachment: the attach command, DaemonAttachResult response, and session_attached event.
  • Capability negotiation via capabilities array and telemetryDisabled flag controls payload contents and attachment eligibility.
  • Dual delivery pattern provides both synchronous result and asynchronous event for flexible client architectures.
  • Protocol version 7 requires explicit validation in DaemonAttachResult.protocol.
  • Slim attach mode reduces bandwidth by omitting state and messages when the client signals support.

Frequently Asked Questions

What is the minimum required field for an attach command?

The activeSessionId string is the only required field. All other properties—including id, supportsExtensionUi, and extended metadata—are optional. The daemon assigns default values for omitted envelope identifiers and capability sets.

How does the daemon handle telemetry opt-out?

When telemetryDisabled: true appears in DaemonAttachClientMetadata, telemetry‑enabled workers reject the attachment with an error response. This enforcement happens at the protocol layer before session state transmission begins.

What triggers the session_attached event versus the DaemonAttachResult response?

The daemon emits DaemonAttachResult immediately as the RPC response to the attach command. It then broadcasts session_attached on the outbound event channel, enabling both direct response handling and event‑stream consumption patterns in clients.

When should a client use the slim_attach capability?

Request slim_attach when the client maintains local session state or when bandwidth constraints make full message history undesirable. With this capability, the daemon omits state and messages from DaemonAttachResult, reducing payload size significantly.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →