Agents & Multi-Agent Orchestration

CodeCLI agents are AI-driven workers that execute tasks using tools, file operations, shell commands, and other agents. The multi-agent system supports primary agents, subagents, swarm orchestration with wave-based DAG scheduling, mainframe terminal control, and worktree isolation for safe parallel execution.

Agent Types

TypeDescriptionInvoked By
Primary AgentThe main conversational agent that receives user prompts and orchestrates workUser input
SubagentA child agent spawned by the primary agent to handle a specific subtaskTask tool
Swarm AgentOne of many agents in a coordinated swarm executing a DAG of tasksSwarm scheduler
Mainframe AgentAn agent running inside a terminal pane in mainframe modeMainframe controller

Primary Agents

The primary agent is the top-level agent you interact with in CodeCLI. It receives your messages, decides which tools to use, and can spawn subagents for parallel or independent work. The primary agent has full access to all tools and permissions configured in your session.

When you type a prompt into CodeCLI, the primary agent:

  1. Reads your message and any attached context
  2. Consults its system prompt, CLAUDE.md files, and loaded skills
  3. Plans a sequence of tool calls to accomplish the task
  4. Executes tool calls, checking permissions as needed
  5. May spawn subagents for independent subtasks
  6. Aggregates results and presents the final response

Subagents

Subagents are spawned by the primary agent (or other subagents) using the task tool. Each subagent runs independently with its own context window and can use the full set of available tools. Subagents are ideal for tasks that can be parallelized or isolated.

iNote
Subagents inherit the permissions and tool access of the parent agent unless explicitly restricted in the agent configuration.

Agent Configuration

Agents are configured through frontmatter in markdown files or through thecodecli.json configuration file. The configuration controls the model, temperature, permissions, available tools, and execution behavior.

Configuration Schema

FieldTypeDefaultDescription
modelstringclaude-sonnet-4-20250514AI model to use for this agent
temperaturenumber0.0Sampling temperature (0.0 - 2.0)
maxTokensnumber16384Maximum tokens in the response
maxStepsnumber75Maximum tool-use turns before stopping
maxTurnsnumber200Maximum total conversation turns
permissionsobject{}Per-tool permission overrides
toolsstring[]allExplicit tool whitelist or blacklist
systemPromptstringdefaultCustom system prompt for this agent
allowedCommandsstring[][]Shell commands the agent is allowed to run
blockedCommandsstring[][]Shell commands the agent is blocked from running
timeoutnumber600Maximum execution time in seconds
retryOnFailurebooleanfalseWhether to retry on tool failures
maxRetriesnumber2Maximum number of retries per tool call
worktreebooleanfalseRun in an isolated git worktree
descriptionstringHuman-readable description of the agent

Example: Agent Configuration File

codecli.json
json
{
"agents": {
"code-reviewer": {
"model": "claude-sonnet-4-20250514",
"temperature": 0.0,
"maxSteps": 50,
"permissions": {
"read": "allow",
"bash": "allow",
"edit": "deny"
},
"systemPrompt": "You are a code reviewer. Read files and provide feedback. Never edit files.",
"description": "Reviews code and provides feedback without making changes"
},
"test-writer": {
"model": "claude-sonnet-4-20250514",
"temperature": 0.2,
"maxSteps": 75,
"permissions": {
"read": "allow",
"bash": "allow",
"edit": "allow",
"glob": "allow",
"grep": "allow"
},
"allowedCommands": ["npm", "npx", "jest", "vitest"],
"systemPrompt": "You write tests. Read the source code and write comprehensive test files.",
"description": "Writes test files for source code"
}
}
}

Example: Agent as Markdown Frontmatter

agents/security-auditor.md
markdown
---
model: claude-sonnet-4-20250514
temperature: 0.0
maxSteps: 100
permissions:
read: allow
bash: deny
edit: deny
grep: allow
glob: allow
tools:
- read
- grep
- glob
- websearch
---
You are a security auditor agent. Your job is to scan codebases for common
vulnerabilities including:
- SQL injection
- XSS vulnerabilities
- Hardcoded secrets
- Insecure dependencies
- Authentication bypass issues
Scan all files in the provided paths and produce a detailed security report.
Never modify any files. Only read and analyze.

Agent Selection and Invocation

Agents are selected automatically based on the task or explicitly using slash commands and the task tool. The selection process follows these rules:

  1. Explicit invocation — Use /agent NAME to activate a specific named agent
  2. Task tool — The primary agent spawns a subagent with {"agent": "name"}
  3. Automatic routing — CodeCLI selects the best agent based on the task description and agent descriptions

