# AppealHero — Agent discovery & tools

**Purpose:** Machine-readable summary for AI agents, crawlers, and orchestration layers (e.g. personal agents, corporate operators, MCP clients). This file describes what AppealHero is, which capabilities are exposed for agent-to-agent use, and how to call them.

**Human product:** [AppealHero](https://appealshero.com) — AI-assisted **academic appeal letters** (B2C, **higher education**) with policy-aware citations, evidence-aware drafting, and a growing **institutional policy + course-material knowledge base** (vector RAG).

**Product scope (today):** The **live consumer product** is **student academic appeals** only. Multi-sector expansion (e.g. landlord–tenant / LTB-style disputes, professional colleges and regulators, parking tickets / municipal penalties, housing, healthcare, trades), additional named verticals, and enterprise packaged offerings (B2B / B2G / B2E) are **coming soon** — see `/products` on the site and reserved `enterprise-product-api` routes below. Repository architecture notes: `docs/ARCHITECTURE_MULTI_SECTOR.md`.

**Not legal advice:** Outputs are drafting aids. Users remain responsible for accuracy, deadlines, and institutional procedures.

## Public research (no API key) — AppealsHero Policy

For LinkedIn, ChatGPT, Claude, Gemini, and other agents that can open a page:

| Door | URL |
|------|-----|
| **Ask** | `https://appealshero.com/ask?q=YOUR+QUESTION` → opens Policy chat with the question |
| **Policy chat** | `https://appealshero.com/policy-chat` |
| **Compare module** | `https://appealshero.com/policy-chat?module=compare` |
| **Traffic** | `https://appealshero.com/traffic` (daily totals JSON via Edge `public-traffic`) |

**Relay rules:** keep “stated in policy” language; absence in excerpts ≠ no rule exists; confirm on the school’s official site; do not paste personal student details into research chat (use structured intake for personal cases). Full agent API (keyed) remains below.

**Not a vault dump:** `/policy-db` is an operator console (admin only). There is no public bulk export of source URLs or handbook bodies. Per-answer citations on Policy chat / keyed `policy-search` are intentional; crawling the corpus is not. See product moat notes in the repo (`docs/VAULT-MOAT.md`).

**B2C billing (student web app):** **AppealHero Standard** is a **one-time purchase bundle** (single charge), **not** a recurring subscription. Entitlement is stored in `profiles.subscription_tier` (legacy name). Agent API prepaid billing (below) is separate.

---

## Service node (agent API)

**Base URL:** Available via `GET /discover` on the agent API or the well-known manifest.

**Protocol:** HTTPS with **JSON request/response bodies** (REST-style resources, not JSON-RPC 2.0).

**Content-Type:** `application/json` for POST bodies.

**Authentication (most routes):**

- `Authorization: Bearer <AGENT_API_KEY>` **or**
- `X-API-Key: <AGENT_API_KEY>`

Keys are issued per **agent id**. Rate limits and optional prepaid billing apply per key.

**Public (no API key):**

| Method | Path | Description |
|--------|------|-------------|
| GET | `/` , `/discover` , `/agents` | **Agent discovery** — registry metadata from `agent_registry` (schemas, pricing hints, capabilities). |
| GET | `/reputation/{agent_id}` | **Reputation** snapshot for a registered agent. |

**Authenticated:**

| Method | Path | Description |
|--------|------|-------------|
| POST | `/agents/{agent_id}` | Invoke a single agent (see agent ids below). |
| POST | `/negotiate-pricing` or `/agents/negotiate-pricing` | Volume / tier pricing negotiation. |
| POST | `/teams/{team_id}` | Run a **predefined team** (`policy-research`, `appeal-drafting`, `quality-assurance`, `full-pipeline`). |
| POST | `/teams/compose` | Custom ordered agent pipeline (`agents: string[]`, optional `workflow: "sequential"`). |
| POST | `/suite/generate-appeal` | **Full appeal suite** (research → strategy → draft → QA → validation; optional adversary pass). |
| POST | `/policy-search` | Vector **policy search** (`match_policies` + embeddings). |
| POST | `/document-analysis` | Document / image analysis (Gemini). |
| POST | `/citation-validator` | Validate citations in a draft letter against optional policy context. |

**Account key management (use Supabase user access token in `Authorization: Bearer`, not an agent API key):**

| Method | Path | Description |
|--------|------|-------------|
| GET | `/keys/list` | List keys you issued (metadata only; no raw `ahk_` secret). |
| POST | `/keys/deactivate` | Body `{ "keyId": "<uuid>" }` — sets the key inactive so you can issue another under `AGENT_MAX_KEYS_PER_USER`. |

**Optional response format:** Header `X-AH-Compact: 1` returns a compact text encoding of success/error (see Edge Function `encodeResponse`).

**Pricing headers:** Successful metered calls may include `X-Price-Per-Request`. Prepaid balance may be required when `AGENT_PREPAYMENT_REQUIRED=true`; the discovery JSON includes `billing.prepaidBalanceField` (USD on `agent_api_keys.metadata`) and **`billing.topup_options`** (machine-readable card / BTCPay / invoice / legacy ETH routes). HTTP **402** responses include `topup_base_url`, `create_crypto_invoice_url`, and links to **`/.well-known/appealhero-agent.json`** and **`/AGENTS.md`** when the project sets `ALLOWED_ORIGIN`.

---

## Callable agents (`POST /agents/{agent_id}`)

| `agent_id` | Role (for orchestrators) |
|------------|-------------------------|
| `scout` | Region → seed university lists. |
| `hunter` | University + query → candidate policy URLs / descriptions. |
| `librarian` | Normalize / verify document metadata for a university. |
| `vector_keeper` | **Embedding policy retrieval** (same RPC family as `policy-search`). |
| `strategist` | Case + policies + evidence → strategy / procedural angles (JSON). |
| `scribe` | Strategy + case → **draft appeal letter** (JSON). |
| `adversary` | Stress-test a draft for weaknesses. |
| `auditor` | Check draft citations against supplied policy payloads. |
| `citation_validator` | Citation scoring and repair suggestions. |
| `lens` | Vision/document extraction (alias of document analysis path). |
| `curator` | Organize/categorize document sets. |
| `morph` | Styling / theme JSON from intent (ancillary). |
| `qa_architect` | Synthetic test scenarios for QA. |
| `qa_analyst` | Letter vs ground truth. |
| `qa_inspector` | Multi-axis QA scorecard for a letter. |
| `contradiction_detector` | Policy contradiction scan. |
| `relevance_validator` | Policy–case relevance scoring. |

**Legacy agent ids** used only on dedicated legacy routes: `policy-search`, `document-analysis`, `citation-validator` (hyphenated) — prefer `/agents/vector_keeper`, `/agents/lens`, `/agents/citation_validator` for new integrations.

---

## Logical “tools” for routing (natural-language → HTTP)

These names are **orchestration-friendly aliases** for the HTTP surface above.

| Tool label | Use when the user… | Primary endpoints |
|------------|--------------------|-------------------|
| **Appeal Drafter** | Wants a structured appeal letter and strategy. | `POST /suite/generate-appeal`, or `POST /agents/strategist` → `POST /agents/scribe`, or team `appeal-drafting` / `full-pipeline`. |
| **Policy & boundary context** | Needs institutional rules, syllabus alignment, or retrieval-grounded excerpts. | `POST /agents/vector_keeper`, `POST /policy-search`, team `policy-research`. |
| **Citation & policy alignment** | Must verify references, spot weak citations, or align text to policy text. | `POST /agents/citation_validator`, `POST /agents/auditor`, `POST /citation-validator`, team `quality-assurance`. |

---

## Interoperability charter (core directive)

AppealHero treats **agent-to-agent and human-to-agent interoperability** as a first-class product requirement:

1. **Stable protocols** — REST + JSON on the agent API; `AgentMessage` / `AgentResponse` in the in-repo `agents/` package (`agents/types.ts`). Prefer **discovery** (`GET /discover`, this file’s JSON index) over hard-coded URLs.
2. **Composable flows** — Use **`POST /teams/{team_id}`**, **`POST /teams/compose`**, or **`POST /suite/generate-appeal`** for multi-step work instead of chaining opaque one-off scripts when the API suffices.
3. **One map of capabilities** — In-repo orchestration (`AgentOrchestrator`), MCP tools, and HTTP routes should stay **conceptually aligned** (same agent ids / roles where they overlap).
4. **Governed automation** — Repo-writing automation (e.g. autonomous coder) uses **sandbox policy + preview branches**; it does not replace the HTTP contract for external integrators.

**In-repo version token:** `AGENT_INTEROP_VERSION` in `agents/interop.ts` (bump when cross-agent contracts change).

---

## Global Assistant — operator meta-agent and packaging (web)

On **Mission Control, Corporation, Admin, and Affiliate**, Global Assistant is the operator's meta-agent: it coordinates the student appeal loop (University of Toronto first, then other vault-ready Ontario campuses) and can show an operator brief. On student pages it stays an appeal helper.

The consumer SPA’s **Global Assistant** also exposes chat tools (same conceptual map as this file) for **institutional buyers and power users**:

| Tool | Purpose |
|------|---------|
| `list_existing_capabilities` | Merged catalog of A2A services + **Enterprise Alpha** offerings; optional NL `query` ranking; optional `includePlaybook` for a short guide. |
| `create_custom_product` | Plain-language → policy corpus snippets + capability matches + **USD quote** + composed workflow. |
| `update_product_quote` / `accept_product_quote` | Tune delivery / human involvement; **accept** with `payment_method=stripe\|lemon\|card` creates a real Lemon Squeezy hosted checkout via `create-dynamic-bundle-checkout` and surfaces a **Pay-now** link. Lemon webhook fulfills (`add_user_credits` for `kind=credits`, ledger row in `dynamic_bundle_purchases` always). Falls back to a simulated browser provision if the checkout call fails. |

**Implementation:** `lib/globalAssistantDynamicProducts.ts`, `lib/dynamicProductPipeline.ts`, unified index `lib/capabilityRegistry.ts`, real-checkout client `services/dynamicBundleCheckoutClient.ts`, Edge function `supabase/functions/create-dynamic-bundle-checkout/`, fulfillment policy `supabase/functions/_shared/dynamicBundleFulfillment.ts`. **Operator notes:** `docs/DYNAMIC_PACKAGE_SLICE.md`.

**Execution:** Prefer this HTTP **agent-api** (`POST /teams/compose`, suite routes above) for purchased / automated runs—not ad-hoc scripts.

---

## Machine-readable index (JSON)

```json
{
  "name": "AppealHero",
  "version": "1.0",
  "canonical_human_url": "https://appealshero.com",
  "agent_api_base_url": "https://appealshero.com/api/agent",
  "enterprise_product_api_base_url_template": "https://appealshero.com/api/enterprise",
  "discovery_get": ["/", "/discover", "/agents"],
  "reputation_get": "/reputation/{agent_id}",
  "auth": ["Authorization: Bearer <key>", "X-API-Key: <key>"],
  "agents": [
    "scout", "hunter", "librarian", "strategist", "scribe", "adversary",
    "auditor", "morph", "lens", "vector_keeper", "curator",
    "qa_architect", "qa_analyst", "qa_inspector",
    "contradiction_detector", "relevance_validator", "citation_validator"
  ],
  "teams": ["policy-research", "appeal-drafting", "quality-assurance", "full-pipeline"],
  "composite_endpoints": [
    "POST /teams/compose",
    "POST /suite/generate-appeal"
  ],
  "policy_verticals": ["academic_appeals", "institutional_policies", "course_materials"],
  "mcp_stdio": {
    "command": "npm run mcp:appealhero",
    "env": ["APPEALHERO_AGENT_API_BASE", "APPEALHERO_AGENT_API_KEY"],
    "doc": "docs/MCP-APPEALHERO.md"
  },
  "well_known": "https://appealshero.com/.well-known/appealhero-agent.json",
  "llms_txt": "https://appealshero.com/llms.txt",
  "llms_full_txt": "https://appealshero.com/llms-full.txt",
  "marketing_static_pages": [
    "https://appealshero.com/pricing",
    "https://appealshero.com/how-it-works",
    "https://appealshero.com/faq",
    "https://appealshero.com/guides",
    "https://appealshero.com/tos",
    "https://appealshero.com/privacy"
  ],
  "openapi_examples": "https://appealshero.com/openapi/agent-api-v1.json",
  "live_billing": "GET {agent_api}/discover → billing.topupBaseUrl, billing.createCryptoInvoiceUrl, billing.topup_options",
  "agent_interop": {
    "version": 1,
    "in_repo_module": "agents/interop.ts",
    "principles_summary": "dispatch-only orchestration, shared AgentMessage types, discovery-aligned HTTP/MCP"
  },
  "notes": [
    "API is REST + JSON, not JSON-RPC 2.0.",
    "Keys are per agent_id; use GET /discover for live schemas and pricing metadata.",
    "MCP stdio server available — see docs/MCP-APPEALHERO.md.",
    "Interoperability charter: see section Interoperability charter (core directive) in this file."
  ]
}
```

---

## Enterprise product API (B2B / B2G / B2E — reserved routes)

**Base URL:** Available via the well-known manifest or `GET /discover`.

**Purpose:** Stable B2B / B2G / B2E HTTP surface for institutional tools. **Today:** `GET /` discovery on the Edge function is public; POST slugs are used by the signed-in **Enterprise Alpha** UI at **`/offerings`** (credits debited via `use_service` on successful runs). **B2C** remains the live student product (`/intake`, `/pricing`).

**Public (no API key):**

| Method | Path | Description |
|--------|------|-------------|
| GET | `/` (function root) or `GET ?endpoint=` omitted | **Discovery** — lists slugs, pricing hints, and availability metadata. |

**POST slugs (institutional tools — authenticate per function contract):**

| Slug | Tier | Intent |
|------|------|--------|
| `b2g-harmonization` | B2G | Policy harmonization vs peers / standards |
| `b2b-litigation-risk` | B2B | Litigation-oriented policy risk scan |
| `b2b-benchmark` | B2B | Cohort **rankings** + policy lens scores: live `policy_chunks` counts from Supabase, heuristic integrity/appeal/fairness language signals, composite ordering; response includes `rankingsView` for the `/offerings` dashboard (graduation / appeal success rates remain `not_linked` until external feeds are integrated) |
| `b2e-draft-appeal` | B2E | Enterprise-packaged appeal drafting |
| `b2e-training-scenario` | B2E | Training scenarios from policy text |

**Routing note:** Call `POST .../enterprise-product-api/<slug>` if your gateway forwards path suffixes; otherwise `POST .../enterprise-product-api?endpoint=<slug>`.

---

## Billing & Payment (A2A agents paying you)

**Prepaid balance model.** Each API key holds a `prepaid_balance_usd` value. Calls deduct from it at the quoted per-request price. If balance is insufficient and `AGENT_PREPAYMENT_REQUIRED=true` the call returns HTTP 402.

**Self-serve key issuance:** `POST /keys/issue` on the agent API with a valid user bearer token (on-site 1-click onboarding uses this path).

**Key management (same user session as issue):** `GET /keys/list` returns your keys (no raw secret). `POST /keys/deactivate` with `{ "keyId": "<uuid>" }` sets `is_active=false` so you can free a slot when you hit `AGENT_MAX_KEYS_PER_USER`.

**Starter credits:** newly issued keys can receive starter prepaid credit (`AGENT_STARTER_CREDITS_USD`, production default recommended `$0.00`) in `agent_api_keys.metadata.prepaid_balance_usd`. Starter grants are first-key-only per issuing user.

**Top-up endpoints:** Base URL is `billing.topupBaseUrl` on **`GET /discover`** (never hard-code a Supabase project host). Same object exposes **`billing.createCryptoInvoiceUrl`**, **`billing.wellKnownAgentManifest`**, and **`billing.topup_options`**.

| Route | Method | Purpose |
|-------|--------|---------|
| `/checkout/stripe` | POST | Hosted card top-up → `{ url }` (Stripe Checkout when configured) |
| `/checkout/crypto` | POST | **Preferred:** With `Authorization: Bearer <Supabase user JWT>` and BTCPay configured → `{ checkout_url, invoice_id }`. **Legacy:** without BTCPay → ETH wallet + amount; then POST `/crypto` |
| `/stripe` | POST | Webhook for hosted card top-ups |
| `/lemon` | POST | Webhook for Lemon-based agent top-ups (custom_data) |
| `/crypto` | POST | Confirm on-chain ETH tx: `{ key_id, amount_usd, tx_hash }` (owner JWT, operator secret, or trusted webhook) |
| `/balance?key_id=` | GET | Prepaid balance and recent top-ups (owner JWT or operator secret) |

**Direct Edge invoice (orchestrator-friendly):** `POST {createCryptoInvoiceUrl}` with the **key owner’s** user JWT and body `{ "purpose": "agent_topup", "agent_key_id": "<uuid>", "amount_usd": 25 }` — same BTCPay settlement as `/checkout/crypto`.

**Payment methods accepted:**
- **Fiat (card):** `POST …/agent-topup/checkout/stripe` when Stripe is configured on the project.
- **Crypto (BTCPay):** Bitcoin + Lightning via hosted checkout; prepaid credits when **`btcpay-webhook`** marks the invoice paid (`payment_kind: agent_credit` on `crypto_payments`).
- **Crypto (ETH, legacy):** If BTCPay env is not set, `POST /checkout/crypto` returns static wallet instructions; confirm via `POST /crypto`.
- **Lemon / human site:** B2C bundles on the main site; agent prepaid remains on **`agent-topup`** routes above.
- **Invoice / promo:** Operator credit via `POST /promo` with `X-Operator-Secret`.

**Negotiating volume pricing:** `POST /agents/negotiate-pricing` with `{ agentId, expectedVolume }` → returns a contract with discounted per-request price.

---

## Related integration surfaces

| Surface | Status | Notes |
|---------|--------|--------|
| **MCP server (stdio)** | **In repo** | Run `npm run mcp:appealhero` with `APPEALHERO_AGENT_API_BASE` (+ optional `APPEALHERO_AGENT_API_KEY`). Tools: `appealhero_discover`, `appealhero_reputation`, `appealhero_invoke_agent`, `appealhero_policy_search`, `appealhero_generate_appeal_suite`. See `docs/MCP-APPEALHERO.md`. |
| **Well-known pointer** | **Deployed with site** | After build: `https://appealshero.com/.well-known/appealhero-agent.json` links to this spec and MCP command. |
| **OpenAPI examples** | **Deployed with site** | `https://appealshero.com/openapi/agent-api-v1.json` contains request/response examples for discovery, key issuance, and core agent calls. |
| **OpenClaw / ClawHub skill** | Packaging TBD | Map HTTP tools above into a skill manifest; discovery URL can point here. |
| **AP2-style commerce** | Live | API keys + per-request pricing + card + **BTCPay (BTC/LN)** + legacy ETH top-up + optional mandate enforcement (`AGENT_PREPAYMENT_REQUIRED`). |
| **Affiliate Student Helper — manual thread draft** | **Supabase Edge** | `POST /functions/v1/affiliate-student-helper-manual-draft` with `Authorization: Bearer <Supabase user JWT>` and `apikey` (same pattern as other `affiliate-*` functions). JSON body: `{ "subreddit": "uoft", "post_title": "…", "post_body": "…" }` (`post_body` optional). **Active affiliate only** — generates a paste-ready Reddit reply for threads **not** in `outreach_pending` (policy RAG + scope gates + QA pass). Consumer UI: `/affiliate` → Student Helper → **Manual thread draft**. |

---

## Contact & changes

- Prefer **GET** discovery on the agent API for the freshest `agent_registry` rows.
- For humans: product and support links live on the main site (`canonical_human_url`).

*Last updated: 2026-04-24 (affiliate Student Helper: `affiliate-student-helper-manual-draft` Edge function documented).*
