Skip to content

Chapter 21 · Multi-Session Collaboration: pi-intercom and pi-messenger ​

Chapter goals: Master two multi-session collaboration extensions in the pi ecosystem — pi-intercom (peer-to-peer定向 messages) and pi-messenger (multi-agent chatroom); understand各自的适用场景与选型依据; and搭建 a three-terminal collaboration workflow.

21.1 Multi-Session Collaboration Overview ​

When you run multiple pi sessions simultaneously — one researching, one coding, one reviewing — how do they共享 findings and协调行动? pi's answer is not内置 sub-agents; instead it provides two互补协作 modes through the扩展 ecosystem:

Dimensionpi-intercompi-messenger
通信模型Peer-to-peer 1:1 directed messagesShared chatroom (broadcast)
主要用途User orchestrates their own multiple sessionsMulti-agent autonomous协同
发现机制Broker process (real-time registration)File-basedregistry
消息可见性Private; only sender and receiverBroadcast to所有 online agents
持久化Stored in Pi session historyShared coordination file
基础设施Local IPC socket/pipesPure filesystem; no daemon

The two are not互斥: you can use pi-messenger to let a group of workers自主分工跑 Crew tasks,同时用 pi-intercom to传递精确指令 between two specific sessions.

Installation

Both packages install via the pi包管理器:

bash
pi install npm:pi-intercom
pi install npm:pi-messenger

Restart Pi after安装 to生效.

21.2 pi-intercom: Peer-to-Peer Messages ​

Architecture Principles ​

Each Pi session加载 pi-intercom connects to a lightweight本地 broker process. The broker维护在线会话注册表; routing messages to the target you指定 (by name or session ID).通信使用 Unix domain socket (macOS/Linux) or named pipes (Windows), length-prefixed JSON protocol.

The broker auto-starts on first连接 (spawned when the first client connects); exits 5 seconds after the last connection断开. No manual daemon management needed. Heartbeat机制 detects half-open connections; clients auto-reconnect after broker异常重启.

Installation and Configuration ​

bash
# Install the extension
pi install npm:pi-intercom

# Auto-connects to the broker and registers the pi-intercom skill after restarting Pi

# Optional: add collaboration guidance in the project AGENTS.md

Recommended adding the以下 snippet to the project's AGENTS.md to help agents understand when to跨会话协调:

xml
<pi-intercom>
Coordinate with other local pi sessions on related codebases.
Use `/skill:pi-intercom` for patterns.

**When:** Same codebase (parallel work), reference codebase (consulting patterns).
**Not when:** Unrelated codebases, trivial questions, or when you can proceed independently.

**Principle:** Prefer `send` for notifications; `ask` only when blocked waiting for input.
</pi-intercom>

Advanced config at ~/.pi/agent/intercom/config.json:

json
{
  "confirmSend": false,
  "inboundTrigger": "always",
  "enabled": true,
  "replyHint": true,
  "status": "researching"
}

Core Tool Usage ​

The intercom tool supports八种 actions covering complete peer-to-peer communication scenarios:

typescript
// List all online sessions (with [self]标记)
intercom({ action: "list" })
// → • executor (20d43841) — ~/projects/api [self, idle]
// → • research (6332faab) — ~/projects/api [same cwd, thinking]

// Only list peers in the same cwd
intercom({ action: "list-cwd" })

// Send-and-forget消息——通知类场景用 send
intercom({
    action: "send",
    to: "research",
    message: "Check if UserService.validate() handles null input."
})

// Blocking ask——需要回复才能继续的场景用 ask
intercom({
    action: "ask",
    to: "planner",
    message: "Should retry apply to all endpoints or just idempotent ones?"
})
// → Reply from planner: Only GET/PUT/DELETE — never POST. Max 3 retries.

// Reply to the最近 inbound ask
intercom({ action: "reply", message: "Task-3 done. All tests passing." })

// View pending inbound asks
intercom({ action: "pending" })

// Cancel a sent message
intercom({ action: "cancel", messageId: "abc123" })

Key difference between send and ask:

  • send is fire-and-forget; the tool立即返回. If the target恰好 has a pending ask, send auto-infers it is its reply and关联 replyTo;
  • ask requires the target to be online; after sending blocks等待回复 (default 10-minute timeout, adjustable via PI_INTERCOM_ASK_TIMEOUT_MS); the回复 returns as a tool result; the agent无需中断当前 turn即可继续.

User-side快捷键: press Alt+M or type /intercom to open a session选择浮层; arrow keys选目标, Enter发送, Esc关闭.

Planner-Worker Orchestration Mode ​

The most自然用法 is to split tasks across two terminals:

bash
# Terminal 1                          # Terminal 2
/name planner                         /name worker

The Planner uses send to下发 tasks (no need to wait forack); the Worker uses ask to提问 the Planner when遇到歧义 and waits for the reply before continuing — no context lost全程.

