Multi-Agent Systems

AI Crew Mode

MeshPilot's AI Crew mode leverages an event-driven orchestrator to run parallel, role-based LLM agents across codebase engineering tasks, maximizing execution speed while minimizing token costs.

What is AI Crew?

AI Crew is an advanced engineering workflow in MeshPilot that automates complex software development tasks by dividing work among a roster of specialized LLM agents. Instead of running a single long-lived agent that attempts to perform research, implementation, testing, and reviews sequentially, AI Crew leverages a role-based execution pattern.

Why Does It Exist?

Traditional multi-agent frameworks often suffer from "token sinks" - processes where agents spend massive amounts of inference context polling tasks, spamming other agents' terminals via mailbox protocols, or executing corrective re-prompts.

MeshPilot replaces this older paradigm with a Coordinator-as-Code approach (defined in the orchestrator file swarmEngine.ts). By keeping the coordinator's scheduling logic in deterministic TypeScript code rather than running an LLM loop, MeshPilot runs **zero LLM tokens** for orchestration. The engine holds a strict Phase Directed Acyclic Graph (DAG) and dispatches exactly one targeted prompt per agent per task, utilizing structured signals for state detection.

How Does It Work?

The Crew lifecycle runs through a series of stages. Below is the conceptual workflow of the Crew orchestrator, from the launch wizard initialization to final completion:

   [ Launch Crew Wizard ]
             |
             v
   [ Init MeshMemory Pack ] ---> [ Seed Tasks in MeshMCP ]
             |
             v
   [ Scout Stage (Audits Stack) ] ---> Outputs scout.md & design-system.md
             |
             v
   [ Foundation Build Stage ] ---> Builder 1 scaffolds base structures
             |
             v
   [ Content Build Stage ] ---> Parallel Builders code separate files
       ^     |
       |     v
       |   [ Review Gate Check ]
       |     |           |
       |   Reject     Approve
       |     |           |
       +-----+           v
                   [ Complete ] ---> Reconcile board & shut down

Orchestrator Sequence Diagram (Mermaid)

mermaidcopy
graph TD
    A[Launch Wizard Setup] --> B[Initialize Memory & Seed Tasks]
    B --> C{Phase: Scout}
    C -- Scout Agent Runs --> D["Scout writes design-system.md"]
    D -- Emits SCOUT_COMPLETE --> E{Phase: Foundation}
    E -- Builder 1 Runs --> F[Builder 1 establishes core scaffold]
    F -- Emits BUILDER_COMPLETE --> G{Phase: Build}
    G -- Parallel Builders Run --> H[Builders edit distinct code slices]
    H -- Emits BUILDER_COMPLETE & task_id --> I{Phase: Review}
    I -- Reviewer Runs Tests & Checks Diffs --> J{Review Verdict}
    J -- Rejects --> K[Bounce Builder with Feedback]
    K --> G
    J -- Approves --> L[Mark Task Complete in MeshMCP]
    L -- Emits REVIEWER_COMPLETE --> M{Phase: Complete}
    M --> N[Reconcile Board & Shutdown]

The Four Roles

AI Crew structures execution using four distinct agent roles. Roles are visual-themed inside the console and configured in swarmConstants.ts:

1. Coordinator (Zero-Token Engine)

Unlike other roles, the Coordinator is not an LLM agent. Its logic is fully defined as code in the Local Crew Engine. It is responsible for parsing phase advancement rules, normalizing rosters (using normalizeRosterAgents), writing role-specific prompts to disk, and managing shared files.

2. Scout

The Scout executes during the first phase of the Crew. It scans the target directory, audits dependencies, analyzes database schemas, and outlines conventions. It publishes its findings to MESH_CHART/scout.md and writes the visual design rules to MESH_CHART/design-system.md.

3. Builder

Builders write code, refactor components, and fix issues. The orchestrator separates them into:

  • Foundation Builder (Builder 1): Dispatched first to establish base layouts, configuration setups, and boilerplates.
  • Parallel Builders (Builder 2+): Dispatched simultaneously once the foundation is set. They are assigned non-overlapping file scopes to prevent merge conflicts.

4. Reviewer

The Reviewer executes code reviews and checks overall quality. It examines diffs, validates that implementation aligns with the original mission, and runs test scripts. It possesses the authority to approve a task (marking it complete) or reject it (bouncing the work back to the assigned builder with feedback).

Orchestrator Sequencing & The Launch Wizard

The lifecycle of a Crew launch is managed step-by-step through the user interface in SwarmView.tsx.

1. Setup and Roster Calibration

The user configures the bench path and selects the default CLI model. The wizard allows scaling between 1 and 10 workers (configured via MIN_WORKERS and MAX_WORKERS in constants). The system runs a pre-flight model validation check:

typescriptcopy
// Pre-flight check: verify agent CLI setup before launching the crew
const modelError = validateAgentModels(agents);
if (modelError) {
  showToast(modelError);
  return;
}

2. Mission & Skills Setting

The user sets the Crew's goal, along with optional skills. Available skills include:

  • Incremental Build: Forces agents to commit and save working code at every intermediate step.
  • Code Review: Requires Reviewer validation before tasks are marked complete.
  • Parallel Files: Restricts Builders to isolated directories and files.
  • Auto Tests: Directs agents to generate and execute unit/integration tests alongside source changes.

3. Context & Stitch Import

Users can attach static design guidelines or import exported **Stitch Design bundles**. The Stitch import engine in SwarmView.tsx recursively scans HTML, CSS, assets, and images, automatically appending custom conversion rules to the mission payload. It instructs the Scout to map layout boundaries and guides builders to convert static HTML folders into modular React screens.

4. Memory Injection & Task Seeding

