> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codemachine.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Build Agents

> Configure main agents, sub-agents, modules, and controllers for your workflow.

This is the first step to create a workflow: defining **who**. Agents are the actors that execute each step of your workflow.

Agents are configured in JavaScript files inside the `config/` folder. Each agent type has its own configuration file.

| File             | Agent Type  | Purpose                                |
| ---------------- | ----------- | -------------------------------------- |
| `main.agents.js` | Main agents | Core workflow steps                    |
| `modules.js`     | Modules     | Agents with loop behavior              |
| `sub.agents.js`  | Sub-agents  | Delegated tasks spawned by main agents |

<Note>
  Controllers are defined in `main.agents.js` with `role: 'controller'`. They're main agents with special orchestration capabilities.
</Note>

***

## Main Agents

Main agents are the core building blocks of your workflow. Each main agent runs as a step in the workflow sequence.

### Basic Structure

```javascript config/main.agents.js theme={null}
const path = require('node:path');
const promptsDir = path.join(__dirname, '..', 'prompts', 'templates');

module.exports = [
  {
    id: 'planner',
    name: 'Project Planner',
    description: 'Analyzes requirements and creates implementation plan',
    promptPath: path.join(promptsDir, 'planner', 'main.md'),
  },
];
```

### Agent Fields

| Field                | Required | Description                                         |
| -------------------- | -------- | --------------------------------------------------- |
| `id`                 | Yes      | Unique identifier (lowercase, hyphens)              |
| `name`               | Yes      | Display name shown in UI                            |
| `description`        | Yes      | Brief description of what the agent does            |
| `promptPath`         | Yes      | Path or array of paths to prompt files              |
| `chainedPromptsPath` | No       | Array of chained prompt paths (multi-step agents)   |
| `role`               | No       | Set to `'controller'` for controller agents only    |
| `engine`             | No       | AI engine to use (defaults to workflow default)     |
| `model`              | No       | AI model to use (defaults to engine default)        |
| `tracks`             | No       | Array of track IDs this agent runs for              |
| `conditions`         | No       | Array of condition IDs (runs when ALL are selected) |
| `conditionsAny`      | No       | Array of condition IDs (runs when ANY is selected)  |

***

## Prompt Path: String vs Array

The `promptPath` field accepts either a single path or an array of paths.

<Tabs>
  <Tab title="String (Single File)" icon="file">
    One prompt file loaded as the agent's instructions.

    ```javascript theme={null}
    {
      id: 'planner',
      promptPath: path.join(promptsDir, 'planner', 'main.md'),
    }
    ```
  </Tab>

  <Tab title="Array (Multiple Files)" icon="layer-group">
    Multiple prompt files **merged into one** and shown to the agent as a single prompt. Use this to split large prompts into organized files.

    ```javascript theme={null}
    {
      id: 'planner',
      promptPath: [
        path.join(promptsDir, 'planner', 'persona.md'),
        path.join(promptsDir, 'planner', 'instructions.md'),
        path.join(promptsDir, 'planner', 'examples.md'),
      ],
    }
    ```
  </Tab>
</Tabs>

<Info>
  **promptPath array** = Files merged into one prompt, shown at once.

  **chainedPromptsPath** = Separate prompts injected sequentially, one after another with user interaction between each.
</Info>

### When to Use Array promptPath

| Use Case                  | Example                                                       |
| ------------------------- | ------------------------------------------------------------- |
| Organizing large prompts  | Split persona, instructions, and examples into separate files |
| Reusing prompt components | Share common instructions across agents                       |
| Maintaining readability   | Keep individual files focused and manageable                  |

```javascript theme={null}
// Complex agent with organized prompt structure
{
  id: 'architect',
  name: 'System Architect',
  description: 'Designs system architecture',
  promptPath: [
    path.join(promptsDir, 'shared', 'coding-standards.md'),
    path.join(promptsDir, 'architect', 'persona.md'),
    path.join(promptsDir, 'architect', 'workflow.md'),
    path.join(promptsDir, 'architect', 'output-format.md'),
  ],
}
```

