Claude
Skills
Sign in
Back

ai-multi-agent

Included with Lifetime
$97 forever

Multi-agent orchestration — N AI agents with distinct personas debate sequentially in real-time. Each agent sees prior agents' output, creating adversarial pressure-testing. Use this skill when the user says "add multi-agent", "ai debate", "agent panel", "multi-agent chat", or "adversarial agents".

AI Agents

What this skill does


# AI Multi-Agent

Multi-agent orchestration where N AI agents with distinct personas (Product Manager, QA Engineer, Senior Engineer) debate sequentially in real-time. Each agent sees all prior agents' output in its context, creating a chain of adversarial pressure-testing against feature specifications.

The key innovation: agents run SEQUENTIALLY, not in parallel. PM writes the happy path, QA reads PM's output and pokes holes, Engineer reads both and flags constraints. Each subsequent agent gets all prior agents' outputs in its context. This sequential chain is what creates the adversarial pressure-testing.

## Prerequisites

- Next.js app with `src/` directory and App Router
- `ai-core` skill installed (`getModel()` available at `@/lib/ai`)
- `ai-chat` skill installed (provides chat page, `withAuth` from auth dependency)
- shadcn/ui initialized

## Installation

No additional packages required. Uses `streamText` from the `ai` package (already installed by `ai-core`) and `@phosphor-icons/react` (already installed by `ai-chat`).

## What Gets Created

```
src/
├── lib/
│   └── ai/
│       └── agents/
│           ├── types.ts           # AgentConfig, AgentMessage, DebateRound types
│           ├── registry.ts        # Default agent configs (PM, QA, Engineer) + register/get
│           └── prompts.ts         # System prompt builders per agent role
├── app/
│   └── api/
│       └── ai/
│           └── debate/
│               └── route.ts       # POST — runs sequential agent debate, streams via SSE
└── components/
    └── ai/
        └── multi-agent/
            ├── debate-panel.tsx    # Container: triggers debate, renders agent streams
            ├── agent-message.tsx   # Single agent message with Accept/Dismiss buttons
            └── agent-badge.tsx     # Color-coded agent name badge
```

## What Gets Modified

```
src/app/(app)/chat/page.tsx    # Add debate panel as right column
```

## Comment Slots

- **chat/page.tsx**: `// [ai-multi-agent]: add debate panel` — adds debate panel as a right column in the chat layout

## Setup Steps

### Step 1: Create `src/lib/ai/agents/types.ts`

```typescript
export type AgentRole = "pm" | "qa" | "engineer";

export type AgentConfig = {
  id: string;
  name: string;
  role: AgentRole;
  color: string;
  description: string;
  systemPrompt: string;
};

export type AgentMessage = {
  id: string;
  agentId: string;
  role: AgentRole;
  content: string;
  timestamp: string;
  status: "streaming" | "complete" | "accepted" | "dismissed";
};

export type DebateRound = {
  id: string;
  context: string;
  messages: AgentMessage[];
  createdAt: string;
};

export type DebateStreamEvent =
  | { type: "agent-start"; agentId: string; agentName: string; agentRole: AgentRole; color: string }
  | { type: "text-delta"; agentId: string; text: string }
  | { type: "agent-done"; agentId: string }
  | { type: "debate-done" };
```

### Step 2: Create `src/lib/ai/agents/registry.ts`

```typescript
import type { AgentConfig } from "./types";

const agentRegistry = new Map<string, AgentConfig>();

// --- Default agents ---

agentRegistry.set("pm", {
  id: "pm",
  name: "Product Manager",
  role: "pm",
  color: "#3b82f6",
  description: "Focuses on user value, happy path, prioritization, and acceptance criteria.",
  systemPrompt: `You are a Product Manager reviewing a feature specification. Your job is to:
1. Clarify the user value and happy path
2. Prioritize features by impact
3. Identify missing user stories
4. Suggest acceptance criteria

Respond with 2-4 observations. Each observation starts with a tag:
- [REQUIREMENT]: Something that must be in the spec
- [SUGGESTION]: An improvement that would add value
- [QUESTION]: An ambiguity that needs resolution

