# Agent Forge - System Flow Diagram

## High-Level Flow

```
┌─────────────┐
│   User      │
│   Browser   │
└──────┬──────┘
       │
       │ 1. "Help me create an agent"
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│                    ChatInterface                         │
│  • Sends message to /api/chat                           │
│  • Receives tool call in response                       │
│  • Renders AgentForgeCard                               │
└──────┬───────────────────────────────────────────────────┘
       │
       │ 2. POST /api/chat
       │    { message, agentId: "agent-1" (Morgan) }
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│                   /api/chat Route                        │
│  • Forwards to Morgan's n8n webhook                     │
│  • Parses streaming response                            │
│  • Detects tool_call with name="create_agent_package"  │
│  • Returns { toolCall: {...} }                          │
└──────┬───────────────────────────────────────────────────┘
       │
       │ 3. Webhook request
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│              Morgan's n8n Workflow                       │
│  • Runs agent design conversation                       │
│  • Collects requirements                                │
│  • Generates complete system prompt                     │
│  • Emits tool call with payload:                        │
│    {                                                     │
│      agentId: "custom-uuid",                            │
│      displayName: "Agent Name",                         │
│      systemPrompt: "# Web Agent Bundle...",             │
│      ...metadata                                         │
│    }                                                     │
└──────┬───────────────────────────────────────────────────┘
       │
       │ 4. Tool call response
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│                  ChatInterface                           │
│  • Displays AgentForgeCard with payload                │
│  • User chooses action:                                 │
│    - Use now                                            │
│    - Pin for later                                      │
│    - Share                                              │
└──────┬───────────────────────────────────────────────────┘
       │
       ├──────────────────────────────────────────────────┐
       │                                                   │
       │ USE NOW                                           │ PIN
       │                                                   │
       ▼                                                   ▼
┌────────────────────────────────┐         ┌────────────────────────────┐
│   Register with Backend        │         │    Save to LocalStorage    │
│                                │         │                            │
│  POST /api/agents/create       │         │  Key: "pinned-agents"      │
│  {                             │         │  Value: [                  │
│    agentId,                    │         │    {                       │
│    systemPrompt,               │         │      agentId,              │
│    metadata                    │         │      displayName,          │
│  }                             │         │      systemPrompt,         │
│                                │         │      ...                   │
│  ▼                             │         │    }                       │
│                                │         │  ]                         │
│  n8n Registration Webhook      │         │                            │
│  • Stores prompt in DB         │         │  ▼                         │
│  • Returns promptToken         │         │                            │
│                                │         │  Confirmation message      │
│  ▼                             │         │  "✓ Agent pinned"          │
│                                │         │                            │
│  Switch to custom agent        │         └────────────────────────────┘
│  Update UI                     │
│  Timeline marker               │
│  "✓ Now chatting with X"       │
└────────────────────────────────┘
```

## Using a Custom Agent

```
┌─────────────┐
│   User      │
└──────┬──────┘
       │
       │ 1. Starts chat with custom agent
       │    (from "Use now" or pinned drawer)
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│                  ChatInterface                           │
│  • Calls handleUseAgentNow() or handleSelectPinnedAgent()│
│  • Registers agent (if needed)                          │
│  • Switches active agent                                │
└──────┬───────────────────────────────────────────────────┘
       │
       │ 2. User sends message
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│              POST /api/chat                              │
│  { message, agentId: "custom-xyz", ... }                │
└──────┬───────────────────────────────────────────────────┘
       │
       │ 3. Routes to custom webhook
       │    (detects agentId.startsWith("custom-"))
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│            n8n Custom Agent Webhook                      │
│  • Receives message                                      │
│  • Retrieves systemPrompt by agentId                    │
│  • Uses as system message for LLM                       │
│  • Returns response                                      │
└──────┬───────────────────────────────────────────────────┘
       │
       │ 4. Response (standard format)
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│                  ChatInterface                           │
│  • Displays assistant message                           │
│  • Continues conversation                               │
└──────────────────────────────────────────────────────────┘
```

## Pinned Agents Flow

```
┌─────────────┐
│   User      │
└──────┬──────┘
       │
       │ 1. Clicks bookmark icon
       │
       ▼
┌──────────────────────────────────────────────────────────┐
│            PinnedAgentsDrawer Opens                      │
│                                                          │
│  • Reads from localStorage["pinned-agents"]             │
│  • Displays reorderable list                            │
│  • Each card shows:                                     │
│    - Icon, name, summary                                │
│    - Tags and note                                      │
│    - "Start chat" button                                │
│    - Remove button                                      │
│                                                          │
│  User Actions:                                          │
│  ├─ Drag to reorder → saves to localStorage            │
│  ├─ Click "Start chat" → loads agent & starts session  │
│  └─ Click remove → deletes from localStorage           │
└─────────────────────────────────────────────────────────┘
```

## LocalStorage Structure