***

## Single-Step vs Multi-Step

Agents can be single-step or multi-step based on whether they have chained prompts.

<Tabs>
  <Tab title="Single-Step" icon="circle-1">
    One prompt file, injected once. Best for focused tasks.

    ```javascript theme={null}
    {
      id: 'code-reviewer',
      name: 'Code Reviewer',
      description: 'Reviews code for issues and improvements',
      promptPath: path.join(promptsDir, 'reviewer', 'main.md'),
    }
    ```
  </Tab>

  <Tab title="Multi-Step" icon="list-ol">
    Multiple prompts injected sequentially into the same session. Best for complex workflows with progressive context.

    ```javascript theme={null}
    {
      id: 'onboarding-guide',
      name: 'Onboarding Guide',
      description: 'Guides users through project setup',
      promptPath: path.join(promptsDir, 'onboarding', 'main.md'),
      chainedPromptsPath: [
        path.join(promptsDir, 'onboarding', 'chained', 'step-01-intro.md'),
        path.join(promptsDir, 'onboarding', 'chained', 'step-02-setup.md'),
        path.join(promptsDir, 'onboarding', 'chained', 'step-03-config.md'),
      ],
    }
    ```

    <Card title="Writing Chained Prompts" icon="link" href="/build-workflows/write-prompts#chained-step-files">
      Learn how to write chained step files
    </Card>
  </Tab>
</Tabs>

### When to Use Each

| Type            | Use When                                                        |
| --------------- | --------------------------------------------------------------- |
| **Single-step** | Focused tasks, smaller prompts, minimal context needed          |
| **Multi-step**  | Q\&A flows, progressive context building, conversational agents |

<Info>
  Multi-step agents maintain the same session throughout all steps. The agent remembers everything from previous steps.
</Info>

***

## Modules

Modules are main agents with loop behavior. They can send the workflow back to earlier steps, creating validation gates and iteration cycles.

### Module Structure

```javascript config/modules.js theme={null}
const path = require('node:path');
const promptsDir = path.join(__dirname, '..', 'prompts', 'modules');

module.exports = [
  {
    id: 'quality-gate',
    name: 'Quality Gate',
    description: 'Validates work and loops back if issues found',
    promptPath: path.join(promptsDir, 'quality-gate', 'main.md'),
    behavior: {
      type: 'loop',
      action: 'stepBack',
    },
  },
];
```

### Module Fields

In addition to standard agent fields, modules have:

| Field             | Required | Description          |
| ----------------- | -------- | -------------------- |
| `behavior.type`   | Yes      | Must be `'loop'`     |
| `behavior.action` | Yes      | Must be `'stepBack'` |

### How Modules Control Flow

Modules communicate with the workflow by writing to a directive file when validation **fails**:

```
.codemachine/memory/directive.json
```

```json theme={null}
{
  "action": "loop",
  "reason": "Validation failed: 3 tests failing, missing error handling",
  "target": "developer"
}
```

If validation **passes**, no action is needed. The workflow continues to the next step by default.

<Warning>
  Your module's prompt **must** include instructions on how to validate and how to write the directive file. Without these instructions, the agent won't know how to trigger the loop.
</Warning>

<Card title="Writing Module Prompts" icon="pen" href="/build-workflows/write-prompts#module-prompts">
  Learn how to write prompts that instruct modules to validate and write directives
</Card>

<Card title="Workflow Signals MCP" icon="plug" href="#workflow-signals">
  Configure MCP for directive-based workflow control
</Card>

### Common Module Patterns

