# AgentForms — Form Infrastructure for AI Agents

## Positioning

AgentForms is form infrastructure for AI agents. Agents are the primary builders — they create, configure, and manage forms, documents, and workflows programmatically. Humans can interact when needed: inspecting forms, monitoring submissions, overriding config, or building manually for quick one-offs.

**What agents do:**
- "Create an intake form for a client onboarding"
- "Generate a quote document for this prospect"
- "Build a survey for our users"
- "Set up automated follow-up emails after form submission"

**What humans do when needed:**
- Inspect agent-built forms and submissions
- Override field config or action settings
- Build forms manually via the web UI for quick one-offs
- Monitor analytics and campaign performance

The entire form lifecycle is API-first. Every form is a JSON schema. Every action is a webhook hook. Every workflow is an LLM-generated pipeline. The human UI shares the same backend — no separate data paths.

## Architecture Overview

```
┌─────────────────────────────────────────────────────────┐
│  AI Agent (Claude, Codex, Hermes, Custom)               │
│                                                         │
│  "Create a client intake form with fields:              │
│   name, email, company, budget, timeline"               │
└──────────────────────┬──────────────────────────────────┘
                       │  /api/agent/build
                       ▼
┌─────────────────────────────────────────────────────────┐
│  AgentForms Relay (Flask + Gunicorn)                    │
│                                                         │
│  ┌─────────────┐  ┌─────────────┐  ┌────────────────┐  │
│  │ Workflow     │  │ Action      │  │ Form Logic     │  │
│  │ Builder (P2) │  │ Pipeline    │  │ Engine (P3)    │  │
│  │             │  │ (P1)        │  │                │  │
│  └──────┬──────┘  └──────┬──────┘  └────────┬───────┘  │
│         │                │                   │          │
│  ┌──────┴──────┐  ┌──────┴──────┐  ┌────────┴───────┐  │
│  │ LLM Client  │  │ Webhook     │  │ Validation     │  │
│  │ (Qwen 4B)   │  │ Dispatch    │  │ Conditions     │  │
│  └─────────────┘  │ Calculations│  │ Multi-step     │  │
│                   └─────────────┘  └────────────────┘  │
└──────────────────────┬──────────────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────────────┐
│  AgentForms Worker (Celery + Redis)                     │
│                                                         │
│  Async action execution: email delivery,                │
│  webhook dispatch, document generation                  │
└─────────────────────────────────────────────────────────┘
```

## Agent API Surface

### Phase 1 — Action Pipeline

Post-submission automation. When a form is submitted, configured actions execute:

| Action Type | Description |
|---|---|
| `webhook` | POST to any URL with submission data |
| `email` | Send formatted email via configured provider |
| `log` | Store in internal audit log |
| `redirect` | Redirect user to specified URL |
| `document` | Generate document (PDF, DOCX) from template |

Actions are ordered by `execution_order`, triggered by `trigger_event` (default: `submission`).

### Phase 2 — Workflow Builder

Agent tells the LLM what it needs. LLM returns a complete form schema:

```
POST /api/agent/build
{
  "prompt": "Create a contractor NDA with fields: party names, effective date, scope of work, confidentiality period, governing state",
  "form_type": "contract",
  "theme": { "primary": "#2563eb" }
}
```

Returns: complete `field_config` JSON + action suggestions.

### Phase 3 — Form Logic Engine

Server-side evaluation of form logic:

- **Validation** — email, phone, pattern, min/max, required
- **Conditional fields** — show/hide based on other field values (11 operators)
- **Calculated fields** — `{{price}} * {{quantity}}` formula engine
- **Multi-step forms** — step grouping with navigation

All logic is evaluable by headless agents — no client-side dependency.

### Phase 4 — Event Stream + SDK

- **SSE Event Stream** — real-time submission events for agent consumption
- **JS SDK** — client-side embed for human-facing forms

## API Reference

### Agent Build Endpoint

```
POST /api/agent/build
Authorization: Bearer <token>
```

**Request:**
```json
{
  "prompt": "string (required)",
  "form_type": "string (optional, default: 'form')",
  "theme": {
    "primary": "string (hex color)"
  }
}
```

**Response:**
```json
{
  "success": true,
  "site_id": 1,
  "fields": [...],
  "actions_suggested": [...],
  "embed_url": "https://agentforms.io/embed/abc123",
  "token": "abc123"
}
```

### Site CRUD

```
POST /api/sites              — Create site
GET  /api/sites              — List sites
GET  /api/sites/:id          — Get site
PUT  /api/sites/:id          — Update site
DELETE /api/sites/:id        — Delete site

POST /api/sites/:id/actions  — Create action
GET  /api/sites/:id/actions  — List actions
PUT  /api/actions/:id        — Update action
DELETE /api/actions/:id      — Delete action
```

### Form Submission

```
POST /api/submit?token=<token>
Content-Type: application/x-www-form-urlencoded
```

Returns `200 OK` on success, `422` with validation errors.

## Data Model

```
users
  └── sites
        ├── field_config (JSON)
        ├── actions
        │     ├── type
        │     ├── config (JSON)
        │     ├── trigger_event
        │     └── execution_order
        └── submissions
              └── data (JSON)
```

## Authentication

- **API Key** — `X-API-Key` header or `Bearer` token
- **Session** — SameSite+Secure cookies for human UI
- **CSRF** — Exempted for JSON API endpoints; required for HTML forms

## Deployment

- **Relay** — Flask + Gunicorn on `0.0.0.0:5060`
- **Worker** — Celery + Redis for async actions
- **Database** — SQLite (`relay.db`), Postgres migration planned
- **LLM** — Qwen3.5-4B via llama.cpp on port 8086 (configurable via `BUILDER_LLM_HOST`)
- **Docker** — `docker compose up -d`

## Phase Roadmap

| Phase | Status | Description |
|---|---|---|
| P1: Action Pipeline | ✅ Done | Webhook/email/log/redirect/document actions |
| P2: Workflow Builder | ✅ Done | LLM-generated forms from prompts |
| P3: Form Logic Engine | ✅ Done | Validation, conditions, calculations, multi-step |
| P4: SSE + JS SDK | ✅ Done | Real-time streaming build, EventSource SDK |
| P5: Document Generation | 🔜 Planned | PDF/DOCX from templates |
| P6: Postgres Migration | 🔜 Planned | Production-scale database |

## Testing

```bash
cd /home/vincent/projects/agentforms
python -m pytest tests/ -v
```