Invoking Agents with the Task Tool

Task tool invocation
json
// Spawn a single subagent
{
"tool": "task",
"description": "Review the authentication module for security issues",
"agent": "security-auditor"
}
// Spawn a subagent with a specific prompt
{
"tool": "task",
"description": "Write tests for src/auth/*.ts",
"agent": "test-writer",
"prompt": "Focus on edge cases for password hashing and token validation"
}

Multi-Agent Orchestration

The task tool enables the primary agent to delegate work to subagents. Subagents can be spawned sequentially or in parallel depending on task dependencies. CodeCLI manages the lifecycle, context windows, and result aggregation automatically.

Sequential Execution

When tasks have dependencies (task B requires output from task A), the primary agent chains them sequentially:

Sequential subagent execution
json
// Step 1: Analyze codebase
{
"tool": "task",
"description": "Analyze the codebase structure and list all public APIs",
"agent": "code-reviewer"
}
// Step 2: Generate docs based on analysis results
{
"tool": "task",
"description": "Generate API documentation based on the analysis",
"agent": "doc-writer"
}

Parallel Subagent Execution

When tasks are independent, the primary agent can spawn multiple subagents that run concurrently. Each subagent gets its own context window and executes independently. Results are collected and merged when all subagents complete.

Parallel subagent spawning
json
// All three tasks run simultaneously
[
{
"tool": "task",
"description": "Review src/auth/ for security issues",
"agent": "security-auditor"
},
{
"tool": "task",
"description": "Write tests for src/auth/",
"agent": "test-writer"
},
{
"tool": "task",
"description": "Check src/auth/ for style guide compliance",
"agent": "linter"
}
]
Tip
Parallel subagents are most effective when working on independent files or modules. When subagents need to edit overlapping files, use worktree isolation to prevent merge conflicts.

Swarm Orchestration

For large-scale tasks, CodeCLI supports swarm mode with wave-based DAG (Directed Acyclic Graph) scheduling. A swarm is a collection of agents that execute tasks according to a dependency graph, where each "wave" contains tasks that can run in parallel.

How Wave-Based DAG Scheduling Works