Communication patternActionReason
Task delegationplanner uses sendFire-and-forget; planner does not等待 ack
Ambiguity clarificationworker uses askNeeds the answer to继续
Discovery escalationworker uses askNeeds审批 before changing plan
Completion reportworker uses askPlanner may have后续指示

Integration with pi-subagents: contact_supervisor Tool ​

When the pi-subagents extension is also installed, sub-agents spawned by it额外获得 a contact_supervisor tool (not visible in普通会话). The tool supports三种 reasons:

typescript
// Blocking decision请求——子代理遇到歧义或需要审批
contact_supervisor({
    reason: "need_decision",
    message: "Auth service returns 403 instead of 401 for expired tokens. Treat as re-auth trigger or hard failure?"
})

// Structured interview——一次获取多个机器可读的答案
contact_supervisor({
    reason: "interview_request",
    message: "Please answer these before I continue the migration.",
    interview: {
        title: "API migration choices",
        questions: [
            { id: "api", type: "single", question: "Which API?", options: ["Stable", "Experimental"] }
        ]
    }
})

// Non-blocking进度更新——有意义的进展或改变计划的发现
contact_supervisor({
    reason: "progress_update",
    message: "Discovered the bug is in the retry wrapper, not the API client."
})

Do not use contact_supervisor for日常完工交接 —正常返回结果即可; only use it when the答案 affects the任务契约 or needs owner审批.

21.3 pi-messenger: Multi-Agent Chatroom ​

Architecture and Philosophy ​

pi-messenger's核心理念 is "multiple agents in不同 terminals sharing the same folder对话像聊天室一样". It coordinates entirely via filesystem — no daemon, no server,纯文件读写.

After joining, agents获得 a主题化随机名称 (e.g. SwiftRaven, LunarDust); the status bar shows online count: msg: SwiftRaven (2 peers) ●3.

Installation and Quick Start ​

bash
# Install
pi install npm:pi-messenger

# View/install preset Crew agents
npx pi-messenger --crew-install

# Remove the extension
npx pi-messenger --remove

After joining, six基础协调 actions are available:

typescript
// Join the mesh
pi_messenger({ action: "join" })

// Reserve paths to prevent其他 agent写入冲突
pi_messenger({ action: "reserve", paths: ["src/auth/"], reason: "Refactoring auth module" })

// Directed私聊
pi_messenger({ action: "send", to: "GoldFalcon", message: "auth is done" })

// Broadcast to everyone
pi_messenger({ action: "broadcast", message: "API contract updated, please review." })

// Release locks
pi_messenger({ action: "release" })

// Leave the mesh
pi_messenger({ action: "leave" })

The file locking机制实现 via intercepting tool_call hooks: other agents attempting to write to reserved paths receive a block message telling them to协调 with which agent. Locks auto-release on leave or process exit.

Crew: From PRD to Parallel Execution ​

Crew is pi-messenger's最 powerful功能 — transforming a PRD doc into a dependency-graph任务图, then executing in waves:

typescript
// Planning phase——analyze the codebase;生成依赖图任务
pi_messenger({ action: "plan" })

// Execution phase——execute one wave of ready tasks in a single call
pi_messenger({ action: "work" })

// Autonomous mode——连续执行 until all tasks complete or block
pi_messenger({ action: "work", autonomous: true })

// Review a specified task's implementation
pi_messenger({ action: "review", target: "task-1" })

Wave execution dependency scheduling logic:

text
Wave 1:  task-1 (no deps)  ─┐
         task-3 (no deps)  ─┤── execute in parallel
Wave 2:  task-2 (→task-1) ─┤── task-1 done, task-2解锁
         task-4 (→task-3) ─┘── task-3 done, task-4解锁
Wave 3:  task-5 (→task-2,4)── all deps done

Each completed task自动触发 reviewer审查 — SHIP保持完成态, NEEDS_WORK重置并附带反馈重试, MAJOR_RETHINK阻塞.

Crew Agents and Skills ​

Crew agents are defined as .md files (含 frontmatter specifying model and thinking level)存放 in the extension's crew/agents/ directory. To customize for a single project,复制 to .pi/messenger/crew/agents/ and edit.

Four default roles and model分配:

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 skills are领域知识的按需加载单元, placed in .pi/messenger/crew/skills/:

markdown
---
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.

The Planner sees the skill index and can标注 it to相关 tasks; Workers读取 on-demand; zero token waste.

Configuration and Cost Control ​

Crew launches多个 LLM sessions in parallel — token消耗可能很大.建议先用廉价模型验证流程再升级. Config file ~/.pi/agent/pi-messenger.json:

json
{
  "autoRegister": true,
  "nameTheme": "nature",
  "stuckThreshold": 900,
  "crew": {
    "concurrency": { "workers": 2 },
    "models": { "worker": "claude-haiku-4-5" },
    "review": { "enabled": true, "maxIterations": 3 },
    "work": { "maxAttemptsPerTask": 5, "maxWaves": 50 }
  }
}

