# Agent Forge & Catalog - Product Requirements Document

## Overview

This PRD describes the Agent Forge feature that enables users to collaborate with Morgan (the Agent Architect) to create custom agents whose full prompts are delivered via secure tool calls, rendered with rich UI in chat, and managed in a local catalog.

## Goals

1. Enable users to mint custom agents through conversation with Morgan
2. Securely package agent prompts without exposing them in the UI
3. Provide an intuitive catalog for managing pinned agents
4. Allow immediate use or persistent storage of created agents
5. Set foundation for future voice/multimodal agent creation workflows

## User Flows

### Creating a Custom Agent

1. **Initiation**: User selects "Create new" chip in hero or asks Morgan to create an agent
2. **Collaboration**: Morgan runs interactive design workflow, asking questions
3. **Packaging**: Once finalized, Morgan emits a `create_agent_package` tool call
4. **Reveal**: UI displays Agent Forge Card with animated "forging" sequence
5. **Action**: User chooses to "Use now", "Pin for later", or "Share"

### Using a Created Agent

**Use Now Flow:**
1. Agent is registered with backend via `/api/agents/create`
2. System switches active agent to the new custom agent
3. Timeline marker confirms switch
4. User can immediately start chatting

**Pin Flow:**
1. User adds optional note about when to use the agent
2. Agent is saved to localStorage `pinned-agents` array
3. Confirmation message displayed
4. Agent appears in pinned catalog

### Managing Pinned Agents

1. User clicks bookmark icon in header
2. Drawer slides in from right showing all pinned agents
3. User can:
   - Reorder agents via drag handles
   - Start chat with any agent
   - Remove agents from list
   - View agent metadata and notes

## Technical Architecture

### Morgan Behavior Updates

**File**: `.fortura-core/agents/agent-architect.md`

**Changes**:
- Added activation instruction for agent packaging protocol
- Added core principle about secure packaging
- Added detailed workflow documentation after YAML block

**Tool Call Format**:
```json
{
  "type": "tool_call",
  "name": "create_agent_package",
  "payload": {
    "agentId": "custom-{uuid}",
    "displayName": "Agent Name",
    "summary": "Brief description",
    "tags": ["tag1", "tag2"],
    "systemPrompt": "# Web Agent Bundle Instructions...",
    "hints": {
      "recommendedIcon": "🔮",
      "whenToUse": "Use when..."
    }
  }
}
```

### API Routes

**`/api/agents/create` (NEW)**:
- Accepts agent package from client
- Registers with n8n via `CUSTOM_AGENT_REGISTRATION_WEBHOOK`
- Fallback: stores locally if webhook not configured
- Returns success and optional `promptToken`

**`/api/chat` (UPDATED)**:
- Detects `create_agent_package` tool calls in responses
- Forwards tool calls directly to client in `toolCall` field
- Routes custom agents (ID starting with `custom-`) to `CUSTOM_AGENT_WEBHOOK`

**`/api/flags` (UPDATED)**:
- Now exposes `VOICE_INPUT_ENABLED` flag (default: false)

### Type Definitions

**File**: `src/lib/types.ts`

**New Types**:
- `ToolCall`: Generic tool call structure
- `AgentPackagePayload`: Agent package from Morgan
- `PinnedAgent`: Stored pinned agent with metadata
- `CustomAgent`: Runtime custom agent extending Agent

**Updated Types**:
- `ChatResponse`: Added `toolCall?` field

### React Components

**`AgentForgeCard` (NEW)**:
- Location: `src/components/agent-forge-card.tsx`
- Shows animated "forging" sequence initially
- Reveals metadata card with CTAs after loading
- Handles "Use now", "Pin", and "Share" actions
- Displays status badge and agent info

**`PinnedAgentsDrawer` (NEW)**:
- Location: `src/components/pinned-agents-drawer.tsx`
- Slide-in drawer from right side
- Reorderable list with drag handles (Framer Motion Reorder)
- Start chat, view details, or remove agents
- Persists order to localStorage

**`ChatInterface` (UPDATED)**:
- Added bookmark button to header for pinned drawer
- Added "Create new" chip to hero section
- Detects tool calls in `sendMessage`
- Renders `AgentForgeCard` when agent package received
- Handles agent registration and switching
- Integrates `PinnedAgentsDrawer`

### Storage

**LocalStorage Keys**:
- `pinned-agents`: Array of `PinnedAgent` objects
- `chat-session-{agentId}`: Session ID per agent
- `chat-messages-{agentId}`: Message history per agent

**Data Retention**:
- All storage is client-side only (for now)
- System prompts stored unencrypted in localStorage
- Future: Add server-side sync and encryption

### Feature Flags

**File**: `src/lib/flags.ts`

**New Flag**:
- `VOICE_INPUT_ENABLED`: boolean (default: false)
- Environment variable: `VOICE_INPUT_ENABLED`
- Future use for voice/multimodal capture

## UI/UX Design

### Agent Forge Card

**Loading State**:
- Rotating package icon
- Glass morphism styling
- Three animated progress steps:
  1. "Gathering intent"
  2. "Synthesizing persona"
  3. "Sealing prompt"
- Shimmer background effect

**Revealed State**:
- Large emoji icon badge
- Display name in Playfair font
- Summary text and tags
- "Prompt secured" status badge
- Three action buttons:
  - "Use now" (gradient orange/terracotta)
  - "Pin for later" (outline style)
  - Share (icon button)
- Optional "When to use" hint

### Pinned Agents Drawer

**Layout**:
- Fixed right side, full height
- Glass morphism with dark gradient
- Header with count and close button
- Scrollable card list

**Agent Cards**:
- Emoji icon + name + summary
- Tags display
- Optional user note
- Drag handle for reordering
- "Start chat" button
- Remove button (trash icon)

