# AYHire API Documentation

## Base URL

```
http://localhost:3000/api
```

---

## Endpoints

### POST /api/analyze

Analyze a single GitHub user. Scrapes their profile, scores them with Claude, generates embeddings.

A saved analysis from the last 30 days is free. Without a key this is the free profile check behind /engineer: a couple of new analyses a day per visitor, from a small shared daily allowance; use a key for more.

**Request:**
```json
{
  "username": "sindresorhus"
}
```

**Response:**
```json
{
  "candidate": {
    "id": "uuid",
    "github_username": "sindresorhus",
    "name": "Sindre Sorhus",
    "scores": {
      "technical_depth": 10,
      "shipping_velocity": 9,
      "communication": 9,
      "gem_score": 2
    },
    "summary": "Prolific open-source maintainer...",
    "top_skills": ["TypeScript", "JavaScript", "Swift", "CLI tools"],
    "red_flags": [],
    "outside_work": [{ "repo": "xojs/xo", "stars": 7800, "commits": 120, "pull_requests": 4 }],
    "version": 2
  }
}
```

---

### POST /api/bulk-analyze

Analyze up to 25 GitHub users, best total (out of 40) first. Saved analyses from the last 30 days are free; up to 4 new analyses run per request and the rest come back in `pending` (send them again). New analyses count toward the hourly limit; when it is spent the rest come back in `limited`.

**Request:**
```json
{
  "usernames": ["shadcn", "leerob", "rauchg"]
}
```

**Response:**
```json
{
  "analyzed": [
    { "github_username": "shadcn", "total": 41.5, "scores": { "technical_depth": 8.5 }, "summary": "...", "top_skills": ["TypeScript"], "red_flags": [], "cached": true }
  ],
  "pending": [],
  "limited": [],
  "limit_resets_at": null,
  "limit_reason": null,
  "failed": [],
  "counts": { "asked": 3, "saved": 1, "new": 2, "pending": 0, "limited": 0, "failed": 0 }
}
```

---

### POST /api/search

Semantic search over analyzed candidates using RAG (pgvector embeddings).

**Request:**
```json
{
  "query": "TypeScript developer who builds with Supabase and ships weekly",
  "limit": 10
}
```

**Response:**
```json
{
  "candidates": [
    {
      "id": "uuid",
      "github_username": "example",
      "name": "Dev Name",
      "scores": { ... },
      "raw_data": { "summary": "...", "top_skills": [...] },
      "search_relevance": 0.87
    }
  ],
  "query": "TypeScript developer who builds with Supabase and ships weekly"
}
```

---

### GET /api/candidates

List all analyzed candidates, paginated. Requires an API key or a session. Contact data (email) is not included.

**Query params:**
- `limit` (default: 50, max: 100)
- `offset` (default: 0)

**Response:**
```json
{
  "candidates": [...],
  "total": 142
}
```

---

### GET /api/candidates/:id

Get a candidate profile with repos. Requires an API key or a session. Contact data (email) is not included.

**Response:**
```json
{
  "candidate": {
    "id": "uuid",
    "github_username": "sindresorhus",
    "name": "Sindre Sorhus",
    "bio": "Full-Time Open-Sourcerer...",
    "location": null,
    "avatar_url": "https://...",
    "scores": { ... },
    "raw_data": { "summary": "...", "top_skills": [...], "red_flags": [...] },
    "analyzed_at": "2026-05-09T..."
  },
  "repos": [
    {
      "repo_name": "awesome",
      "language": null,
      "stars": 464513,
      "forks": 32000,
      "analysis": { "topics": [...], "url": "https://github.com/..." }
    }
  ]
}
```

---

## Roles (open positions you source for)

Agents use the MCP tools `list_roles`, `create_role`, `find_people_for_role`, `score_role_person`, `get_role`, `decide` and `get_shortlist` (and `get_search_plan`, `set_search_plan`, `next_round` for rounds that learn), and decide themselves who is worth scoring. All routes need an API key or a session.

### GET /api/roles
Your roles, newest first, with counts of picks, set aside, not looked at yet and shortlisted.