<AccordionGroup>
  <Accordion title="Validation Loop" icon="check-double">
    Check work quality, fix issues, re-check until passing.

    ```javascript theme={null}
    {
      id: 'validator',
      name: 'Code Validator',
      description: 'Validates code quality and loops if issues found',
      promptPath: path.join(promptsDir, 'validator', 'main.md'),
      behavior: { type: 'loop', action: 'stepBack' },
    }
    ```
  </Accordion>

  <Accordion title="Review Cycle" icon="rotate">
    Review output, request changes, iterate until approved.

    ```javascript theme={null}
    {
      id: 'reviewer',
      name: 'Review Module',
      description: 'Reviews and requests revisions until approved',
      promptPath: path.join(promptsDir, 'reviewer', 'main.md'),
      behavior: { type: 'loop', action: 'stepBack' },
    }
    ```
  </Accordion>

  <Accordion title="Quality Gate" icon="shield-check">
    Block progression until quality threshold is met.

    ```javascript theme={null}
    {
      id: 'quality-gate',
      name: 'Quality Gate',
      description: 'Ensures quality standards before proceeding',
      promptPath: path.join(promptsDir, 'quality-gate', 'main.md'),
      behavior: { type: 'loop', action: 'stepBack' },
    }
    ```
  </Accordion>
</AccordionGroup>

### Workflow File Options

When using modules in your workflow file, you can configure loop behavior:

```javascript theme={null}
resolveModule('quality-gate', {
  loopSteps: 2,           // How many steps to go back
  loopMaxIterations: 3,   // Maximum loop attempts
  loopSkip: ['logger'],   // Agents to skip on re-loop
})
```

***

## Sub-Agents

Sub-agents are helper agents that main agents can spawn during execution. They run as separate sessions and return results to the calling agent.

### When to Use Sub-Agents

* Delegating specialized subtasks
* Parallel task execution
* Context isolation for specific work
* Reusable agent capabilities

### Sub-Agent Types

<Tabs>
  <Tab title="Static" icon="file">
    Pre-defined prompt file. You define the prompt at build time.

    ```javascript config/sub.agents.js theme={null}
    {
      id: 'test-writer',
      name: 'Test Writer',
      description: 'Writes unit tests for given code',
      mirrorPath: path.join(promptsDir, 'sub-agents', 'test-writer.md'),
    }
    ```
  </Tab>

  <Tab title="Dynamic" icon="bolt">
    No prompt file. The main agent generates the prompt at runtime.

    ```javascript config/sub.agents.js theme={null}
    {
      id: 'specialist',
      name: 'Dynamic Specialist',
      description: 'Specialized agent generated at runtime',
      // No mirrorPath - empty .md file created in .codemachine/agents/
    }
    ```
  </Tab>
</Tabs>

### Why Sub-Agent Prompts Live in `.codemachine/`

Unlike main agents whose prompts are in the `prompts/` folder, sub-agent prompts live in the runtime `.codemachine/agents/` folder. This design enables:

* **Dynamic prompt generation** - A main agent (like an `agent-builder`) can write prompts for sub-agents at runtime
* **Cross-agent access** - Other agents can read and modify sub-agent prompts during workflow execution
* **Flexibility** - Use static prompts via `mirrorPath`, or leave it empty for fully dynamic sub-agents that receive instructions when invoked

Sub-agents are also accessible via the `codemachine run` command for direct execution.

### Sub-Agent Fields

| Field         | Required    | Description                     |
| ------------- | ----------- | ------------------------------- |
| `id`          | Yes         | Unique identifier               |
| `name`        | Yes         | Display name                    |
| `description` | Yes         | What the sub-agent does         |
| `mirrorPath`  | Static only | Path to pre-defined prompt file |

### Invoking Sub-Agents

Sub-agents must be invoked via MCP tools or CLI commands.

**Example orchestrator with agent-coordination MCP:**