Be specific and actionable. Reference the spec text directly.`,
});

agentRegistry.set("qa", {
  id: "qa",
  name: "QA Engineer",
  role: "qa",
  color: "#ef4444",
  description: "Focuses on edge cases, error states, race conditions, and accessibility gaps.",
  systemPrompt: `You are a QA Engineer reviewing a feature specification. Your job is to:
1. Find edge cases the PM missed
2. Identify error states and failure modes
3. Flag race conditions and concurrency issues
4. Check accessibility and internationalization gaps
5. Challenge assumptions with "what if" scenarios

You've read the PM's observations below. Build on them — don't repeat.
Respond with 2-4 observations. Each starts with a tag:
- [EDGE_CASE]: A scenario not covered by the spec
- [ERROR_STATE]: What happens when something fails
- [CONCERN]: A potential problem with the current approach
- [QUESTION]: Something that needs clarification`,
});

agentRegistry.set("engineer", {
  id: "engineer",
  name: "Engineer",
  role: "engineer",
  color: "#22c55e",
  description: "Focuses on technical constraints, implementation approaches, complexity estimates, and dependencies.",
  systemPrompt: `You are a Senior Engineer reviewing a feature specification. Your job is to:
1. Flag technical constraints and feasibility issues
2. Suggest implementation approaches
3. Estimate complexity (S/M/L/XL)
4. Identify dependencies on other systems
5. Note performance implications

You've read both PM and QA observations. Build on them.
Respond with 2-4 observations. Each starts with a tag:
- [CONSTRAINT]: A technical limitation to consider
- [APPROACH]: A recommended implementation strategy
- [COMPLEXITY]: Size estimate with justification
- [DEPENDENCY]: An external system this depends on`,
});

// --- Public API ---

export function getAgent(id: string): AgentConfig | undefined {
  return agentRegistry.get(id);
}

export function getAllAgents(): AgentConfig[] {
  return Array.from(agentRegistry.values());
}

export function registerAgent(config: AgentConfig): void {
  agentRegistry.set(config.id, config);
}
```

### Step 3: Create `src/lib/ai/agents/prompts.ts`

```typescript
import type { AgentConfig } from "./types";

type PriorOutput = {
  agentName: string;
  content: string;
};

/**
 * Builds the full system prompt for an agent, injecting prior agents' outputs
 * so each subsequent agent can reference and build upon earlier observations.
 */
export function buildAgentPrompt(
  agent: AgentConfig,
  priorOutputs: PriorOutput[]
): string {
  if (priorOutputs.length === 0) {
    return agent.systemPrompt.replace("{prior_context}", "");
  }

  const priorContext = priorOutputs
    .map(
      (output) =>
        `--- ${output.agentName}'s observations ---\n${output.content}`
    )
    .join("\n\n");

  const contextBlock = `\n\nPrior observations from other reviewers:\n\n${priorContext}`;

  // If the system prompt contains {prior_context}, replace it.
  // Otherwise, append the context block at the end.
  if (agent.systemPrompt.includes("{prior_context}")) {
    return agent.systemPrompt.replace("{prior_context}", contextBlock);
  }

  return `${agent.systemPrompt}${contextBlock}`;
}
```

### Step 4: Create `src/app/api/ai/debate/route.ts`

```typescript
import { streamText } from "ai";
import { getModel } from "@/lib/ai";
import { withAuth } from "@/lib/auth-guard";
import { getAllAgents } from "@/lib/ai/agents/registry";
import { buildAgentPrompt } from "@/lib/ai/agents/prompts";
import type { DebateStreamEvent } from "@/lib/ai/agents/types";

export const POST = withAuth(async (request, { user: _user }) => {
  const { context }: { context: string } = await request.json();

  if (!context?.trim()) {
    return Response.json({ error: "Context is required" }, { status: 400 });
  }

  const agents = getAllAgents();
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    async start(controller) {
      const send = (event: DebateStreamEvent) => {
        controller.enqueue(
          encoder.encode(`data: ${JSON.stringify(event)}\n\n`)
        );
      };

      const priorOutputs: Array<{ agentName: string; content: string }> = [];

      for (const agent of agents) {
        send({
          type: "agent-start",
   
Files: 1
Size: 27.6 KB
Complexity: 38/100
Category: AI Agents

Related in AI Agents