```javascript
// Pinned agents array
localStorage["pinned-agents"] = [
  {
    agentId: "custom-aurora-123",
    displayName: "Aurora Researcher",
    summary: "Synthesizes insights with citations",
    tags: ["research", "citations"],
    recommendedIcon: "🌌",
    whenToUse: "Use for research tasks...",
    systemPrompt: "# Web Agent Bundle Instructions\n...",
    pinnedAt: "2025-11-15T10:30:00.000Z",
    note: "Great for academic research"
  },
  // ... more agents
]

// Per-agent session (existing)
localStorage["chat-session-custom-aurora-123"] = "session-custom-aurora-123-1731672000000-abc123"

// Per-agent messages (existing)
localStorage["chat-messages-custom-aurora-123"] = [
  {
    id: "123",
    role: "user",
    content: "Help me research...",
    timestamp: "2025-11-15T10:31:00.000Z"
  },
  // ... more messages
]
```

## n8n Webhook Payloads

### 1. Morgan's Tool Call Response

```json
{
  "type": "tool_call",
  "name": "create_agent_package",
  "payload": {
    "agentId": "custom-aurora-researcher",
    "displayName": "Aurora Researcher",
    "summary": "Synthesizes multi-source insights with citations",
    "tags": ["research", "analysis", "citations"],
    "systemPrompt": "# Web Agent Bundle Instructions\n\nYou are now operating as...\n\n[FULL PROMPT HERE - 1000s of lines]",
    "hints": {
      "recommendedIcon": "🌌",
      "whenToUse": "Use when you need comprehensive research with proper citations"
    }
  }
}
```

### 2. Registration Webhook Request

```json
{
  "agentId": "custom-aurora-researcher",
  "systemPrompt": "# Web Agent Bundle Instructions...",
  "metadata": {
    "displayName": "Aurora Researcher",
    "summary": "Synthesizes multi-source insights with citations",
    "tags": ["research", "analysis", "citations"],
    "recommendedIcon": "🌌",
    "whenToUse": "Use when you need comprehensive research...",
    "createdAt": "2025-11-15T10:30:00.000Z"
  }
}
```

### 3. Registration Webhook Response

```json
{
  "success": true,
  "agentId": "custom-aurora-researcher",
  "promptToken": "encrypted-token-or-agentId",
  "message": "Agent registered successfully"
}
```

### 4. Custom Agent Chat Request

```json
{
  "message": "What are the latest trends in AI research?",
  "sessionId": "session-custom-aurora-researcher-1731672000000-abc123",
  "agentId": "custom-aurora-researcher",
  "timestamp": "2025-11-15T10:35:00.000Z",
  "images": [] // optional
}
```

### 5. Custom Agent Chat Response

```json
{
  "response": "Based on recent research, the top AI trends include...",
  "citations": ["Source 1", "Source 2"] // optional custom fields
}
```

## Component Hierarchy

```
ChatInterface
├── Header Actions
│   ├── Bookmark Button → opens PinnedAgentsDrawer
│   └── New Chat Button
│
├── Message Feed
│   ├── User Messages
│   ├── Assistant Messages
│   ├── Loading Indicator
│   └── AgentForgeCard (when tool call received)
│       ├── Loading Animation (3 steps)
│       ├── Metadata Display
│       │   ├── Icon Badge
│       │   ├── Display Name
│       │   ├── Summary
│       │   ├── Tags
│       │   └── Status Badge
│       └── Action Buttons
│           ├── Use Now
│           ├── Pin (opens dialog)
│           └── Share
│
├── Hero Empty State
│   ├── Greeting Animation
│   ├── Agent Chips
│   │   ├── Regular agents
│   │   └── "+ Create new" chip
│   └── Prompt Cards
│
├── Composer
│   ├── Textarea
│   ├── Agent Dropdown
│   ├── Send Button
│   └── Image Attach Button (if enabled)
│
└── PinnedAgentsDrawer (modal)
    ├── Header (count + close)
    ├── Agent List (reorderable)
    │   └── Agent Cards
    │       ├── Icon + Name
    │       ├── Summary
    │       ├── Tags
    │       ├── User Note
    │       ├── "Start chat" Button
    │       └── Remove Button
    └── Empty State (if no agents)
```

## State Management

```typescript
// ChatInterface state
const [messages, setMessages] = useState<Message[]>([])
const [agentPackage, setAgentPackage] = useState<AgentPackagePayload | null>(null)
const [showPinnedDrawer, setShowPinnedDrawer] = useState(false)

// When tool call received:
if (data.toolCall?.name === "create_agent_package") {
  setAgentPackage(data.toolCall.payload)
  // AgentForgeCard renders automatically
}

// When user clicks "Use now":
handleUseAgentNow(agentId)
  → POST /api/agents/create
  → onAgentSelected(customAgent)
  → setAgentPackage(null)
  → Timeline marker added

// When user clicks "Pin":
handlePinAgent(package, note)
  → Save to localStorage["pinned-agents"]
  → setAgentPackage(null)
  → Confirmation message added

// When user clicks bookmark:
setShowPinnedDrawer(true)
  → PinnedAgentsDrawer opens
  → Reads from localStorage
  → Displays agents

// When user starts chat from drawer:
handleSelectPinnedAgent(agent)
  → POST /api/agents/create (if needed)
  → onAgentSelected(customAgent)
  → setShowPinnedDrawer(false)
```

---

**Last Updated**: 2025-11-15  
**For**: Multi-Agent Chat Interface - Agent Forge Feature