```javascript main.agents.js theme={null}
{
  id: 'blueprint-orchestrator',
  name: 'Blueprint Orchestrator',
  description: 'Coordinates architecture sub-agents',
  promptPath: path.join(promptsDir, 'orchestrator', 'main.md'),
  mcp: [
    {
      server: 'agent-coordination',
      only: ['run_agents', 'get_agent_status', 'list_available_agents'],
      targets: ['data-architect', 'api-architect', 'ui-architect'],
    },
  ],
}
```

<Warning>
  Include MCP tools documentation in your main agent's prompt if it needs to call sub-agents.
</Warning>

<Card title="Writing Sub-Agent Prompts" icon="pen" href="/build-workflows/write-prompts#sub-agent-prompts">
  Learn how to write prompts for agents that orchestrate sub-agents
</Card>

<CardGroup cols={3}>
  <Card title="Agent Coordination MCP" icon="plug" href="#agent-coordination">
    Configure MCP for sub-agents
  </Card>

  <Card title="CLI Reference" icon="terminal" href="/reference/cli-reference">
    Run sub-agents via CLI
  </Card>

  <Card title="Full Example" icon="book-open" href="/build-workflows/workflow-examples#technical-implementation-3">
    See complete workflow
  </Card>
</CardGroup>

***

## Controllers

Controllers are special agents that orchestrate autonomous workflows. They respond on behalf of the user, driving the entire workflow.

Controllers require `role: 'controller'` and must be configured with the `workflow-signals` MCP to approve step transitions.

**Example controller and step agent with workflow-signals MCP:**

```javascript main.agents.js theme={null}
module.exports = [
  // Controller - Approves/rejects step transitions
  {
    id: 'project-controller',
    name: 'Project Controller',
    role: 'controller',
    promptPath: path.join(promptsDir, 'controller', 'main.md'),
    mcp: [
      {
        server: 'workflow-signals',
        only: ['approve_step_transition', 'get_pending_proposal'],
      },
    ],
  },

  // Step agents - Propose completion
  {
    id: 'pm',
    name: 'Product Manager',
    promptPath: path.join(promptsDir, 'pm', 'main.md'),
    mcp: [
      {
        server: 'workflow-signals',
        only: ['propose_step_completion'],
      },
    ],
  },

  // ... other step agents with same MCP config
];
```

<Warning>
  Both controller and all step agents must have `workflow-signals` MCP configured for autonomous mode to work.
</Warning>

<CardGroup cols={2}>
  <Card title="Workflow Signals MCP" icon="plug" href="#workflow-signals">
    Configure MCP for autonomous mode
  </Card>

  <Card title="Full Example" icon="book-open" href="/build-workflows/workflow-examples#autonomous%3A-greenfield-project-build">
    See complete autonomous workflow
  </Card>
</CardGroup>

***

## Built-in MCP Servers

CodeMachine provides built-in MCP servers for agent coordination and workflow control. Configure these on your agents using the `mcp` field.

### MCP Configuration Fields

| Field     | Description                                                          |
| --------- | -------------------------------------------------------------------- |
| `server`  | The MCP server name (`'workflow-signals'` or `'agent-coordination'`) |
| `only`    | Array of tool names to expose (limits available tools)               |
| `targets` | Array of sub-agent IDs that can be invoked (agent-coordination only) |

***

### Workflow Signals

Controllers and step agents communicate through the `workflow-signals` MCP. Step agents propose completion, and the controller approves or rejects.

<Warning>
  Both controller and all step agents must have `workflow-signals` MCP configured for autonomous mode to work.
</Warning>