### POST /api/roles
Create a role: `{ "title": "...", "brief": "...", "search": { "mode": "repos", "query": "agent framework", "language": "Python" } }`.

### GET /api/roles/:id · PATCH /api/roles/:id · DELETE /api/roles/:id
The role and everyone in it, ranked with AyHire's call (picks, then set aside, then not looked at yet). PATCH changes the title, brief or search.

### POST /api/roles/:id/run
The whole run in one call: find the people behind matching repos, save them, then score the top people not looked at yet. Body: `{ "score_top": 5 }` (0-10). Saved analyses are free; new ones count toward the hourly limits.

### POST /api/roles/:id/search
Only the first step: find and save people. Returns `{ found, added, total, next }` (`next` = who to score next).

### POST /api/roles/:id/people/:username/score
Score one person in the role: analysis (free when saved) and an availability check. Returns the person with their call, and `limited` when an hourly cap stopped part of the work.

### PATCH /api/roles/:id/people/:username
Save your decision (`shortlisted`, `not_now`, `none`), notes, watch or contacted date. With `not_now` (or on someone already Not now), `reasons` says why: `too_junior`, `wrong_stack`, `wrong_location`, `not_open_to_work`, `other` (with `feedback_note`, up to 300 characters); `more_like_this` says the opposite. Reasons are feedback for the role's next round, never the decision itself; a shortlist counts as liking someone, and `none` removes the feedback.

### GET /api/roles/:id/plan · PUT /api/roles/:id/plan · POST /api/roles/:id/plan
GET: the role's search plan, what you set on top of it (`controls`: required places, languages and words; preferred skills; seed repos; people with no location), the `version` and the last versions with what changed, wider searches (`alternatives`: suggested, approved or dismissed), feedback (counts by reason, and each person's reasons) and `next_round` (the page it reads and what feedback changes). PUT `{ "version": 2, "required": { "places": ["Berlin"], "languages": ["Go"], "terms": ["webrtc"] }, "preferred": ["rust"], "seeds": ["livekit/agents"], "location_unknown": "exclude", "approve": ["seed-1a2b3c4d"], "reject": [], "restore_version": 1 }` (all optional) saves a new version and returns `{ plan, changes }`; a `version` that is no longer current is refused. POST reads the plan again from the title and brief (one model call within your suggestion allowance, a fixed fallback without it) and returns `{ role, plan, changes }`.

### POST /api/roles/:id/rounds · GET /api/roles/:id/rounds
POST `{ "request_id": "…", "stage": "all" }` runs the role's next round: it reads on from the last round's page, keeps every required constraint (someone with no location is never a match for a place), applies what feedback changed and saves only people the role has not seen. The reply is the /search reply plus `round: { number, plan_version, page, changes, new_people, exhausted, words, left_out }`. `exhausted` means no more new people for this plan; nobody already seen is added to fill it. The same `request_id` again returns the same round; a second round while one runs gets 429. A required language needs evidence (a repo of theirs in it, or a search in it that found them). A round left after its `index` stage (no `live` call came) ends when the next round starts. A role that is mostly not code also looks on LinkedIn on the live stage (`linkedin`), as /search does. Wider searches are only suggested (GET /plan) and run once approved with PUT. GET returns `{ rounds, next }`.

### POST /api/roles/:id/imports
Import a list of people into the role: the content of a CSV or text file, at most 200 KB and 500 people. GitHub handles or github.com links, and LinkedIn `/in/` links if any; optional columns `github`, `linkedin`, `name`, `note` (a note becomes the reason they were added; other columns are ignored, and emails are never stored). Without a GitHub column, a bare word is read as a handle only in a .txt list or a one-column file; next to other columns only `@handle` and github.com links count. Returns a preview, with who will be added (`ready`, the first 100), and changes nothing in the role. A LinkedIn link gets a GitHub account only when exactly one GitHub profile itself links it; anything less certain is a row to check, never added or analyzed until someone resolves it. Names never identify anyone. The same file again returns the same open import (`reused: true`). Rows to check can be resolved before importing. The MCP tools are `import_people`, `list_imports`, `get_import`, `run_import`, `resolve_import_row` and `cancel_import`.