Before launching, the Coordinator automatically connects to **MeshMemory** to build context packs. The context pack retrieves historic decisions, conventions, and API structures from prior sessions.

Additionally, to prevent the Kanban board from starting empty, the crew seeds starter tasks directly into hosted **MeshMCP** for the Scout, Builders, and Reviewer (see taskUtils.ts).

Technical Details & State Machine

The Local Crew Engine relies on regex patterns matching stdout/stderr buffers from terminal panes to evaluate task progression and state changes.

Completion & Handoff Signals

The orchestrator listens for specific completion and control tags emitted by agent terminal processes:

SCOUT_DONE
/SCOUT[_\s]COMPLETE/i
BUILDER_DONE
/BUILDER(?:[-\s]*\d+)?[_\s]COMPLETE/i
REVIEWER_APPROVED
/REVIEWER[_\s]APPROVED/i
REVIEWER_REJECTED
/(?:REVIEWER[_\s]REJECTED|NEEDS[_\s]FIXES|CHANGES[_\s]REQUESTED)/i
REVIEWER_DONE
/(?:REVIEWER[_\s]COMPLETE|REVIEW[_\s]COMPLETE|SWARM[_\s]COMPLETE)/i
SHARE
/^[ \t>]*SHARE:\s*(.+)$/gim (Captures shared facts to append to MESH_CHART/context.md)
TASK_ID
/task[_\s]?id[=:\s]+([a-zA-Z0-9_-]+)/i (Pairs process output with a MeshMCP task ID)

Stall Protection Watchdog

To prevent the Crew from hanging indefinitely if an LLM crashes, gets rate-limited, or fails to emit a completion tag, the engine implements a stall watchdog:

  • STALL_MS: Configured to 4 * 60 * 1000 (4 minutes).
  • Operation: The orchestrator arms a timer when dispatching an agent. Each new line of terminal output clears and restarts the timer.
  • Resolution: If the agent generates no output for 4 minutes, the engine assumes a stall, automatically completes the agent state with the status 'stall timeout - no output', and advances the DAG.

Rejection, Bounce, and Retries

If the Reviewer issues a reject verdict, the Coordinator maps the failure back to the responsible agent based on the parsed task_id. The engine transitions that builder's state back to 'idle', resets its buffers, and re-dispatches the agent with feedback injected into the prompt:

typescriptcopy
// Inside swarmEngine.ts - Bouncing a builder for corrections
private bounceBuilder(es: EngineSession, taskId?: string): void {
  const builder = taskId
    ? es.agents.find((a) => a.role === 'builder' && a.taskId === taskId)
    : es.agents.find((a) => a.role === 'builder' && a.state === 'awaiting-review');
  if (!builder) return;
  
  if (taskId) this.pushTaskStatus(es, taskId, 'in_progress');
  builder.state = 'idle';
  builder.outputSeen = false;
  builder.buffer = '';
  this.dispatch(es, builder, 'Reviewer requested changes. Re-read your task notes and fix the reported issues.');
}

Quota & API Failure Protection

The engine monitors terminal buffers for API limits and auth issues via the BLOCKED regex. If hit, the agent state changes to 'blocked', allowing the user to resolve API keys or credit issues without corrupting the session.

typescriptcopy
const BLOCKED = /(exhausted your capacity|RESOURCE_EXHAUSTED|rate\s+limit\s+exceeded|quota\s+will\s+reset|You\s+have\s+exhausted|\bUnauthorized\b|\b401\b|MCP\s+connection\s+failed)/i;

Task Splitting & Parallel Conflict Resolution

Running multiple builders in parallel poses a high risk of write conflicts if two agents edit the same file. MeshPilot solves this using two mechanisms:

  • Non-Overlapping File Ownership: During the wizard execution, tasks are separated. taskUtils.ts provides inferTaskAssignment, which counts current task loads and assigns files. The Coordinator builds custom instructions targeting only those files, ensuring builders do not access overlapping paths.
  • Broker-Mediated Shared Context: Agents read MESH_CHART/context.md upon startup. If any agent discovers a critical convention or API change, it outputs SHARE: <fact>. The Coordinator intercepts this and updates context.md. Agents read this file to stay aligned on variables, ports, and configuration rules, eliminating terminal-to-terminal prompt spam.

Best Practices for AI Crews

  • Provide a Detailed Crew Mission: Describe the tech stack, API boundaries, and endpoints in the initial mission payload.
  • Leverage the Stitch Design Import: If converting static designs to React or Vue, import the Stitch export folder. It auto-configures paths and asset assets for the agents.
  • Create Independent Tasks: When designing custom task checklists, verify that files assigned to Builder A do not import elements from Builder B that are still unwritten.
  • Keep the Reviewer Active: Enable the *Code Review* skill for production releases to ensure test suites pass before merging code.

Troubleshooting

Crew hangs on "Awaiting Review"

This usually happens when a builder finishes its task but fails to print the completion marker, or the printed task ID doesn't match the record in MeshMCP. Check the agent's terminal logs. You can manually advance the crew or rerun the agent using the Re-dispatch button in MeshConsole.

All agents show "Blocked"

This indicates that your LLM provider has rate-limited your account or your credits are exhausted. Resolve the limit in your provider dashboard, check your API key in settings, and click **Relaunch Crew** to resume.

Related Pages

  • MeshConsole - Managing terminal panes, CLI presets, and developer environments.
  • MeshMCP - Custom Model Context Protocol integrations and remote task synchronization.
  • MeshMemory - Archiving, retrieving, and packaging semantic codebase decisions.

Ready to build

Move from reading the docs to running MeshPilot.

Create a free account, install MeshConsole, and connect your first MCP client. Support is one click away if you get stuck.