<Tabs>
  <Tab title="Controller Agent" icon="gamepad">
    The controller approves or rejects step transitions.

    ```javascript theme={null}
    {
      id: 'project-controller',
      name: 'Project Controller',
      description: 'Orchestrates workflow and approves transitions',
      role: 'controller',
      promptPath: path.join(promptsDir, 'controller', 'main.md'),
      mcp: [
        {
          server: 'workflow-signals',
          only: ['approve_step_transition', 'get_pending_proposal'],
        },
      ],
    }
    ```

    | Tool                      | Description                                   |
    | ------------------------- | --------------------------------------------- |
    | `approve_step_transition` | Accept or reject a step's completion proposal |
    | `get_pending_proposal`    | Read the current pending proposal from a step |
  </Tab>

  <Tab title="Step Agents" icon="list-ol">
    Step agents propose when they're done.

    ```javascript theme={null}
    {
      id: 'pm',
      name: 'Product Manager',
      description: 'Creates product requirements',
      promptPath: path.join(promptsDir, 'pm', 'main.md'),
      mcp: [
        {
          server: 'workflow-signals',
          only: ['propose_step_completion'],
        },
      ],
    }
    ```

    | Tool                      | Description                              |
    | ------------------------- | ---------------------------------------- |
    | `propose_step_completion` | Signal that the step is ready for review |
  </Tab>
</Tabs>

<Card title="See Autonomous Example" icon="book-open" href="/build-workflows/workflow-examples#autonomous%3A-greenfield-project-build">
  View a complete autonomous workflow with controller and step agents
</Card>

***

### Agent Coordination

Main agents or controllers that orchestrate sub-agents need the `agent-coordination` MCP configured.

```javascript theme={null}
{
  id: 'orchestrator',
  name: 'Orchestrator',
  description: 'Coordinates sub-agents for specialized tasks',
  promptPath: path.join(promptsDir, 'orchestrator', 'main.md'),
  mcp: [
    {
      server: 'agent-coordination',
      only: ['run_agents', 'get_agent_status'],
      targets: ['code-generator', 'test-runner', 'doc-writer'],
    },
  ],
}
```

| Tool                    | Description                   |
| ----------------------- | ----------------------------- |
| `list_available_agents` | Discover available sub-agents |
| `run_agents`            | Execute sub-agent scripts     |
| `get_agent_status`      | Check execution status        |
| `list_active_agents`    | See currently running agents  |

<Card title="See Sub-Agent Example" icon="book-open" href="/build-workflows/workflow-examples#technical-implementation-3">
  View a complete workflow using sub-agents with agent-coordination MCP
</Card>

***

## Agent Characters

Agent characters give your agents visual personality in the CLI. Each agent can have custom ASCII faces and phrases.

### Character Configuration

```json config/agent-characters.json theme={null}
{
  "personas": {
    "swagger": {
      "baseFace": "(⌐■_■)",
      "expressions": {
        "thinking": "(╭ರ_•́)",
        "tool": "<(•_•<)",
        "error": "(╥﹏╥)",
        "idle": "(⌐■_■)"
      },
      "phrases": {
        "thinking": ["Processing...", "Working on it..."],
        "tool": ["Got what I needed", "Perfect, moving on"],
        "error": ["Hmm, that didn't work", "Trying another way"],
        "idle": ["Ready when you are", "Your turn"]
      }
    }
  },
  "agents": {
    "planner": "swagger",
    "reviewer": "analytical"
  },
  "defaultPersona": "friendly"
}
```

### Pre-built Styles

| Style        | Base Face   | Best For                 |
| ------------ | ----------- | ------------------------ |
| `swagger`    | `(⌐■_■)`    | Cool, confident agents   |
| `friendly`   | `(˶ᵔ ᵕ ᵔ˶)` | Warm, helpful agents     |
| `analytical` | `[•_•]`     | Logical, precise agents  |
| `cheerful`   | `◕‿◕`       | Upbeat, positive agents  |
| `technical`  | `{•_•}`     | Developer-focused agents |
| `precise`    | `<•_•>`     | Validation, QA agents    |

### Custom Characters

Create custom characters by defining all expressions and phrases:

```json theme={null}
{
  "personas": {
    "my-custom-style": {
      "baseFace": "[◉_◉]",
      "expressions": {
        "thinking": "[◉~◉]",
        "tool": "[◉!◉]",
        "error": "[x_x]",
        "idle": "[◉_◉]"
      },
      "phrases": {
        "thinking": ["Analyzing...", "Computing..."],
        "tool": ["Data received", "Processing result..."],
        "error": ["Error encountered", "Retrying..."],
        "idle": ["Standing by", "Awaiting input"]
      }
    }
  }
}
```

<Note>
  If no character is defined for an agent, it falls back to the `swagger` character.
</Note>

***

## Engine & Model

Each agent can use a different AI engine and model. Configure `engine` and `model` fields to optimize for your use case.

<Card title="Model Configuration" icon="microchip" href="/build-workflows/model-configuration">
  See available engines, model options, reasoning effort, and fallback system
</Card>

***

## Track & Condition Filtering

Filter when agents run based on user-selected tracks and conditions.

### Agent-Level Filtering

Control when an entire agent runs:

```javascript theme={null}
{
  id: 'frontend-specialist',
  name: 'Frontend Specialist',
  description: 'Handles frontend implementation',
  promptPath: path.join(promptsDir, 'frontend', 'main.md'),
  tracks: ['frontend', 'fullstack'],    // Only runs for these tracks
  conditions: ['has_ui'],                // AND only if has_ui is selected
}
```

### Step-Level Filtering

For multi-step agents, filter individual steps:

```javascript theme={null}
{
  id: 'developer',
  name: 'Full Stack Developer',
  description: 'Implements features',
  promptPath: path.join(promptsDir, 'developer', 'main.md'),
  chainedPromptsPath: [
    // Always loads
    path.join(promptsDir, 'developer', 'chained', 'step-01-setup.md'),
    // Only for frontend track
    {
      path: path.join(promptsDir, 'developer', 'chained', 'step-02-react.md'),
      tracks: ['frontend'],
    },
    // Only if mobile condition selected
    {
      path: path.join(promptsDir, 'developer', 'chained', 'step-03-mobile.md'),
      conditions: ['has_mobile'],
    },
  ],
}
```

### Filtering Rules

* **Both track AND conditions must match** if both are specified
* **Empty arrays = always runs/loads**
* Agent-level filtering is checked first, then step-level

***

## Complete Example

Here's a complete `main.agents.js` with multiple agent types:

```javascript config/main.agents.js theme={null}
const path = require('node:path');
const promptsDir = path.join(__dirname, '..', 'prompts', 'templates');

module.exports = [
  // Single-step main agent
  {
    id: 'planner',
    name: 'Project Planner',
    description: 'Analyzes requirements and creates implementation plan',
    promptPath: path.join(promptsDir, 'planner', 'main.md'),
    engine: 'claude',
    model: 'opus',
  },

  // Multi-step main agent with filtering
  {
    id: 'developer',
    name: 'Developer',
    description: 'Implements the planned features',
    promptPath: path.join(promptsDir, 'developer', 'main.md'),
    chainedPromptsPath: [
      path.join(promptsDir, 'developer', 'chained', 'step-01-setup.md'),
      {
        path: path.join(promptsDir, 'developer', 'chained', 'step-02-frontend.md'),
        tracks: ['frontend', 'fullstack'],
      },
      {
        path: path.join(promptsDir, 'developer', 'chained', 'step-03-backend.md'),
        tracks: ['backend', 'fullstack'],
      },
    ],
    engine: 'codex',
    modelReasoningEffort: 'medium',
  },

  // Controller agent
  {
    id: 'project-controller',
    name: 'Project Owner',
    description: 'Orchestrates the workflow autonomously',
    role: 'controller',
    promptPath: path.join(promptsDir, 'controller', 'project-owner.md'),
    engine: 'claude',
    model: 'opus',
  },
];
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Write Prompts" icon="pen" href="./write-prompts">
    Create prompts for your agents
  </Card>

  <Card title="Your First Workflow" icon="rocket" href="./your-first-workflow">
    Put it all together in a workflow
  </Card>
</CardGroup>