Model strings支持 provider/model format and the :level suffix to控制 thinking depth (e.g. openrouter/anthropic/claude-sonnet-4:high).

Team Layer: Optional Team-Scale Layer ​

Team is an可选层 above Crew, adding project-level roles,章程, persistent记忆, and high-risk审批门控. Most users可直接用自然语言交互:

text
Use the review squad for this cleanup.
Use a migration team and pause before risky database changes.
Approve the auth API task.

Three built-in示例 profiles可立即激活:

typescript
pi_messenger({ action: "team.setup", name: "migration-squad" }) // with审批门控
pi_messenger({ action: "team.setup", name: "review-squad" })    // review流
pi_messenger({ action: "team.setup", name: "research-squad" })  // research-priority流

21.4 Selection Comparison ​

ScenarioRecommended ToolReason
You manually drive两个 sessions (research → execution)pi-intercomPoint-to-point精确控制; send/ask分离
A group of autonomous agents分工做大任务pi-messenger (Crew)Wave parallel + auto review + dependency scheduling
Sub-agents need to请示决策 to the parentpi-intercom + pi-subagentscontact_supervisor三种 reason
Team-level roles/approval/memorypi-messenger (Team)Built-in migration/review/research squads
Quick传递一段代码片段pi-intercom send + attachmentsSupports file/snippet/context types
Long-running multi-project agent群pi-messengerFile persistence; recoverable after重启

One-sentence principle: for precise control over who gets the message use intercom; for群体自主协同 use messenger.

21.5 Walkthrough: Three-Terminal Collaboration Building a Feature ​

假设你要为 Web 应用添加暗色主题. Use three terminals分别承担规划、前端实现和测试审查角色:

Terminal 1 — Planner:

bash
/name planner
pi install npm:pi-intercom
pi install npm:pi-messenger

Start Crew planning via pi-messenger:

typescript
pi_messenger({ action: "plan", prompt: `
Add dark mode to this app:
1. CSS variables for theme colors (--bg-color, --text-color)
2. System preference detection (prefers-color-scheme)
3. Manual toggle button with localStorage persistence
4. Update all existing components to use variables
` })
// Auto-starts workers to execute

Terminal 2 — Frontend Worker:

bash
/name frontend-worker
pi install npm:pi-messenger

The Worker自动接收 tasks via Crew, or manually认领:

typescript
pi_messenger({ action: "join" })
pi_messenger({ action: "reserve", paths: ["src/styles/", "src/theme.ts"] })
pi_messenger({ action: "work" })  // execute assigned tasks

When遇到设计歧义 use intercom to提问 the planner:

typescript
intercom({
    action: "ask",
    to: "planner",
    message: "Should dark mode default to system preference or manual toggle on first visit?"
})

Terminal 3 — Reviewer:

bash
/name reviewer
pi install npm:pi-intercom
pi install npm:pi-messenger

Listen for完工报告 and review:

typescript
pi_messenger({ action: "join" })
pi_messenger({ action: "status" })   // view crew progress

// Or use intercom to直接询问 the worker
intercom({
    action: "ask",
    to: "frontend-worker",
    message: "Are all CSS variables defined in a single theme.ts? Show me the variable names."
})

Three terminals各司其职; seamlessly衔接 via两种协作通道 — this is pi's extension ecosystem "组合优于内置"设计哲学.

Chapter Summary ​

  • pi-intercom provides本地 point-to-point messages: send (fire-and-forget) / ask (blocking wait for reply) / reply / cancel;
  • pi-subagents子代理额外获得 contact_supervisor;三种 reason对应 decision/interview/progress;
  • pi-messenger is a file-based chatroom: join/reserve/send/broadcast; file locking防冲突;
  • Crew transforms a PRD into a dependency-graph任务; wave parallel execution + auto review loop;
  • Team layer adds roles,章程, memory, and approval门控;
  • Selection principle: precise control → intercom;群体自主 → messenger.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What is the核心区别 between send and ask in pi-intercom?

2. What problem does pi-messenger's reserve action primarily solve?

3. How does Crew's wave execution调度 tasks?

4. In which scenario should you choose pi-intercom over pi-messenger?

🛠️ Hands-on Practice ​

  1. Install pi-intercom; open two terminals分别命名为 planner and worker; use intercom({ action: "list" }) to确认互相可见; then完成一轮任务委派 via send/ask.
  2. Install pi-messenger and join the mesh; create a PRD file with 3 tasks; run the完整 Crew flow via plan + work autonomous:true.
  3. Create .pi/messenger/crew/skills/deploy-checklist.md in the project containing your deployment checklist;观察 whether the planner标注s it to relevant tasks.

Back to Course Guide