1
  • The orchestrator decomposes the top-level task into a DAG of subtasks
  • 2
  • Tasks with no dependencies form Wave 0 and execute immediately
  • 3
  • As each wave completes, dependent tasks become unblocked and form the next wave
  • 4
  • All tasks within a wave execute in parallel across available agent slots
  • 5
  • Results from each wave are merged and passed to dependent tasks in subsequent waves
  • 6
  • The process repeats until all tasks in the DAG are complete
  • DAG Visualization

    Wave execution diagram
    text
    Wave 0 (parallel): Wave 1 (parallel): Wave 2: Wave 3:
    +---------------+ +---------------+ +----------+ +----------+
    | Analyze | | Write Tests | | Run All | | Generate |
    | codebase |--->| for Auth |--->| Tests |--->| Coverage |
    | structure | +---------------+ | | | Report |
    +---------------+ +---------------+ +----------+ +----------+
    | | Write Docs | ^
    v | for API |----------+
    +---------------+ +---------------+
    | Identify |
    | public APIs |
    +---------------+

    Swarm Configuration

    codecli.json — swarm settings
    json
    {
    "swarm": {
    "maxConcurrentAgents": 4,
    "defaultAgentModel": "claude-sonnet-4-20250514",
    "timeoutPerAgent": 300,
    "mergeStrategy": "sequential-rebase",
    "worktreeIsolation": true,
    "onConflict": "fail-and-report",
    "retryFailedWaves": true,
    "maxWaveRetries": 2
    }
    }
    SettingTypeDefaultDescription
    maxConcurrentAgentsnumber4Maximum number of agents running in parallel per wave
    defaultAgentModelstringclaude-sonnet-4-20250514Default model for swarm agents
    timeoutPerAgentnumber300Timeout in seconds per individual agent
    mergeStrategystringsequential-rebaseHow to merge results: sequential-rebase, patch-merge, or fail
    worktreeIsolationbooleantrueRun each agent in an isolated git worktree
    onConflictstringfail-and-reportAction on merge conflicts: fail-and-report, prefer-newest, or prefer-oldest
    retryFailedWavesbooleantrueRetry failed tasks in a wave before failing the entire swarm
    maxWaveRetriesnumber2Maximum number of retries for failed wave tasks

    Mainframe Terminal Control

    Mainframe mode provides a split-pane terminal interface where multiple agents run simultaneously, each in its own terminal pane. This gives you real-time visibility into what each agent is doing and allows direct interaction with any agent.

    Starting Mainframe Mode

    Terminal
    bash
    # Start mainframe with 4 agent panes
    codecli --mainframe --panes 4
    # Start mainframe with a specific layout
    codecli --mainframe --layout "2x2"
    # Start mainframe with named agents
    codecli --mainframe --agents "researcher,coder,tester,reviewer"

    Mainframe Commands

    CommandDescription
    :focus NUMBERSwitch focus to a specific agent pane
    :broadcast MESSAGESend the same message to all agent panes
    :pause NUMBERPause execution in a specific pane
    :resume NUMBERResume a paused pane
    :kill NUMBERTerminate a specific agent pane
    :spawn AGENTAdd a new agent pane
    :layout LAYOUTChange the pane layout (2x1, 2x2, 3x1, etc.)
    :mergeMerge all agent results into a summary
    :quitExit mainframe mode
    iNote
    Mainframe mode requires a terminal that supports ANSI escape sequences. It works best in terminals with at least 120 columns and 40 rows.

    Worktree Isolation

    When multiple agents need to edit files in the same repository, worktree isolation prevents conflicts by giving each agent its own git worktree. Each worktree is a separate checkout of the repository at the same commit, allowing agents to work independently.

    How Worktree Isolation Works

    1
  • CodeCLI creates a git worktree for each agent under .claude/worktrees/
  • 2
  • Each agent operates in its own worktree directory with full file access
  • 3
  • When an agent completes, its changes are committed to a separate branch
  • 4
  • CodeCLI merges agent branches back using the configured merge strategy
  • 5
  • Conflicts are handled according to the onConflict setting
  • Worktree directory structure
    bash
    .claude/
    worktrees/
    agent-1/ # Worktree for agent 1
    src/
    auth.ts # Agent 1's version
    agent-2/ # Worktree for agent 2
    src/
    utils.ts # Agent 2's version
    agent-3/ # Worktree for agent 3
    tests/
    auth.test.ts

    Merge Strategies

    StrategyDescriptionUse When
    sequential-rebaseRebases each agent branch onto main one at a timeAgents edit overlapping files
    patch-mergeGenerates patches per agent and applies them in orderAgents edit different files
    failStops on first conflict and requires manual resolutionSafety-critical codebases

    Agent-Specific Tools and Permissions

    Each agent can be configured with a specific set of tools and permission levels. This allows you to create agents with narrowly scoped capabilities for security and reliability.

    Tool Availability by Agent Type

    ToolPrimary AgentSubagentSwarm AgentMainframe Agent
    bashYesYesYesYes
    read / write / editYesConfigurableConfigurableConfigurable
    glob / grepYesYesYesYes
    task (spawn subagents)YesYesNoYes
    webfetch / websearchYesConfigurableConfigurableConfigurable
    computer_useYesConfigurableNoNo
    skillYesYesYesYes
    todowrite / todoreadYesYesYesYes
    kanbanwrite / kanbanreadYesNoNoNo
    mcp_* (MCP tools)YesConfigurableConfigurableConfigurable

    Example: Read-Only Agent

    codecli.json — read-only agent
    json
    {
    "agents": {
    "analyst": {
    "model": "claude-sonnet-4-20250514",
    "temperature": 0.0,
    "permissions": {
    "read": "allow",
    "glob": "allow",
    "grep": "allow",
    "bash": "deny",
    "edit": "deny",
    "write": "deny"
    },
    "systemPrompt": "You are a code analyst. Only read files and provide analysis. Never modify anything."
    }
    }
    }

    Example: Full-Access Agent with Command Restrictions

    codecli.json — restricted agent
    json
    {
    "agents": {
    "frontend-dev": {
    "model": "claude-sonnet-4-20250514",
    "temperature": 0.3,
    "permissions": {
    "read": "allow",
    "edit": "allow",
    "write": "allow",
    "bash": "allow",
    "glob": "allow",
    "grep": "allow"
    },
    "allowedCommands": [
    "npm", "npx", "node", "pnpm", "yarn",
    "git status", "git diff", "git log",
    "eslint", "prettier", "tsc"
    ],
    "blockedCommands": [
    "rm -rf", "sudo", "curl", "wget", "ssh"
    ],
    "systemPrompt": "You are a frontend developer. Focus on React/TypeScript code."
    }
    }
    }
    PreviousSessionsNextSkills