**Request:**
```json
{ "text": "github,linkedin,name,note\nada,,Ada,Wrote the parser\n,https://www.linkedin.com/in/someone/,Someone,", "filename": "people.csv" }
```

**Response:**
```json
{
  "import": { "id": "uuid", "role_id": "uuid", "status": "preview", "analyze": false, "resume_at": null },
  "counts": { "total": 2, "ready": 1, "review": 1, "in_role": 0, "invalid": 0, "duplicate": 0, "added": 0 },
  "expected": { "add": 1, "review": 1, "saved_analyses": 0, "new_analyses_at_most": 1, "analyses_left_this_hour": 20 },
  "problems": [{ "row_no": 2, "line": 3, "status": "review", "linkedin_url": "https://www.linkedin.com/in/someone/", "message": "No GitHub profile is known for this LinkedIn.", "evidence": {} }],
  "ready": [{ "row_no": 1, "line": 2, "status": "ready", "github_username": "ada", "label": "Ada", "note": "Wrote the parser" }],
  "reused": false,
  "words": "2 people: 1 ready, 1 to check."
}
```

### GET /api/roles/:id/imports
The role's last 5 imports with their progress: `{ imports: [{ import, counts, more, words }] }`.

### GET /api/imports/:id?rows=problems
The import, its counts, a sentence and its rows: `rows=problems` (default: rows to check and lines left out), `review` or `all`; `offset` and `limit` (up to 500); `rows_total` is how many rows the filter has.

