# Agent API — Setup

> **Rule of this project: if anything below is unclear, read this file top to bottom once. Every screen, error and doc page points back here.**

Self-hosted agent gateway. One endpoint in (`POST /api/chat`), live SSE out. It runs a real multi-step agent (planning, tools, web search, code execution, file outputs, image/video generation) and manages its own credit pool in the background — no API keys, no signup, no database, no build step.

---

## 1. Requirements

| need | why |
|---|---|
| PHP **7.4+** (8.x recommended) | the whole backend |
| PHP extension **curl** | all outbound calls |
| Apache with `mod_rewrite` **or** the PHP built-in server | clean `/api/*` paths |
| writable `storage/` folder | pool + stats live there |

No composer, no npm, no database. That's the whole list.

## 2. Deploy (shared hosting / cPanel — the normal way)

1. Upload `agent-api.zip` to your `public_html` folder.
2. Extract it **into** `public_html` (so `index.php`, `api.php`, `lib/`, `storage/` sit at the top level). cPanel: right-click the zip → Extract.
3. Make sure `storage/` is writable (most hosts already are; otherwise set `755` or `775` on `storage/`).
4. Open `https://your-domain.tld/` — you should see the agent screen. Open `https://your-domain.tld/api/info` — you should see JSON with `"ok": true`.

That's it. The first request automatically starts the background keeper, which farms funded keys and keeps the buffer full.

**Sub-directory deploy works too** (e.g. `public_html/agent/`): the included `.htaccess` and path parsing handle it — visit `https://your-domain.tld/agent/`.

## 3. Local development / VPS

```bash
PHP_CLI_SERVER_WORKERS=8 php -S 0.0.0.0:8080 router.php
```

The workers matter: the API streams SSE while also serving `stop`/`status` calls, and the built-in server is single-threaded without them. On Apache this is a non-issue.

## 4. Check it's alive

```bash
curl "https://YOUR-HOST/api/info"      # banner + pool state
curl "https://YOUR-HOST/api/credits"   # {keys, credits, keeper_running}
```

`keys` may start at `0` — the keeper fills the buffer within seconds of the first traffic and keeps it topped up (bigger under load).

## 5. Use it

```bash
curl -N -X POST "https://YOUR-HOST/api/chat" \
  -H "Content-Type: application/json" \
  -d '{"message":"write a python script that lists the first 30 fibonacci numbers and run it"}'
```

You get a live SSE stream: `open → key → run → thinking → tool → text → file/media → credits → done`.
The final `done` event carries the whole conversation as one JSON object.

Full event reference, all read/control endpoints (sessions, status, stop, media, credits) and body options are in **`docs.html`** — open it in the browser.

## 6. Wire your own bot (Telegram / Discord / anything)

Minimal loop that works everywhere:

```
1. POST /api/chat {message}                  → stream events to the user live
2. keep the conversation id from `done`      → send it back as session_id next turn
3. GET  /api/sessions/{id}/status            → show "running…" in your bot
4. POST /api/sessions/{id}/stop              → your bot's cancel button
```

If your host can't stream SSE to the bot, read the stream server-side (any SSE client) and push the final `done` JSON to the user.

## 7. How the credit pool stays full (automatic — do not touch)

- Fresh anonymous keys claim a free credit grant on arrival (~+100, seconds per key).
- Claims are minted **in parallel** and rotate through fresh network exits when a source throttles.
- A captcha-proof mailbox path backfills when the fast path is throttled (with its own cooldown).
- Existing keys re-claim their grant **daily** on their own.
- A key that hits the wall mid-task is rotated out and the task **replays silently** — users never see a credit error.
- The keeper watches request stats and scales the buffer (6 keys calm → up to 24 under heavy load).

You never pay anything and never configure anything. If `storage/` is writable, it runs itself.

## 8. Files

```
index.php          the web UI (agent screen)
api.php            the whole API (one front controller — no ?route)
docs.html          endpoint + event reference
lib/Agent.php      streaming agent client
lib/Keys.php       key pool + parallel farming + fallbacks
lib/Manager.php    stats + demand-aware buffer sizing
manager_worker.php the background keeper (spawned automatically)
lib/Proxy.php      rotating-egress gateway client (fresh IP per hop)
router.php         dev-server router (Apache uses .htaccess instead)
storage/           runtime state (starts empty, must be writable)
.htaccess          clean /api/* routing + protects lib/ and storage/
```

## 9. Troubleshooting

| symptom | fix |
|---|---|
| `/api/*` gives 404 on Apache | `mod_rewrite` off — enable AllowOverride, or host in a folder and use `index.php` as-is with the built-in server |
| `"pool empty"` event on chat | normal during the very first minute; keeper fills the buffer. If it persists, check the host can make outbound HTTPS calls |
| nothing streams, request hangs | some hosts buffer output — ask for `mod_deflate` off for PHP or use the built-in server for dev |
| `storage/` errors | make the folder writable (see §2 step 3) |
| still stuck | re-read this file once more, top to bottom — the answer is usually in §2, §5 or §7 |

---

<!-- pkg: R2xpdGNoeUFQSQ== / 476c6974636879415049 -->