**Empty State**:
- Centered icon and message
- Guidance to create agents with Morgan

### Hero Section Updates

**New Chip**:
- "+ Create new" button
- Orange gradient styling
- Populates input with creation prompt
- Positioned after agent chips

### Header Buttons

**Bookmark Button**:
- Always visible in top-right
- Opens pinned agents drawer
- Icon: Bookmark glyph

## Environment Variables

### Development (`.env.local`)

```env
# Existing
IMAGE_UPLOADS_ENABLED=true
DIFF_TOOL_ENABLED=true
AGENT_1_URL=https://n8n.example.com/webhook/agent-1
AGENT_1_NAME=Agent Name
AGENT_1_DESCRIPTION=Agent description

# New
VOICE_INPUT_ENABLED=false
CUSTOM_AGENT_WEBHOOK=https://n8n.example.com/webhook/custom-agent
CUSTOM_AGENT_REGISTRATION_WEBHOOK=https://n8n.example.com/webhook/register-agent
```

### Production (`wrangler.jsonc`)

```jsonc
{
  "vars": {
    "IMAGE_UPLOADS_ENABLED": "true",
    "DIFF_TOOL_ENABLED": "true",
    "VOICE_INPUT_ENABLED": "false",
    "CUSTOM_AGENT_WEBHOOK": "https://n8n.production.com/webhook/custom",
    "CUSTOM_AGENT_REGISTRATION_WEBHOOK": "https://n8n.production.com/webhook/register"
  }
}
```

## n8n Integration

### Custom Agent Webhook

**Endpoint**: `CUSTOM_AGENT_WEBHOOK`

**Purpose**: Handle messages for custom agents

**Request**:
```json
{
  "message": "User message",
  "sessionId": "session-custom-xyz-...",
  "agentId": "custom-xyz",
  "timestamp": "2025-11-15T...",
  "images": ["base64..."] // optional
}
```

**Response**: Standard n8n response format (streaming or JSON)

### Registration Webhook

**Endpoint**: `CUSTOM_AGENT_REGISTRATION_WEBHOOK`

**Purpose**: Store custom agent prompts for later retrieval

**Request**:
```json
{
  "agentId": "custom-xyz",
  "systemPrompt": "# Web Agent Bundle...",
  "metadata": {
    "displayName": "Aurora Researcher",
    "summary": "...",
    "tags": ["research"],
    "recommendedIcon": "🌌",
    "whenToUse": "...",
    "createdAt": "2025-11-15T..."
  }
}
```

**Response**:
```json
{
  "success": true,
  "promptToken": "optional-token-for-retrieval"
}
```

## Future Enhancements

### Voice & Multimodal (Phase 2)

**Goal**: Allow users to create agents using voice and images

**Components**:
1. Microphone button in composer
2. Web Speech API or MediaRecorder integration
3. Client-side transcription (optional)
4. Image annotation overlay for screenshots
5. Agent Forge Card shows captured media in "Research materials" section

**Flag**: `VOICE_INPUT_ENABLED=true`

### Server-Side Sync (Phase 3)

**Goal**: Sync pinned agents across devices

**Approach**:
- Add user authentication
- Store pinned agents in Cloudflare KV or D1
- Encrypt system prompts server-side
- Sync on login/agent selection

### Sharing & Marketplace (Phase 4)

**Goal**: Share custom agents with others

**Features**:
- Generate shareable links with prompt tokens
- Public agent marketplace
- Import from link or ID
- Ratings and reviews

## Success Metrics

1. **Adoption**:
   - % of users who create at least one custom agent
   - Average custom agents per user
   - % of sessions using custom agents

2. **Engagement**:
   - Time spent creating agents
   - Messages per custom agent session
   - Pin rate (pinned vs. used-once)

3. **Quality**:
   - Agent creation completion rate
   - User satisfaction with created agents
   - Repeat usage of pinned agents

## Testing Checklist

- [ ] Morgan emits tool calls correctly
- [ ] Agent Forge Card animates and displays properly
- [ ] "Use now" registers agent and switches context
- [ ] "Pin" saves to localStorage with note
- [ ] "Share" copies agent info to clipboard
- [ ] Pinned drawer opens/closes smoothly
- [ ] Reordering saves to localStorage
- [ ] Remove button deletes from list
- [ ] Start chat loads custom agent correctly
- [ ] Custom agent messages route properly
- [ ] Morgan webhook receives tool call format
- [ ] Registration webhook stores prompts
- [ ] Feature flag disables voice input UI
- [ ] Mobile responsive behavior
- [ ] Dark mode styling
- [ ] Linter checks pass

## Known Limitations

1. **Security**: System prompts stored unencrypted in localStorage
2. **Sync**: No cross-device synchronization
3. **Validation**: No prompt validation before registration
4. **Limits**: No cap on number of pinned agents
5. **Expiration**: No automatic cleanup of old custom agents
6. **Voice**: Implementation deferred to Phase 2

## Deployment Notes

1. Update Morgan's prompt file in production n8n workflows
2. Configure `CUSTOM_AGENT_WEBHOOK` and `CUSTOM_AGENT_REGISTRATION_WEBHOOK`
3. Set `VOICE_INPUT_ENABLED=false` initially
4. Monitor custom agent creation rate
5. Test tool call parsing in production environment
6. Add observability for agent registration failures

## Documentation Updates Needed

- [ ] Update CLAUDE.md with agent forge workflow
- [ ] Add Agent Forge usage guide
- [ ] Document n8n webhook setup
- [ ] Update README with new features
- [ ] Create video walkthrough

---

**Status**: Implementation Complete (except voice/multimodal Phase 2)  
**Version**: 1.0  
**Date**: 2025-11-15  
**Author**: AI Agent Development Team