### POST /api/imports/:id/run
`{ "confirm": true, "analyze": false }` on the first call; then `{}`. Each call does one bounded step: up to 25 people added, or up to 25 analyzed (`analyze: true`; saved analyses are free, at most 4 new ones per step, each within your hourly limit). People already in the role are left as they are. Call again while `more` is true; when `import.status` is `paused` (the hour's analyses are used up), after `import.resume_at`. `busy: true` means another step was running and this call did nothing. Analyses are charged to the person who confirmed the import, so only their calls run them: for anyone else `more` is false and `waiting_for_owner` is true. Returns `{ import, counts, more, busy?, waiting_for_owner?, words }`.

### POST /api/imports/:id/rows/:row
Say who a row to check is: `{ "github_username": "ada" }` (added on the next run step), `{ "action": "skip" }`, or `{ "action": "linkedin_list" }` (adds their LinkedIn to the role's LinkedIn list, without a GitHub account). Works in the preview too. Returns `{ row, import, counts, more, words }`; `more`: call run again.

### POST /api/imports/:id/cancel
Stops the import: rows not added yet are cancelled, people already added stay. Calling it again changes nothing.

### GET /api/imports/:id/export
Every row as CSV (`line, github, linkedin, name, status, message, analysis`). Cells a spreadsheet would run as a formula (starting with `=`, `+`, `-`, `@`, a tab or a carriage return) start with an apostrophe.

### POST /api/research/estimate · POST /api/research/jobs
Paid research jobs, for agents. `company_people`: who LinkedIn lists with a current role at a company, by title and place if given. Each person is what their LinkedIn says, not confirmed employment, and never a complete roster. Estimate first (free: live provider prices, nothing reserved): `{ "kind": "company_people", "input": { "company": "Acme", "job_title": "Engineer" }, "max_results": 25 }` returns the steps and `at_most_usd`. A company name goes in `company` (looked up, and taken only when exactly one LinkedIn company has that name); `company_id` takes only LinkedIn's numeric id, and a name there is refused before anything is sent. Then POST /api/research/jobs with the same body plus `request_id` (your own id, 8 to 64 letters, digits, - or _) and `max_cost_usd` (at most $0.50 by default). Starting needs a plan; within `max_cost_usd` the steps run without asking again. Each call runs about 40 seconds of steps; the same `request_id` again resumes the job, never pays twice, and a higher `max_cost_usd` raises its budget. Read `next.code`: `call_again`, `wait_until` (after `next.at`), `give_company_id` (pick from `results.candidates` and start a new job), `raise_budget` or `none`. `cost` keeps settled, in-flight and unknown apart: an unknown cost is not zero. AyHire never tops up the provider balance. The MCP tools are `estimate_research`, `start_research_job`, `get_research_job` and `cancel_research_job`.

### GET /api/research/jobs · GET /api/research/jobs/:id · POST /api/research/jobs/:id/cancel
GET: the workspace's last 10 jobs, or one job's status with `?request_id=`; by id, its state, steps, results so far, cost and next action. Both read only the database and never spend. Cancel stops new work, asks the provider to stop runs still going, and reports what was already spent.

### GET /api/watches
Everyone watched in your current workspace (`?workspace=` for another), with what each watch is for, the last check and the latest change.

### GET /api/watches/:username
One watch, or `{ "watch": null }`.

### PUT /api/watches/:username
Watch someone, or change what you hear about. Body (all optional): `{ "rules": ["open_to_work", "job_change", "says_looking", "new_work"], "paid_checks": false, "role_id": null }`. A new watch gets every rule. `role_id` is context for links, and they must already be in that role. Returns `{ watch, created }`.

### DELETE /api/watches/:username
Stop watching. Returns `{ deleted }`.

### GET /api/notifications · PUT /api/notifications
Your email choice for the current workspace (`?workspace=` for another): `{ "email": "off" | "instant" | "daily" }`. Instant sends at most one email an hour; daily at most one a day. Returns `{ workspace, email, address, configured }`.

### GET /api/integrations/webhooks · POST /api/integrations/webhooks
The workspace's webhooks (owners see the full address). POST `{ "url": "https://…", "events": ["watch.signal", "role.fits"], "description": "…" }` (owners; `events` defaults to both) returns `{ webhook, secret }`: the secret is shown only here.

### PATCH /api/integrations/webhooks/:id · DELETE /api/integrations/webhooks/:id
Change `url`, `events`, `description` or `active` (true also clears a pause); or delete it.

### POST /api/integrations/webhooks/:id/test · POST /api/integrations/webhooks/:id/rotate
Send a signed `ping` now and see the answer; or get a new secret.

### GET /api/integrations/webhooks/:id/deliveries · POST /api/integrations/webhooks/:id/deliveries/:delivery/resend
The webhook's last 50 deliveries (kept 30 days), newest first. Each has `id` (the `X-AyHire-Delivery` your receiver saw), `event_type`, `status` (`pending`, `sending`, `sent`, `failed` or `skipped`), `attempts`, `last_status`, `last_error`, `created_at`, `sent_at`, `next_attempt_at` (while it waits for a retry) and `can_resend`. Owners can send a delivery that went out, or failed, again: the same body and id, signed now, one try (10 a minute). It returns `{ ok, status, ms, error, delivery }`.

### Webhook requests
AyHire POSTs JSON with these headers:
- `X-AyHire-Event`: `watch.signal`, `role.fits` (someone you watch may fit another open role) or `ping` (a test). For `role.fits`, `data` is `{ event_id, person, role: { id, title, app_url }, fit: { relevance, main_area, reasons: [{ kind, text, evidence_url }] }, sentence, evidence }`.
- `X-AyHire-Delivery`: the delivery id, the same on every retry and on a Send again: ignore one you've seen. Delivery is at least once, so the same id can arrive twice.
- `X-AyHire-Signature`: `t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>" with your secret>`

Body: `{ id, type, version: 2, created_at, workspace: { id, name }, text, data }`. For `watch.signal`, `data` is `{ event_id, person, change, evidence, role }`.
Answer 2xx within 10 seconds. Failed deliveries are retried after 1, 2, 4, 8, 16 and 24 hours (at most 3 days); redirects aren't followed; a 410 pauses the webhook.

Check a request (Node):
```js
import { createHmac, timingSafeEqual } from "node:crypto";
function fromAyHire(secret, rawBody, header) {
  const p = Object.fromEntries(String(header).split(",").map((x) => x.split("=")));
  if (Math.abs(Date.now() / 1000 - Number(p.t)) > 300) return false;
  const want = createHmac("sha256", secret).update(`${p.t}.${rawBody}`).digest("hex");
  return !!p.v1 && p.v1.length === want.length && timingSafeEqual(Buffer.from(p.v1), Buffer.from(want));
}
```

### GET /api/activity?limit=20&kinds=watch_signal
What changed, newest first. `kinds` (optional, comma-separated): `new_matches`, `availability_changed`, `watch_signal`, `fits_role`.

### POST /api/activity/:id/add-to-role
Adds the person in a "may fit" suggestion (kind fits_role) to its role, with a reason. Returns `{ added, already, role, github_username, href }`.

### POST /api/roles/:id/people/:username/check
Re-check availability now (a paid lookup).

### GET /api/roles/:id/people/:username/brief
An interview brief for one person in one role, free and built from what AyHire already saved: the requirements their work supports, what is unknown (never a negative), the relevant projects, up to 3 questions, each linked to the work it asks about (one about what nothing public shows has no link), skills marked observed / inferred / unknown, review signals and freshness. Every claim points into `sources`. Returns `{ brief }`; `?format=md` returns Markdown to download; `?recheck=1` also checks on GitHub that the account and the cited repos still exist.

### GET /api/roles/:id/people/:username/outcomes · POST the same · DELETE .../outcomes/:event
Hiring outcomes for one person in one role: reviewed, shortlisted, contacted, replied, interview, offer, hired, declined, each with who recorded it (a person, or an agent) and when it happened. POST `{ "stage": "interview", "happened_at": "2026-10-20T12:00:00Z", "note": "Call with Sam" }` (`source` and `replaces`, to correct one, are optional); a stage they already have comes back with `already: true`. DELETE removes one: it stays in the history and never counts. Saving a decision records its outcome too.

### GET /api/roles/:id/funnel
The role's funnel: per stage who reached it, who has no outcome recorded after it (kept apart from zero), conversions with their denominators (`rate` null when there is nothing to divide by), declines, interview conversion and the time to the first shortlist. Returns `{ funnel }`.

### GET /api/shortlist
Everyone you shortlisted, across roles.

---

## Agents, keys and signing out

- **MCP:** `/mcp` (the same server as `/api/mcp`). AI apps connect with that address and a sign-in (OAuth 2.1, found from `/.well-known/oauth-protected-resource/mcp`), and a connection gets only what the person allowed (see, change, spend). Scripts and agents can send an API key instead. The tools, how to connect each AI app, signing out and the cards some chat apps draw: `/agents.md`.
- **API keys:** `Authorization: Bearer ayh_…` or `x-api-key`. Create and revoke them on Integrations (`/app/integrations#keys`).

### DELETE /api/keys/:id
Revokes a key (`current` means the key making the call). Returns `{ revoked: true, id }`. An API key can revoke only itself, which is what `ayhire logout` does; other keys and connected apps are revoked from Integrations in a signed-in browser.

---

## Scoring System

Four general scores about someone's public work. None is judged against a role, and where someone lives is never used.

| Dimension | Description | Range |
|-----------|-------------|-------|
| technical_depth | How substantial and widely used their work is, on their own repos and on other people's projects | 0-10 |
| shipping_velocity | How often and how recently they push, anywhere | 0-10 |
| communication | READMEs, commit messages, pull request titles, issue engagement | 0-10 |
| gem_score | How undiscovered (strong work, little public attention) | 0-10 |

**Total: 40 points max.** Analyses saved before 2026-10-10 also held "value" (work weighed against the cost of hiring where someone lives) and "stack_match" (one fixed stack); both were removed and are ignored.

---

## Environment Variables Required

| Variable | Description |
|----------|-------------|
| NEXT_PUBLIC_SUPABASE_URL | Supabase project URL |
| SUPABASE_SERVICE_ROLE_KEY | Supabase service role key |
| GITHUB_TOKEN | GitHub personal access token |
| ANTHROPIC_API_KEY | Anthropic API key for Claude analysis |
| VOYAGE_API_KEY | (Optional) Voyage AI key for embeddings |

---

## Rate Limits

- GitHub API: 5,000 requests/hour with token
- Claude API: depends on your Anthropic plan
- Bulk analyze: max 10 users per request (sequential to respect rate limits)
