Peer System

LAN peer-to-peer — discover other Clew instances, send messages, delegate tasks, and execute commands remotely.

The peer system lives in src/peer/ and consists of three core layers: PeerServer (HTTP server), PeerDiscovery (LAN scanning), and PeerStore (in-memory registry).

Architecture

 ┌─────────────────────────────────────────────────────────────────────────────┐
 │                          PEER SYSTEM FLOW                                   │
 └─────────────────────────────────────────────────────────────────────────────┘

                          ┌──────────────────────────┐
                          │      /peer share          │
                          │  (Machine A — Worker)     │
                          └────────────┬─────────────┘
                                       │
                     ┌─────────────────┼─────────────────┐
                     ▼                  ▼                  ▼
            ┌──────────────┐  ┌──────────────┐  ┌──────────────┐
            │ PeerServer   │  │PeerDiscovery │  │  PeerStore   │
            │ HTTP :random  │  │              │  │  (in-memory) │
            │  port         │  │              │  │              │
            └──────┬───────┘  └──────┬───────┘  └──────────────┘
                   │                 │
                   │    ┌────────────┼────────────┐
                   │    │            │            │
                   │    ▼            ▼            ▼
                   │ ┌────────┐ ┌────────┐ ┌─────────────┐
                   │ │  File  │ │  UDP   │ │  PeerStore   │
                   │ │ ~/.cl/ │ │multicast│ │ (singleton) │
                   │ │ peers/ │ │239...  │ │             │
                   │ │{pid}.  │ │:42069  │ │             │
                   │ │ json   │ │        │ │             │
                   │ └────┬───┘ └────┬───┘ └─────────────┘
                   │      │          │
                   │      │          │  heartbeat every 30s
                   │      │          │  stale timeout 90s
                   │      │          │
                   ▼      ▼          ▼
 ┌─────────────────────────────────────────────────────┐
 │                   LAN NETWORK                        │
 │                                                     │
 │   ┌─────────┐         ┌─────────┐                   │
 │   │ Machine B│◄───────►│ Machine C│  ...             │
 │   │ Clew Code│  query  │ Clew Code│                   │
 │   └────┬─────┘         └────┬─────┘                   │
 │        │                    │                         │
 └────────┼────────────────────┼─────────────────────────┘
          │                    │
          │  /peer discover    │  /peer discover
          ▼                    ▼


 ═══ WORKER (Machine A) ENDPOINTS ═══

      Peer อื่น          POST /peer-info     ──►  { hostname, ip, cwd, shell, ... }
         │                POST /peer-msg      ──►  receive chat message
         ├───────────────► POST /peer-todo     ──►  receive task (goes to inbox)
         │                POST /peer-exec     ──►  run shell command + return stdout/stderr


 ═══ CLIENT (Machine B) TOOLS ═══

      /peer discover  ──►  scan files + UDP query (3s timeout)
                               │
                               ▼
                          [peer list]
                               │
           ┌───────────────────┼───────────────────┐
           ▼                   ▼                   ▼
    /peer join          /peer send_task      /peer run
    (POST /peer-info)   (POST /peer-todo)    (POST /peer-exec)

           │
           ▼
    /peer send_message   ──►  POST /peer-msg  ──►  destination inbox
    /peer broadcast      ──►  POST /peer-msg  ──►  all connected peers
    /peer ping           ──►  GET  /peer-info  ──►  check alive


 ═══ DAEMON (agentLoop.ts) ═══

      ┌───────────────────────────────────┐
      │  Autonomous Agent Loop            │
      │  - listens /peer-todo 24/7       │
      │  - receives tasks from peers      │
      │  - executes in background worker   │
      │  - max 3 concurrent workers       │
      └───────────────────────────────────┘


 ═══ DATA LIFECYCLE ═══

      advertise ──► heartbeat every 30s
                        │
                        ├── 90s no heartbeat ──► stale → evict
                        │
      stop share ──► send UDP "offline"
                     delete peer file
                     close HTTP server

Core Components

PeerServer src/peer/PeerServer.ts

Lightweight HTTP server started on a random OS-assigned port when /peer share is invoked. Each endpoint handles a different peer interaction:

