pi-messenger

repository·main·Indexed 19 days ago

https://github.com/nicobailon/pi-messenger

An extension for the Pi coding agent that enables inter-agent messaging, file reservation, and coordination via a shared folder. It provides a system for task orchestration through Crew (transforming PRDs into dependency graphs), a Team layer for project-local roles and approvals, and a Chat Overlay for real-time agent communication without requiring a central server or daemon.

Tokens
12.9K
Snippets
32
Records
44
Agent score
71%

What's inside pi-messenger

  1. Configure Worker Coordination Levels

    main

    The coordination setting determines how much workers communicate with each other during execution. This affects the messageBudgets applied to workers.

    • none: No coordination instructions. Workers just execute their task.
    • minimal: Check reservations before editing files. Message if conflicts.
    • moderate: Announce start/completion via broadcast. Check reservations. Ask about unclear dependencies. Workers also receive recent activity context and concurrent task info.
    • chatty (default): All of moderate, plus: DM peers whose tasks overlap, share progress on interface changes, respond to incoming messages, and claim next task after completion. Workers also receive recent activity context and concurrent task info.
  2. Use the Team layer for project-local roles and approvals

    main

    The Team layer is an optional wrapper around Crew that adds project-local roles, a charter, durable memory, and high-risk approval gates. Active Team state is stored in .pi/messenger/team/.

    Key Capabilities

    • Roles: Assign specific responsibilities (e.g., scout, worker, reviewer) to agents. Built-in roles include context-builder, delegate, oracle, planner, researcher, reviewer, scout, and worker.
    • Approvals: Define high-risk tasks (e.g., tagged with database or migration) that require manual approval before workers proceed.
    • Memory: Store project-specific decisions and context.

    API Commands

    • team.setup: Activates a profile (e.g., migration-squad) and creates a charter.
    • team.memory.note: Adds a durable note to the team memory.
    • team.roles: Lists active roles.
    • team.status: Shows current team status.
    // Setup a migration squad with approval gates
    pi_messenger({ action: "team.setup", name: "migration-squad" });
    
    // Add a decision to team memory
    pi_messenger({ action: "team.memory.note", type: "decision", message: "Auth API changes require reviewer sign-off." });
    
    // Check team status
    pi_messenger({ action: "team.status" });
  3. How Crew task orchestration works

    main

    Crew transforms a Product Requirements Document (PRD) into a dependency graph of tasks and executes them in parallel waves.

    Workflow

    1. Plan: The Planner explores the codebase and PRD to draft tasks with dependencies. It refines the plan until it reaches a SHIP state or the maxPasses limit. Progress is logged to .pi/messenger/crew/planning-progress.md within your project directory.
    2. Work: Workers implement tasks whose dependencies are met. A single work call executes one wave. Using autonomous: true runs waves sequentially until completion or blockage. Tasks are automatically reviewed after completion; results include SHIP (done), NEEDS_WORK (retry with feedback), or MAJOR_RETHINK (blocks task).
    3. Review: You can manually review a specific task or the entire plan using the review action.

    Wave Execution

    Tasks are organized into waves based on their dependencies. Independent tasks run concurrently in the same wave. Once a task in Wave $N$ is completed, it unblocks dependent tasks in Wave $N+1$.

    // Plan and auto-start autonomous work when planning completes
    pi_messenger({ action: "plan" });
    
    // Plan with a specific prompt
    pi_messenger({ action: "plan", prompt: "Scan the codebase for bugs" });
    
    // Manual review of a specific task
    pi_messenger({ action: "review", target: "task-1" });
  4. Understand how pi-messenger works internally

    main

    Pi-messenger is a pi extension that hooks into the agent lifecycle using specific event listeners:

    • pi.on("tool_call") and pi.on("tool_result"): Used to track activity like edits, commits, and test runs.
    • pi.on("session_start"): Handles auto-registration.
    • pi.on("session_shutdown"): Handles cleanup.
    • pi.on("agent_end"): Drives autonomous crew mode by checking for ready tasks.

    Key Mechanisms:

    • Messaging: Incoming messages use pi.sendMessage() with triggerTurn: true and deliverAs: "steer" to inject messages as steering prompts.
    • File Reservations: Enforced by returning { block: true } from a tool_call hook during write/edit operations.
    • Crew Workers: Spawned as pi --mode json subprocesses. Progress is tracked via JSONL streaming.
    • Coordination: File-based (no daemon required). Shared state lives in ~/.pi/agent/messenger/. Project-scoped activity and crew logs live in <project>/.pi/messenger/.
  5. Handle Graceful Shutdown of Crew Workers

    main

    When a work run is cancelled (e.g., via Ctrl+C), the system attempts a graceful shutdown sequence:

    1. An inbox message is sent to the worker requesting it to stop, release reservations, and exit.
    2. The system waits for the duration specified in work.shutdownGracePeriodMs (default 30s) for a clean exit.
    3. If the worker is still running, a SIGTERM is sent, followed by a 5s wait.
    4. If still running, a SIGKILL is issued.

    Task State on Shutdown:

    • Graceful exit: Tasks from these workers are reset to todo for retry in the next wave.
    • Crashed/Non-graceful exit: These workers block the task in autonomous mode to prevent infinite retry loops.
  6. Install pi-messenger

    main

    Install the pi-messenger extension for the Pi coding agent using the pi install command. This extension enables multi-agent coordination via shared files without requiring a central daemon or server.

    pi install npm:pi-messenger
  7. Configure the Pi-Messenger Crew

    main

    The Crew skill can be configured at two levels:

    1. User-level: Edit ~/.pi/agent/pi-messenger.json under the crew key. This applies to all projects.
    2. Project-level: Edit .pi/messenger/crew/config.json within your project directory. Project-level settings override user-level settings, which in turn override defaults.

    When configuring models, use the provider/model format (e.g., anthropic/claude-haiku-4-5) for explicit provider selection. You can also use a :level suffix for inline thinking control (e.g., openrouter/anthropic/claude-sonnet-4:high). Note that the :level suffix takes precedence over the thinking.<role> configuration.

    // User-level config (~/.pi/agent/pi-messenger.json)
    {
      "crew": {
        "models": {
          "worker": "anthropic/claude-haiku-4-5",
          "planner": "openrouter/anthropic/claude-sonnet-4:high"
        }
      }
    }
  8. Use the Chat Overlay

    main

    Run /messenger to open an interactive overlay. This interface provides agent presence, an activity feed, and chat capabilities.

    Chat Commands

    • Direct Messages: Use @Name msg (e.g., @SwiftRaven hello).
    • Broadcasts: Use @all msg to send a message to everyone.
    • Default Behavior: Text entered without an @ prefix broadcasts from the Agents tab or DMs the currently selected agent tab.

    Keyboard Shortcuts

    KeyAction
    Tab / Switch tabs (Agents, Crew, agent DMs, All)
    Scroll history / navigate crew tasks
    EnterSend message
    EscClose
  9. Manage Crew skills for domain knowledge

    main

    Crew workers can acquire domain-specific knowledge via Skills. Skills are discovered from three hierarchical locations (later sources override earlier ones):

    1. User skills: ~/.pi/agent/skills/ (using dir/SKILL.md format).
    2. Extension skills: crew/skills/ within the extension.
    3. Project skills: .pi/messenger/crew/skills/ in your project root.

    The planner indexes these skills and tags tasks with relevant ones. Workers load the full content of a skill only when needed via read(), optimizing token usage.

    To add a project-level skill, create a .md file in .pi/messenger/crew/skills/ with a YAML frontmatter header containing name and description.

    ---
    name: our-api-patterns
    description: REST API conventions for this project — auth, pagination, error shapes.
    ---
    
    # API Patterns
    
    Always use Bearer token auth. Paginate with cursor-based `?after=` params.
    Error responses use `{ error: { code, message, details? } }` shape.
  10. Configure Crew models and execution settings

    main

    Crew can consume significant tokens because it runs multiple LLM sessions in parallel. You can configure models and execution constraints in ~/.pi/agent/pi-messenger.json.

    Model Configuration

    By default, agents inherit the host session model. You can override models per role using the crew.models.<role> key. Model strings support the provider/model format and a :level suffix for inline thinking control (e.g., anthropic/claude-sonnet-4:high).

    Configuration Reference

    All fields are optional. Settings are applied in the following hierarchy: crew.models.<role> > agent frontmatter > host session model.

    SettingDescriptionDefault
    concurrency.workersDefault parallel workers per wave2
    concurrency.maxMaximum workers allowed (hard ceiling is 10)10
    dependenciesDependency scheduling mode: advisory or strict"advisory"
    coordinationWorker coordination level: none, minimal, moderate, chatty"chatty"
    models.plannerModel for planner agenthost session model
    models.workerModel for workershost session model
    models.reviewerModel for reviewer agenthost session model
    review.enabledAuto-review after task completiontrue
    review.maxIterationsMax review/fix cycles per task3
    planning.maxPassesMax planner/reviewer refinement passes1
    work.maxAttemptsPerTaskAuto-block after N failures5
    work.maxWavesMax autonomous waves50

    Default Agent Roles and Fallbacks

    AgentRoleDefault Model
    crew-plannerplanneranthropic/claude-opus-4-6
    crew-workerworkeranthropic/claude-haiku-4-5
    crew-reviewerrevieweranthropic/claude-opus-4-6
    crew-plan-syncanalystanthropic/claude-haiku-4-5
    {
      "crew": {
        "concurrency": { "workers": 2, "max": 10 },
        "models": {
          "worker": "anthropic/claude-haiku-4-5",
          "planner": "openrouter/anthropic/claude-sonnet-4:high"
        },
        "review": { "enabled": true, "maxIterations": 3 },
        "planning": { "maxPasses": 1 },
        "work": {
          "maxAttemptsPerTask": 5,
          "maxWaves": 50
        }
      }
    }
  11. How Pi Messenger coordination works

    main

    Pi Messenger enables agents to communicate across terminal sessions using file-based coordination (no daemon required).

    Core Workflow:

    1. Registration: An agent joins the mesh by creating registration files in a shared directory (default: ~/.pi/agent/messenger).
    2. Discovery: Agents use a watcher to monitor the registry for other active agents.
    3. Messaging: Messages are delivered via agent_message types. The extension handles unread counts, chat history, and identity tracking (detecting if a sender is a new session).
    4. Status Tracking: The extension automatically updates the terminal status bar with peer counts, unread messages, planning progress, and active 'Crew' work (e.g., ⚡2/5 🔨1).
    5. Activity Monitoring: The extension tracks agent activity (editing files, running tests, committing code) to provide a real-time status and detect if an agent has become 'stuck'.