# Agent connection procedure

> Approve one browser request to connect your current AI session, verify access and credits, and start working.

Canonical guide: <https://engine.neraperla.com/docs/agent-setup>

Raw Markdown: <https://engine.neraperla.com/docs/raw/agent-setup.md>

OpenAPI: <https://engine.neraperla.com/v1/openapi.json>

## Connection instructions for the agent

When the user sends the connection prompt from [Set up your AI agent](https://engine.neraperla.com/docs/agent-resources),
they are asking you to onboard this session now. Treat that prompt as a setup
request, not a request to review documentation or recommend integrations.
Use this API-key browser approval and polling procedure. Keep the interaction
short: approval link, wait for approval, connection confirmation.

Their request authorizes checking existing credentials, requesting access, and
saving the delivered key privately. Start now; do not present a plan and wait
for another "go". The human approves account and project access in the browser.
Respect any permission controls required by your host application.
Creating the key and the read-only connection checks do not consume credits;
subsequent paid work uses the approved project's billing and limits. Billing
setup may still be required in the approval screen. A temporary session
workspace is supported and does not require a connected folder.

Use `https://engine.neraperla.com` for this setup. An older skill, development endpoint, or
another connected service is not a reason to change hosts or delay connection.
Do not inspect unrelated integrations, ask for a project name or company URL,
or install/update skills, plugins, MCP servers, or standing instructions during
setup. These are instructions for the current session, not an installation.

Do not offer a choice of authentication systems, compare unrelated connected
services, or turn onboarding into a skill review. A missing saved key in a fresh
session is expected; it is not a blocker.

If this session cannot execute HTTP requests or write a private local file,
name that specific limitation and ask the user to paste the same connection
prompt into an agent session with command execution and network access.
Do not route the user into another integration by default or request an API
key pasted into chat. If they explicitly choose a connector instead, use
[Optional agent integrations](https://engine.neraperla.com/docs/agent-integrations); check that its tools
cover the requested task.

## 1. Reuse a working key

Check `BLACKPEARL_API_KEY` in the process environment, then `.env` in the
current workspace and an already-connected user folder if different. Read only
that setting without printing file contents. Do not search the whole disk or
require a new folder connection. A fresh Cowork session may have no saved key;
that is normal and should immediately lead to step 2.

For each candidate, call `GET https://engine.neraperla.com/v1/capabilities` with
`Authorization: Bearer <key>`, keeping the header and response handling inside
your program. A successful JSON response verifies the key: skip to step 4 and
reuse it for every later request. Load `.env` explicitly in new command
processes; writing a file does not export an environment variable.

Only `401 invalid_api_key` or `401 expired_api_key` establishes that a supplied
key needs replacement. `missing_api_key` means fix your Authorization header.
A timeout, `429`, `5xx`, invalid JSON, or permission error does not establish
that the key is bad. Retry transient failures as described below, or report
the actual blocker without minting a replacement. For `project_archived`,
explain that an active project must be selected in a new approval.
`400 project_required` means the key is a valid company-level key without a
default project: keep it, list projects with `GET /v1/projects` (no header
needed), and send the chosen project's id or slug in the `Blackpearl-Project`
header on every later request, including the checks in step 4. Ask the user
to choose only when more than one active project exists.

## 2. Request access immediately

Before creating a request, ensure you can write a private credential file in
the current workspace. Prefer an already-connected persistent user folder if
one is available. Otherwise use the session workspace; do not block setup to
ask the user to mount a folder. Preserve unrelated `.env` entries, never
overwrite a verified working key, and exclude credential files from version
control. On macOS/Linux use file mode `0600`.

Reuse an existing pending request from this session, including its poll URL
and expiry. Do not create another request simply because a command timed out
or the user is still signing in.

If no working key or pending request exists, send one
`POST https://engine.neraperla.com/api/agent-handshakes` with `Content-Type: application/json`.
The body only needs `agent`, set to your product name (for example,
`{"agent":"Claude Cowork"}`). Omit `project_hint` unless the user already
provided it; project selection happens in the approval screen.

Privately retain `handshake_id`, `poll_url`, `interval`, and `expires_at` so an
interrupted command can resume the same request. The poll URL contains a
credential: use it only on the configured API origin; never print it, include it in a chat link, or expose it in an
exception message. Only `verification_url` is intended for the human.

Only an owner or administrator of the organization can approve. Immediately
show that URL as a clickable link with this short message:

> Open this link to approve Blackpearl access. Sign in and complete any account
> or billing steps shown there. I'll keep checking while you do that.

Do not ask them to paste a key, choose a project in chat, or say "done" before
you start polling. Keep the task active after showing the link. If the host
requires yielding for a human action, retain the request and resume it on
return instead of starting again.

## 3. Poll and save the key in one process

Use one polling worker. Follow the returned `interval` (currently 3 seconds).
Give each HTTP request a finite timeout, for example 20 seconds, and let the
worker run through the returned approval window (normally 15 minutes).
A tool's execution time limit is not the handshake's expiry: resume the same
worker or saved request. Never run competing pollers.

Parse each response inside the worker. On `approved`, write `api_key` directly
to the chosen `.env` as `BLACKPEARL_API_KEY`, and record
`BLACKPEARL_API_BASE_URL=https://engine.neraperla.com`. Save immediately, before returning
tool output or fetching any documentation. Replace only these settings,
preserve other entries, and use a private temporary file plus an atomic
rename. Keep the key in memory until saving succeeds. Output only a status,
the file path, and optionally `api_key_prefix`; never the key or raw response.
Do not use a bare `curl`/HTTP tool call that displays the approval response.

| Response | Action |
|---|---|
| `pending` | Keep polling the same URL. The user may still be signing in or selecting a project. |
| `pending_billing` | Keep polling. Let the browser guide account/billing setup; do not create another request. |
| `approved` | Save `api_key` immediately, stop polling, then verify it in step 4. |
| `claimed` | Stop polling: a previous poll already received the key. Check the existing worker and saved file, then verify the saved key. The API cannot return this secret again. |
| `denied` | Stop and report that approval was declined. Do not automatically start another request. |
| `expired` or poll `404` | Stop using this URL. Recheck saved credentials first; if the user still wants to connect, create one replacement request and show its new approval link. |
| Unknown status or malformed successful response | Preserve the request and report the unexpected response without exposing secrets; do not claim success or create a duplicate request. |

For a timeout/network interruption or `502`/`503`/`504`, retry the same poll
URL with bounded backoff (3, 6, 12, then at most 15 seconds), within the
approval window. Respect `Retry-After` on a transient `429` or `503` rather
than polling faster. At the approval deadline, make one final poll: an approval
may have just completed. Follow the returned status; do not continue waiting
on an expired request.
Other errors need their actual message handled; avoid unbounded retry loops.

The approved response is delivered only once. A network interruption can
happen after the server consumes it. If the next response is `claimed` and
neither the worker nor the credential file has the key, explain the lost
delivery briefly. The user can revoke that request's key on **API keys**;
request one replacement approval only after checking for a saved working key.
Never manufacture a credential or keep polling `claimed`.

Do not blindly retry the initial create POST after an ambiguous network
failure: it is not idempotent. Recover any response saved by the worker first.
If no request can be recovered, explain the interruption and make at most one
replacement attempt. Never flood the user with approval links.

## 4. Verify access and credit information

Using the saved/reused key, call both:

- `GET https://engine.neraperla.com/v1/capabilities` — enabled capabilities.
- `GET https://engine.neraperla.com/v1/usage` — the project ID, usage, quotas, budgets, and the
  organization's credit balance.

These are read-only connection checks. Do not create a Brand, research run,
campaign, or any other billable work just to test setup.

If capabilities verifies but usage fails, keep the valid key and report
"Connected; I couldn't check credits yet" with the relevant next step. Do not
restart authentication. If billing is enabled and `credits.balance_usd` is
zero or negative, report "Connected; add credits in Billing before starting
paid work." A disabled capability, exhausted quota, or hard budget limit also
needs its own next step, not a new key. A positive balance is not a guarantee
that every job will pass admission or that its final charge is covered.

Read `https://engine.neraperla.com/docs/raw/gtm-workflow.md` as current-session guidance.
Fetch individual capability guides and `https://engine.neraperla.com/v1/openapi.json` only
as needed for the user's work. Do not install the optional platform skill or
rewrite existing skills. If a documentation fetch fails, retain the verified
connection and report that guidance could not be loaded; do not restart setup
or invent request shapes. Read [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs) before
starting a long-running job.

Finish briefly: "Connected to [project]. Available credits: [verified balance]."
Use the project ID if its name is unavailable; never invent a name or balance.
Then ask "What would you like to work on?" If the user already gave a task,
continue that task using only available capabilities instead of asking again.
Read-only setup does not authorize unrelated paid work.

State where the credential was saved. If it is only in temporary session
storage, say "Connected for this session; a fresh session may need approval
again." Never claim a persistent installation or promise cross-session reuse
unless the actual credential location survives those sessions. Do not display
the full key, internal infrastructure details, or a lengthy capability report.