EndpointMethodPurpose
/peer-infoGETReturn peer metadata (hostname, IP, cwd, shell, platform)
/peer-msgPOSTReceive a chat message from another peer
/peer-todoPOSTReceive a task delegation from another peer
/peer-execPOSTExecute a shell command and return stdout/stderr

PeerDiscovery src/peer/PeerDiscovery.ts

Two discovery mechanisms work together:

  • File-based — Each instance writes ~/.claude/peers/{pid}.json with hostname, IP, port, shell, cwd. Other instances scan this directory to discover local peers.
  • UDP Multicast — Broadcasts heartbeat beacons to 239.255.37.37:42069 every 30 seconds. Responds to clew-peer-query with clew-peer-info. Cross-machine only.
  • Stale eviction — Peers unseen for 90 seconds (PEER_STALE_TIMEOUT) are automatically removed.

PeerStore src/peer/PeerStore.ts

Singleton in-memory registry holding all known peers (discovered + explicitly joined), chat messages, todos, and custom tags (display names, roles).

  • Discovered peers — Auto-evicted after stale timeout
  • Joined connections — Persistent; never auto-cleaned
  • Tags — Custom display names and roles per peer

Discovery Protocol

DiscoveryMessage =
  | { type: "clew-peer-query",  version: 1 }                    // broadcast scan
  | { type: "clew-peer-info",   version: 1,                     // heartbeat / response
      id: string, hostname: string, ip: string, port: number,
      cwd: string, sessionId?: string, appVersion: string,
      shell?: string, platform?: string, term?: string,
      status: "online" | "offline" }

UDP port:     42069
Multicast IP: 239.255.37.37
Heartbeat:    every 30 seconds
Stale after:  90 seconds

Commands

CommandDescription
/peerOpen interactive peer menu (share, join, discover, inbox)
/peer shareStart advertising this instance as a worker on the LAN
/peer stopStop advertising and shut down the peer server
/peer discoverScan for available peers (file + UDP, 3s timeout)
/peer join <host> <port>Connect to a remote peer by host and port
/peer name <name>Set a custom display name for yourself
/peer role <role>Set a role label (builder, tester, deployer, etc.)
/peer inboxView pending messages and todos from peers
/peer disconnect <peer>Disconnect from a specific peer
/peer todosList all received tasks
/peer todo done <id>Mark a received task as done

AI Tools

These are the tools the AI agent uses to interact with the peer system:

ToolDescription
peer_discoverScan LAN for available Clew workers
peer_joinConnect to a remote peer via HTTP
peer_pingCheck if a peer is online (GET /peer-info)
peer_infoFetch detailed peer information
peer_send_messageSend a chat message to a peer
peer_send_taskAssign a task to a remote worker
peer_broadcastSend a task to all connected peers simultaneously
peer_runExecute a shell command on a remote worker
peer_disconnectRemove a peer from the connection list
peer_list_messagesList all received chat messages
peer_list_rolesList all peers with their roles
peer_list_tasksList all task assignments and their status
peer_set_nameAssign a custom display name to a peer
peer_set_roleAssign a functional role to a peer
peer_shareToggle sharing (start/stop/status)

DAEMON Integration

The autonomous agent loop (src/services/autonomous/agentLoop.ts) integrates with PeerServer to accept tasks from remote peers:

  • Listens for incoming /peer-todo POSTs 24/7
  • Queues received tasks and processes them in background workers
  • Max 3 concurrent workers; tasks time out after 30 minutes
  • Results are available via /peer todos and /tasks

Architecture Files

FileRole
src/peer/PeerServer.tsHTTP server with /peer-info, /peer-msg, /peer-todo, /peer-exec endpoints
src/peer/PeerDiscovery.tsFile-based + UDP multicast LAN peer discovery
src/peer/PeerStore.tsIn-memory singleton registry (peers, messages, todos, tags)
src/peer/types.tsShared types and protocol constants
src/commands/peer/Interactive peer menu and CLI commands
src/tools/Peer*Tool/16 AI agent tools wrapping peer operations
src/services/autonomous/agentLoop.tsDaemon integration: accepts remote tasks via PeerServer