# Blackpearl Developer Documentation — Full Bundle This file is generated from canonical public Markdown in manifest order. OpenAPI: Curated index: Documentation MCP: --- # Quickstart > Create your first job, poll it safely, and print a useful sales result. Canonical guide: Raw Markdown: OpenAPI: This guide takes you from a project API key to a business summary and sales angle. You do not need another guide to complete the flow. It uses [Playbooks](https://engine.neraperla.com/docs/playbooks) as the example capability. Every capability in the Build section follows the same pattern shown here — authenticate with a project key, create a job, poll it to a terminal state — so this flow transfers directly. > [!NOTE] > Using Claude Cowork or another AI agent? Copy the [setup prompt](https://engine.neraperla.com/docs/agent-resources), approve access in your browser, and let the agent verify the connection and credits. No manual API-key handling or skill installation is required. ## Prerequisites 1. In the console, create or select a **development project**. A project owns its keys, usage, quotas, budgets, and allowance. 2. Open **API keys**, create a key with the key type **This project**, and copy the secret when it is shown. It cannot be retrieved later. A project key always acts in its own project, so the requests below need no other header. Creating keys needs the owner or administrator role. 3. Make sure your organization has prepaid credit under **Settings → Billing**. While the balance is zero or below, new jobs are refused with `402 insufficient_credits`. See [Billing and auto-recharge](https://engine.neraperla.com/docs/billing). 4. Install `curl` and `jq`. 5. Export the configured API URL and your key: ```bash export BLACKPEARL_API_BASE_URL="https://engine.neraperla.com" export BLACKPEARL_API_KEY="replace-with-your-project-key" export BLACKPEARL_IDEMPOTENCY_KEY="playbook-$(date +%s)-$$" ``` > [!WARNING] > Keep keys in a server-side secret manager. Do not commit them or embed them in browser or mobile code. A hosted development-project request performs real work and records real usage; a key prefix does not create a simulation mode. > [!NOTE] > Running work for several clients from one integration? Use a company-level key (key type **Company (all projects)**) instead, and add `--header "Blackpearl-Project: client-a"` (the project's id or slug) to the create request below. Polling a job by its ID needs no header. See [Authentication and project environments](https://engine.neraperla.com/docs/authentication) and [Managing your clients with projects](https://engine.neraperla.com/docs/projects). ## 1. Create the smallest useful Playbooks job The only input requirement is a non-empty `target_company`, a valid `target_company_domain`, or both. This request uses the domain: ```bash CREATE_RESPONSE=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/playbooks" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: $BLACKPEARL_IDEMPOTENCY_KEY" \ --header "Content-Type: application/json" \ --data '{"target_company_domain":"acme.example"}') printf '%s\n' "$CREATE_RESPONSE" | jq . ``` The API returns `202 Accepted`. The response has this exact field structure; IDs, timestamps, and the brand reflect your request and organization: ```json { "id": "job_example", "status": "queued", "progress": 0, "project_id": "proj_example", "campaign_id": null, "type": "playbooks", "input": { "target_company": null, "target_company_domain": "acme.example", "anchor_company": "Northstar Analytics", "product_info": null, "tone": "consultative", "sections": null, "model": "default", "brand_profile_id": "brand_example", "brand_profile_key": "northstar", "stage": null, "playbook_template_key": null, "offer_id": null, "campaign_id": null }, "result": null, "error": null, "error_code": null, "usage": { "tokens": 0, "input_tokens": 0, "cached_input_tokens": 0, "cache_write_tokens": 0, "output_tokens": 0, "reasoning_tokens": 0, "cost_usd": 0.0, "backend_requests": 0, "backend_runtime_ms": 0, "candidates": null }, "stages": null, "created_at": "2026-07-13T12:00:00Z", "expires_at": "2026-08-12T12:00:00Z", "started_at": null, "finished_at": null } ``` - `id` is the durable job identifier. Persist it before polling. - `Idempotency-Key` makes an ambiguous create safe to repeat with the exact same input for 24 hours. - `status` is `queued` or `running` while active, then `succeeded`, `failed`, or `canceled`. - `progress` is a coarse percentage from 0 through 100. - `project_id` identifies the project charged for the work; Playbooks has no `campaign_id`. - `input` is the normalized request snapshot. Defaults appear even when you omit them, including the brand the job sells as: the project's default brand, else your organization's default, in `brand_profile_id` and `brand_profile_key`, with the brand's name as `anchor_company` when you send none. See [Brands](https://engine.neraperla.com/docs/brands). - `result` remains `null` until success. `error` and `error_code` remain `null` unless the job fails; `error_code` then carries a stable code from the [error matrix](https://engine.neraperla.com/docs/errors) when one applies. - `usage.cost_usd` is the amount charged for this job: `0` while it runs and for a failed job, and its full price once it succeeds. The token and backend counters are kept for compatibility and are always `0`. `stages` is `null` for Playbooks. - The timestamps show when the job was accepted, when its 30-day retention window ends, when execution started, and when it reached a terminal state. The response conforms to OpenAPI schema `PublicPlaybookJobResponse`; the request conforms to OpenAPI schema `PlaybookInput`. Its OpenAPI operation is `create_playbook_v1_playbooks_post`. ## 2. Persist and poll with a deadline This shell flow resumes an existing job from `.blackpearl-playbooks-job` and creates one only when no saved ID exists. It polls with capped backoff, stops at every terminal state, and leaves the ID on disk when the local deadline expires. Playbooks jobs typically take about 10–20 minutes, so the default local deadline is 30 minutes; running the script again resumes the saved job. ```bash STATE_FILE="${BLACKPEARL_JOB_STATE_FILE:-.blackpearl-playbooks-job}" IDEMPOTENCY_FILE="${STATE_FILE}.idempotency" DEADLINE_SECONDS="${BLACKPEARL_POLL_DEADLINE_SECONDS:-1800}" if [ -s "$STATE_FILE" ]; then JOB_ID=$(tr -d '\r\n' < "$STATE_FILE") else if [ ! -s "$IDEMPOTENCY_FILE" ]; then printf 'playbook-%s-%s\n' "$(date +%s)" "$$" > "$IDEMPOTENCY_FILE" fi IDEMPOTENCY_KEY=$(tr -d '\r\n' < "$IDEMPOTENCY_FILE") CREATE_RESPONSE=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/playbooks" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: $IDEMPOTENCY_KEY" \ --header "Content-Type: application/json" \ --data '{"target_company_domain":"acme.example"}') || exit 1 JOB_ID=$(printf '%s' "$CREATE_RESPONSE" | jq -er '.id') || exit 1 printf '%s\n' "$JOB_ID" > "$STATE_FILE" fi deadline=$((SECONDS + DEADLINE_SECONDS)) delay=2 while [ "$SECONDS" -lt "$deadline" ]; do JOB=$(curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/jobs/$JOB_ID" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY") || exit 1 STATUS=$(printf '%s' "$JOB" | jq -er '.status') || exit 1 printf 'status=%s progress=%s%%\n' "$STATUS" "$(printf '%s' "$JOB" | jq -r '.progress')" case "$STATUS" in succeeded) printf 'Business summary: %s\n' "$(printf '%s' "$JOB" | jq -er '.result.business_summary')" printf 'First sales angle: %s\n' "$(printf '%s' "$JOB" | jq -er '.result.sales_angles[0]')" rm -f "$STATE_FILE" rm -f "$IDEMPOTENCY_FILE" exit 0 ;; failed) printf 'Playbooks job failed: %s\n' "$(printf '%s' "$JOB" | jq -r '.error // "No failure message returned"')" >&2 rm -f "$STATE_FILE" rm -f "$IDEMPOTENCY_FILE" exit 1 ;; canceled) printf 'Playbooks job was canceled.\n' >&2 rm -f "$STATE_FILE" rm -f "$IDEMPOTENCY_FILE" exit 1 ;; queued|running) ;; *) printf 'Unknown job status: %s\n' "$STATUS" >&2; exit 1 ;; esac sleep "$delay" if [ "$delay" -lt 15 ]; then delay=$((delay * 2)); fi if [ "$delay" -gt 15 ]; then delay=15; fi done printf 'Polling deadline reached; resume job %s using %s.\n' "$JOB_ID" "$STATE_FILE" >&2 exit 2 ``` > [!IMPORTANT] > A client timeout does not cancel server work. Keep the job ID and resume later. Job polling is rate-limited but is not billed as another Playbooks generation request. The API retains the job and result through `expires_at`, 30 days after creation. Store any result your application needs beyond that timestamp. After expiry, job and candidate reads return `410 job_expired`; expiry does not remove usage, cost, or audit records. If the create connection is lost before you receive the job ID, repeat the exact POST with the key saved in `IDEMPOTENCY_FILE`. A matching request returns the original `202` body and does not create or bill another job. Do not change the input while reusing a key, and do not expect replay after its 24-hour window. ## Expected output A successfully configured Playbooks backend produces output with this structure; generated content varies by request and backend: ```text status=running progress=55% status=succeeded progress=100% Business summary: First sales angle: ``` An unconfigured backend fails the Job instead of returning synthetic content. ## Next steps - Run the tested [Python or TypeScript quickstart](#python-and-typescript-versions) when moving this flow into an application. - Learn how to store and resume jobs in [Jobs and polling](https://engine.neraperla.com/docs/jobs). - Add seller context and choose sections in [Playbooks](https://engine.neraperla.com/docs/playbooks). - Handle API failures by `error.code` using the [error and retry matrix](https://engine.neraperla.com/docs/errors). - See typical prices before you run and what each run was charged afterwards in [Billing and auto-recharge](https://engine.neraperla.com/docs/billing). - Run work for your own clients, each with its own allowance and limits, in [Managing your clients with projects](https://engine.neraperla.com/docs/projects). ## Python and TypeScript versions The same flow ships as tested, dependency-light programs. The complete sources are embedded below; in the repository they live under `docs/examples/`. Both read only `BLACKPEARL_API_BASE_URL` and `BLACKPEARL_API_KEY` for credentials and connection details, so use a project key with them. Their default local polling deadline is 120 seconds: set `BLACKPEARL_POLL_DEADLINE_SECONDS=1800` for a hosted Playbooks run, or run the program again to resume the saved job. Run the standard-library-only script: ```bash python3 docs/examples/python/playbooks_quickstart.py ``` ```python #!/usr/bin/env python3 """Minimal, dependency-free Playbooks quickstart. Required environment: BLACKPEARL_API_BASE_URL Configured gateway URL, for example http://localhost:8400 BLACKPEARL_API_KEY Project-scoped API key """ from __future__ import annotations import json import os import random import sys import time import uuid from pathlib import Path from typing import Any from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen TERMINAL = {"succeeded", "failed", "canceled"} TRANSIENT_READ_CODES = { "rate_limit_exceeded", "internal_error", "audiences_backend_error", "audiences_backend_invalid_response", "audiences_backend_unavailable", } class APIError(RuntimeError): def __init__(self, status: int, code: str, message: str, retry_after: str | None = None): super().__init__(f"API error {status} {code}: {message}") self.status = status self.code = code self.retry_after = retry_after def required_env(name: str) -> str: value = os.environ.get(name, "").strip() if not value: raise RuntimeError(f"Set {name} before running this example") return value def request_json( method: str, url: str, api_key: str, body: dict[str, Any] | None = None, extra_headers: dict[str, str] | None = None, ) -> tuple[dict[str, Any], Any]: payload = json.dumps(body).encode() if body is not None else None request = Request( url, data=payload, method=method, headers={ "Authorization": f"Bearer {api_key}", "Accept": "application/json", **({"Content-Type": "application/json"} if body is not None else {}), **(extra_headers or {}), }, ) try: with urlopen(request, timeout=30) as response: return json.load(response), response.headers except HTTPError as exc: try: payload = json.loads(exc.read()) error = payload.get("error", {}) except (json.JSONDecodeError, AttributeError): error = {} raise APIError( exc.code, str(error.get("code", "http_error")), str(error.get("message", exc.reason)), exc.headers.get("Retry-After"), ) from exc except URLError as exc: raise RuntimeError(f"Could not reach the configured API: {exc.reason}") from exc def persist_job_id(path: Path, job_id: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(f"{job_id}\n", encoding="utf-8") def persistent_idempotency_key(path: Path) -> str: if path.exists() and path.read_text(encoding="utf-8").strip(): return path.read_text(encoding="utf-8").strip() key = f"playbook-{uuid.uuid4()}" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(f"{key}\n", encoding="utf-8") return key def create_or_resume(base_url: str, api_key: str, state_path: Path) -> str: if state_path.exists() and state_path.read_text(encoding="utf-8").strip(): job_id = state_path.read_text(encoding="utf-8").strip() print(f"Resuming Playbooks job {job_id}") return job_id # Persist the key before sending. If the connection fails ambiguously, rerun # with this same request/key during the 24-hour replay window. idempotency_key = persistent_idempotency_key( state_path.with_name(f"{state_path.name}.idempotency") ) job, _ = request_json( "POST", f"{base_url}/v1/playbooks", api_key, {"target_company_domain": "acme.example"}, {"Idempotency-Key": idempotency_key}, ) job_id = job.get("id") if job.get("type") != "playbooks" or not isinstance(job_id, str) or not job_id: raise RuntimeError("Create response did not contain a typed Playbooks job ID") persist_job_id(state_path, job_id) print(f"Created Playbooks job {job_id}") return job_id def poll_job(base_url: str, api_key: str, job_id: str) -> dict[str, Any]: timeout = float(os.environ.get("BLACKPEARL_POLL_DEADLINE_SECONDS", "120")) delay = float(os.environ.get("BLACKPEARL_POLL_INITIAL_SECONDS", "2")) max_delay = float(os.environ.get("BLACKPEARL_POLL_MAX_SECONDS", "10")) deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: job, _ = request_json("GET", f"{base_url}/v1/jobs/{job_id}", api_key) except APIError as exc: if exc.code not in TRANSIENT_READ_CODES: raise if exc.code == "rate_limit_exceeded" and exc.retry_after: delay = max(delay, float(exc.retry_after)) time.sleep(min(delay, max(0.0, deadline - time.monotonic()))) delay = min(max_delay, max(delay * 2, 0.01)) continue status = job.get("status") if status not in {"queued", "running", *TERMINAL}: raise RuntimeError(f"Unknown job status: {status!r}") print(f"status={status} progress={job.get('progress')}%") if status in TERMINAL: return job jittered = delay * random.uniform(0.8, 1.2) time.sleep(min(jittered, max(0.0, deadline - time.monotonic()))) delay = min(max_delay, max(delay * 2, 0.01)) raise TimeoutError(f"Polling deadline reached; resume job {job_id} from the saved state file") def render_result(job: dict[str, Any]) -> None: status = job["status"] if status == "failed": raise RuntimeError(f"Playbooks job failed: {job.get('error') or 'No failure message returned'}") if status == "canceled": raise RuntimeError("Playbooks job was canceled") if job.get("type") != "playbooks" or status != "succeeded": raise RuntimeError("Expected a successful Playbooks job") result = job.get("result") if not isinstance(result, dict): raise RuntimeError("Successful Playbooks job did not contain a typed result") summary = result.get("business_summary") angles = result.get("sales_angles") if not isinstance(summary, str) or not summary or not isinstance(angles, list) or not angles or not isinstance(angles[0], str): raise RuntimeError("Playbooks result did not contain a useful business summary and sales angle") print(f"Business summary: {summary}") print(f"First sales angle: {angles[0]}") def main() -> int: base_url = required_env("BLACKPEARL_API_BASE_URL").rstrip("/") api_key = required_env("BLACKPEARL_API_KEY") state_path = Path(os.environ.get("BLACKPEARL_JOB_STATE_FILE", ".blackpearl-playbooks-job")) try: job_id = create_or_resume(base_url, api_key, state_path) job = poll_job(base_url, api_key, job_id) render_result(job) state_path.unlink(missing_ok=True) state_path.with_name(f"{state_path.name}.idempotency").unlink(missing_ok=True) return 0 except Exception as exc: print(str(exc), file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main()) ``` Install and run with npm: ```bash npm --prefix docs/examples/typescript install npm --prefix docs/examples/typescript start ``` ```typescript import { randomUUID } from "node:crypto"; import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; type JobStatus = "queued" | "running" | "succeeded" | "failed" | "canceled"; interface ErrorResponse { error?: { code?: string; message?: string }; } interface PlaybookJob { id: string; type: "playbooks"; status: JobStatus; progress: number; error: string | null; result: null | { business_summary: string | null; sales_angles: string[] }; } const terminal = new Set(["succeeded", "failed", "canceled"]); const transientReadCodes = new Set([ "rate_limit_exceeded", "internal_error", "audiences_backend_error", "audiences_backend_invalid_response", "audiences_backend_unavailable", ]); class ApiError extends Error { constructor( readonly status: number, readonly code: string, message: string, readonly retryAfter: string | null, ) { super(`API error ${status} ${code}: ${message}`); } } function requiredEnv(name: string): string { const value = process.env[name]?.trim(); if (!value) throw new Error(`Set ${name} before running this example`); return value; } async function requestJson( method: "GET" | "POST", url: string, apiKey: string, body?: object, extraHeaders: Record = {}, ): Promise<{ body: unknown; headers: Headers }> { const response = await fetch(url, { method, headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json", ...(body ? { "Content-Type": "application/json" } : {}), ...extraHeaders, }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(30_000), }); const payload: unknown = await response.json(); if (!response.ok) { const error = (payload as ErrorResponse).error; throw new ApiError( response.status, error?.code ?? "http_error", error?.message ?? response.statusText, response.headers.get("Retry-After"), ); } return { body: payload, headers: response.headers }; } function isPlaybookJob(value: unknown): value is PlaybookJob { if (!value || typeof value !== "object") return false; const job = value as Partial; return typeof job.id === "string" && job.type === "playbooks" && ["queued", "running", "succeeded", "failed", "canceled"].includes(job.status ?? ""); } const sleep = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)); async function saveJobId(path: string, jobId: string): Promise { await mkdir(dirname(path), { recursive: true }); await writeFile(path, `${jobId}\n`, "utf8"); } async function persistentIdempotencyKey(path: string): Promise { try { const key = (await readFile(path, "utf8")).trim(); if (key) return key; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } const key = `playbook-${randomUUID()}`; await mkdir(dirname(path), { recursive: true }); await writeFile(path, `${key}\n`, "utf8"); return key; } async function createOrResume(baseUrl: string, apiKey: string, statePath: string): Promise { try { const jobId = (await readFile(statePath, "utf8")).trim(); if (jobId) { console.log(`Resuming Playbooks job ${jobId}`); return jobId; } } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } // Persist the key before sending so an ambiguous failure is safely retried // with the same request and key during the 24-hour replay window. const idempotencyKey = await persistentIdempotencyKey(`${statePath}.idempotency`); const { body } = await requestJson("POST", `${baseUrl}/v1/playbooks`, apiKey, { target_company_domain: "acme.example", }, { "Idempotency-Key": idempotencyKey }); if (!isPlaybookJob(body)) throw new Error("Create response did not contain a typed Playbooks job ID"); await saveJobId(statePath, body.id); console.log(`Created Playbooks job ${body.id}`); return body.id; } async function pollJob(baseUrl: string, apiKey: string, jobId: string): Promise { const timeoutMs = Number(process.env.BLACKPEARL_POLL_DEADLINE_SECONDS ?? "120") * 1000; let delayMs = Number(process.env.BLACKPEARL_POLL_INITIAL_SECONDS ?? "2") * 1000; const maxDelayMs = Number(process.env.BLACKPEARL_POLL_MAX_SECONDS ?? "10") * 1000; const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { const { body } = await requestJson("GET", `${baseUrl}/v1/jobs/${jobId}`, apiKey); if (!isPlaybookJob(body)) throw new Error("Polling response was not a typed Playbooks job"); console.log(`status=${body.status} progress=${body.progress}%`); if (terminal.has(body.status)) return body; } catch (error) { if (!(error instanceof ApiError) || !transientReadCodes.has(error.code)) throw error; if (error.code === "rate_limit_exceeded" && error.retryAfter) { delayMs = Math.max(delayMs, Number(error.retryAfter) * 1000); } } const jitteredMs = delayMs * (0.8 + Math.random() * 0.4); await sleep(Math.min(jitteredMs, Math.max(0, deadline - Date.now()))); delayMs = Math.min(maxDelayMs, Math.max(delayMs * 2, 10)); } throw new Error(`Polling deadline reached; resume job ${jobId} from the saved state file`); } function renderResult(job: PlaybookJob): void { if (job.status === "failed") throw new Error(`Playbooks job failed: ${job.error ?? "No failure message returned"}`); if (job.status === "canceled") throw new Error("Playbooks job was canceled"); const summary = job.result?.business_summary; const firstAngle = job.result?.sales_angles[0]; if (job.status !== "succeeded" || !summary || !firstAngle) { throw new Error("Playbooks result did not contain a useful business summary and sales angle"); } console.log(`Business summary: ${summary}`); console.log(`First sales angle: ${firstAngle}`); } async function main(): Promise { const baseUrl = requiredEnv("BLACKPEARL_API_BASE_URL").replace(/\/$/, ""); const apiKey = requiredEnv("BLACKPEARL_API_KEY"); const statePath = process.env.BLACKPEARL_JOB_STATE_FILE ?? ".blackpearl-playbooks-job"; const jobId = await createOrResume(baseUrl, apiKey, statePath); const job = await pollJob(baseUrl, apiKey, jobId); renderResult(job); await rm(statePath, { force: true }); await rm(`${statePath}.idempotency`, { force: true }); } main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }); ``` --- # Build a GTM workflow > Chain the main capabilities — brand and offer context, prospecting, playbooks, and outcomes — into one attributable end-to-end workflow. Canonical guide: Raw Markdown: OpenAPI: This guide shows the main end-to-end path through the platform: establish brand and offer context once, discover and qualify prospects, generate a playbook for each prospect you will work, and record what happened. Each step's typed contract lives in its own guide; this page shows how the steps chain. It is written to be followed by an AI agent as well as a human. If you are an agent, also read the behavioral rules in [Use Blackpearl with your AI agent](https://engine.neraperla.com/docs/agent-resources). ## Step 0: Check what is enabled Call `GET /v1/capabilities` before planning. Every generally available capability is returned with an `enabled` flag. Plan only with capabilities that show `enabled: true`; if something the user wants shows `enabled: false`, tell them it exists but needs to be enabled for their organization — do not try to work around it. See [Capabilities and entitlements](https://engine.neraperla.com/docs/feature-flags). ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/capabilities" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq '.capabilities[] | {key, enabled}' ``` ## Step 1: Create the context once — a Brand and an Offer Almost everything downstream improves when the platform knows what you sell and who you are. Both objects are created once and reused by every later run: 1. **Brand** — create it from the company website and run brand research; the platform derives positioning, audience, and voice as a versioned guideline. The only input you need from a user is their company URL. See [Brands](https://engine.neraperla.com/docs/brands). 2. **Offer** — record what is being sold: value propositions, proof points, pricing shape, and ideal-customer hints. Draft it from the brand research rather than asking the user to dictate it, then confirm. See [Offers](https://engine.neraperla.com/docs/offers). These two objects are the GTM graph's anchor. [Campaigns](https://engine.neraperla.com/docs/campaigns) bind a brand, an offer, and saved targeting into a reusable container and run [Audience](https://engine.neraperla.com/docs/audiences) cycles when you want reviewable, exportable lists. ## Step 2: Discover and qualify prospects Create a [Prospecting](https://engine.neraperla.com/docs/prospecting) job. Derive `product_info` and `objective` from the Brand guideline and Offer — do not ask the user to restate them. Leave the structured `target` empty unless the user explicitly constrains it: discovering and qualifying the right people is the platform's job. A run returns every prospect the agent delivers, up to 5,000. `qualification.score` is the search agent's own fit score for that run, not comparable across runs: don't cut prospects by it. ```bash JOB=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/prospects" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: $BLACKPEARL_IDEMPOTENCY_KEY" \ --header "Content-Type: application/json" \ --data '{ "campaign_name": "First prospecting run", "product_info": "Summarized from the Offer value propositions.", "objective": "Summarized from the Offer ideal-customer hints.", "delivery_mode": "draft_only" }') JOB_ID=$(printf '%s' "$JOB" | jq -er '.id') ``` Poll `GET /v1/jobs/{job_id}` to a terminal state as described in [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs). A run typically takes several minutes. A run that delivers no prospects ends `failed` and is not charged unless its search finished and found no matches; see [When a run delivers nothing](https://engine.neraperla.com/docs/prospecting#when-a-run-delivers-nothing). Prospects come without outreach drafts, so write first-touch copy with [Message Templates](https://engine.neraperla.com/docs/message-templates). To keep a reviewable, exportable list, materialize the successful run into an audience snapshot ([Audiences](https://engine.neraperla.com/docs/audiences)). ## Step 3: Generate a playbook per prospect For each qualified prospect (for example, today's call list), create a [Playbooks](https://engine.neraperla.com/docs/playbooks) job for its account. Pass `stage`, `playbook_template_key`, and your `offer_id` so guidance is tailored to selling that offer to that account at that stage. Personalised collateral ([Documents](https://engine.neraperla.com/docs/documents)) and evidence-bound [Message Templates](https://engine.neraperla.com/docs/message-templates) compose the same way. ## Step 4: Record what happened Close the loop with [Outcomes](https://engine.neraperla.com/docs/outcomes): append real-world results — meetings booked, replies, wins — against the prospect, account, or campaign, and read deterministic insight aggregates back. Attribution flows through the GTM graph, so the next run is informed by the last one. ## Coming soon [Enrichment](https://engine.neraperla.com/docs/enrichment) (contact and company data completion, including business-email discovery) is in Preview and will slot between Steps 2 and 3 once generally available. This is the first workflow in what will become a small library. The capability guides above remain the source of truth for exact request and response fields. --- # Brands > Turn a company name or website into a versioned, evidence-backed brand guideline. Canonical guide: Raw Markdown: OpenAPI: Brands creates a reusable identity and messaging foundation for downstream documents, presentations, Playbooks, campaigns, and templates. Supply a company name, an official website, or both. The platform enqueues web research and stores the completed result as a strict, versioned guideline rather than an unstructured report. Brands belong to your company, not to a project. Every API key of your company, including a project key, can list, read, and refresh every brand, whichever project created it; the research run is charged to the project that started it. If you run a project per client and brand names are sensitive, don't give a client a project key of its own; see [Projects](https://engine.neraperla.com/docs/projects#give-each-client-its-own-brand). ## Create and poll a brand Operation `create_brand_v1_brands_post` creates a Brand and starts its first research Job. Send an `Idempotency-Key` with the first request and retain it until the returned job ID is stored. Matching retries within 24 hours replay the original response and do not create a duplicate profile. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/brands" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: brand-20260716-acme" \ --header "Content-Type: application/json" \ --data '{ "company_name": "Acme Corporation", "website_url": "https://acme.example", "is_default": false }' ``` At least one of `company_name` and `website_url` is required. `is_default: true` makes the brand your organization's default; your organization's first brand becomes its default either way. If you run a project per client, leave it false and set the brand as that client project's `default_brand_profile_id` instead; see [Give each client its own brand](https://engine.neraperla.com/docs/projects#give-each-client-its-own-brand). The response is a typed asynchronous job with `type: "brands"`. Poll `GET /v1/jobs/{job_id}` until `status` is `succeeded`, `failed`, or `canceled`. A successful `result` contains `brand_profile_id`, `schema_version`, `revision`, `guideline_hash`, `source_count`, and `guideline_path`. ## Read brand state Operation `list_brands_v1_brands_get` uses `GET /v1/brands` to list active brands. Operation `get_brand_v1_brands__brand_id__get` uses `GET /v1/brands/{brand_id}` to inspect one. Both expose safe state metadata such as `research_status`, `research_job_id`, `guideline_available`, `guideline_revision`, and `source_count`. They do not expose raw provider responses, traces, credentials, internal service identifiers, or the internal branding snapshot. `research_status` is one of `not_started`, `queued`, `researching`, `ready`, `failed`, or `canceled`. If a refresh fails, the previous successful guideline remains stored and readable. ## Consume the guideline After the job succeeds, use operation `get_brand_guideline_v1_brands__brand_id__guideline_get` at the path returned in `result.guideline_path`: ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/brands/$BRAND_ID/guideline" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" ``` The response has stable sections for `identity`, `foundations`, `audience`, `positioning`, `voice`, `messaging`, `visual`, `applications`, `governance`, and `research`, plus `brand_profile_id`, `revision`, `guideline_hash`, `generated_at`, `generation`, and a deterministic `markdown` rendering. Evidence-bearing sections reference entries in `research.sources` and carry a confidence level. Unknown facts remain null or empty rather than being invented. Source URLs are served without `utm_*` tracking parameters, in `research.sources` and in `markdown`. `generation.provider` is `pearl_engine` for a researched guideline. Bind `brand_profile_id`, `revision`, and `guideline_hash` to each downstream artifact. Do not silently change guideline revisions in the middle of a generation job. Treat generated claims and external material as reviewable context: a guideline does not authorize publishing, outreach, or writes to another system. ## Refresh and errors Operation `research_brand_v1_brands__brand_id__research_post` starts a new revision with `POST /v1/brands/{brand_id}/research`. When a run is already active, the endpoint returns that job instead of enqueuing another. Common failures include `invalid_request`, `brand_profile_not_found`, `brand_profile_archived`, `conflict` (for example, your company already has the maximum number of active brands), `not_ready`, `capability_disabled`, `insufficient_credits`, `quota_exceeded`, `budget_exceeded`, and `project_archived`. Follow the [error and retry guide](https://engine.neraperla.com/docs/errors); retry an ambiguous POST only with its original body and idempotency key. --- # Offers > Reuse structured value propositions, proof points, pricing shape, ICP hints, and deal-stage fit across GTM work. Canonical guide: Raw Markdown: OpenAPI: An Offer is the organization-scoped catalog object for what a brand sells. It gives Playbooks, Campaigns, templates, and Outcome attribution one structured source of selling context. Creating or reading an Offer performs no research, pricing calculation, provider call, or outbound action. ## Create an offer Operation `create_offer_v1_offers_post` requires an active `brand_profile_id` and `name`. An optional stable `key` is derived from the name when omitted. ```bash OFFER=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/offers" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data "{ \"brand_profile_id\": \"$BRAND_ID\", \"name\": \"AI SDR co-pilot\", \"key\": \"ai_sdr_copilot\", \"description\": \"Evidence-backed research, qualification, and drafting for SDR teams.\", \"value_props\": [\"Cut account research from hours to minutes\"], \"proof_points\": [\"Customer-approved proof point\"], \"pricing_model\": \"Per-seat subscription\", \"icp\": { \"industries\": [\"B2B SaaS\"], \"company_sizes\": [\"51-200\"], \"regions\": [\"ANZ\"], \"personas\": [\"VP Sales\"], \"signals\": [\"Hiring SDRs\"] }, \"stage_fit\": [\"cold_outreach\", \"discovery\"], \"status\": \"active\" }") OFFER_ID=$(printf '%s' "$OFFER" | jq -er '.id') ``` Allowed stages are `cold_outreach`, `discovery`, `evaluation`, `proposal`, `negotiation`, `closing`, `onboarding`, `expansion`, `renewal`, and `winback`. `icp` is a closed object; unknown fields and credentials are rejected. `pricing_model` is descriptive text, not executable quote or discount logic. Create is not an idempotent replay operation. A duplicate key returns `offer_key_exists`; after an ambiguous network failure, list and match by key before retrying. ## Read and reuse offers Operation `list_offers_v1_offers_get` returns up to 200 organization offers. `include_archived=true` includes catalog entries retained for historical attribution. Operation `get_offer_v1_offers__offer_id__get` returns one Offer in the caller's organization. Pass an active `offer_id` to Playbooks or bind it to a Campaign. Record the same ID on Outcomes and group insights by offer to measure which selling proposition is landing. Archived Offers remain readable historical attribution targets but cannot be selected for new generation work. Common failures include `capability_disabled` (the `offers` capability is not enabled for the organization — creation is blocked while existing offers stay readable), `brand_profile_not_found`, `brand_profile_archived`, `offer_key_exists`, `offer_limit_exceeded`, invalid field or stage values, and `offer_not_found`. Follow [Errors and safe retries](https://engine.neraperla.com/docs/errors). --- # Campaigns > Save repeatable targeting, bind GTM context, and run asynchronous audience cycles without granting delivery authority. Canonical guide: Raw Markdown: OpenAPI: A Campaign is the project-scoped organizing object for repeatable Audience targeting. It saves an `AudienceInput`, records cycle history, and can bind the brand, offer, Playbook, message-template revision, and dossier specification used by a caller's external GTM pipeline. Blackpearl does not enroll recipients, schedule sequences, or send messages. ## Create and find campaigns Operation `create_campaign_v1_campaigns_post` creates a campaign without starting a run. The request uses the same typed targeting fields as direct Audience creation. ```bash CAMPAIGN=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/campaigns" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data '{ "key": "anz-revops-2026q3", "name": "ANZ RevOps leaders", "objective": "Find revenue operations leaders at B2B SaaS companies in Australia and New Zealand.", "target_size": 100, "model": "default" }') CAMPAIGN_ID=$(printf '%s' "$CAMPAIGN" | jq -er '.id') ``` Campaign keys are optional and stable within the project. Repeating a create with the same normalized key and targeting input returns the existing campaign; changed targeting input under that key returns `campaign_key_exists`. Operation `list_campaigns_v1_campaigns_get` lists non-archived campaigns newest first and accepts `limit` plus an opaque `cursor`. Operation `get_campaign_v1_campaigns__campaign_id__get` reads one campaign. ## Bind the GTM graph Operation `update_campaign_v1_campaigns__campaign_id__patch` updates only supplied fields. Use it to change `name`, `key`, `objective`, lifecycle `status`, scalar `metadata`, or these optional relations: `brand_profile_id`, `offer_id`, `playbook_job_id`, `message_template_revision_id`, and `company_dossier_specification_id`. ```bash curl --fail-with-body --silent --show-error \ --request PATCH "$BLACKPEARL_API_BASE_URL/v1/campaigns/$CAMPAIGN_ID" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data "{ \"status\": \"active\", \"brand_profile_id\": \"$BRAND_ID\", \"offer_id\": \"$OFFER_ID\" }" ``` Omit a relation to preserve it, send an empty string to clear it, or send an ID to rebind it. The complete merged relation set is validated. In particular, an offer must belong to the bound brand. Archived or out-of-scope relations fail closed. Lifecycle transitions are `draft` to `active` or `archived`; `active` to `paused`, `completed`, or `archived`; `paused` to `active`, `completed`, or `archived`; and `completed` to `archived`. Archived is terminal. These states describe your pipeline, never Blackpearl delivery activity. ## Run cycles Operation `run_campaign_cycle_v1_campaigns__campaign_id__cycles_post` starts one asynchronous Audience cycle. Supply `Idempotency-Key` and retain it until the Job ID is stored. Only one queued or running cycle is allowed per campaign: starting another returns `409 cycle_in_progress`. An archived campaign returns `campaign_archived`, and a campaign in an archived project returns `project_archived`. ```bash JOB=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/campaigns/$CAMPAIGN_ID/cycles" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: cycle-20260717-anz-revops") ``` Poll the returned Job as described in [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs). Operation `list_campaign_cycles_v1_campaigns__campaign_id__cycles_get` returns the most recent non-expired cycle Jobs in descending creation order. Each retained Job remains readable for 30 days. A cycle's stages use the keys listed in [Audiences](https://engine.neraperla.com/docs/audiences); the first cycle runs the setup stages, and later cycles reuse that setup. On the campaign, `total_cost_usd` is the total charged for its cycles, all time. `schedule` reports recurring cycles configured in the web console; the API reads it but does not change it. Use [Outcomes](https://engine.neraperla.com/docs/outcomes) to record external results against `campaign_id`. A Campaign organizes targeting and attribution; it is not proof of consent and grants no outbound authority. --- # Audiences > Run evidence-backed audience discovery, then materialize immutable review snapshots from real prospects. Canonical guide: Raw Markdown: OpenAPI: Audiences has two complementary workflows. The live audience workflow — powered by the engine ranked first on [GTM-Bench](https://gtm-bench.ai/) — runs asynchronous discovery and returns scored candidates. The snapshot workflow freezes selected prospects from a successful Prospecting job so people can review and export a stable list. Neither workflow authorizes or sends outreach. ## Run one audience discovery Operation `create_audience_v1_audiences_post` accepts an `AudienceInput` at `POST /v1/audiences`. The required `objective` describes the companies and buyers to find. `target_size` is 1 through 2,000, `max_contacts_per_company` is 1 through 10, and optional seller, product, ICP, exclusion, and intent context refines the run. ```bash JOB=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/audiences" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: audience-run-20260717-anz-revops" \ --header "Content-Type: application/json" \ --data '{ "objective": "Find revenue operations leaders at B2B SaaS companies in Australia and New Zealand.", "target_size": 100, "max_contacts_per_company": 3, "model": "default" }') JOB_ID=$(printf '%s' "$JOB" | jq -er '.id') ``` The response is an asynchronous Audience job. The request also saves its targeting as a [Campaign](https://engine.neraperla.com/docs/campaigns), returned as the job's `campaign_id`, so you can run later cycles with `POST /v1/campaigns/{campaign_id}/cycles`. Poll the job using [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs). Its `stages` are, in order, `icp`, `intent`, and `industries` (the campaign's setup, reused by later cycles), then `retrieval`, `prelim`, `deep`, `final`, and `playbooks`. Each stage is `pending`, `running`, `completed`, `skipped`, or `failed`. The job's `usage.cost_usd` is what the cycle was charged. After the Job succeeds, operation `list_audience_candidates_v1_audiences__job_id__candidates_get` pages `GET /v1/audiences/{job_id}/candidates`. Pass each opaque `next_cursor` back unchanged and stop when it is null. Optional `q` filtering is applied before pagination. ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/audiences/$JOB_ID/candidates?limit=50" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` Candidate rows are discriminated by `result_shape`: a `company` row has company scoring plus contacts, while a `contact` row is one scored contact with company context. Results remain available until the job's `expires_at`; save anything needed beyond the 30-day retention window. Operation `export_audience_candidates_csv_v1_audiences__job_id__candidates_csv_get` downloads the full candidate list of a succeeded job as UTF-8, RFC 4180 CSV with CRLF line endings at `GET /v1/audiences/{job_id}/candidates.csv` — one row per contact with the company columns repeated, and a single row for a company without contacts. Cells whose first meaningful character is `=`, `+`, `-`, or `@` are neutralized with a leading apostrophe. A job that has not succeeded returns `not_ready`. ## Materialize an immutable snapshot Use a snapshot when a successful, non-synthetic Prospecting result should become a durable review set. Operation `create_audience_v1_audience_snapshots_post` accepts a caller-owned `key`, a display `name`, the source `prospecting_job_id`, and an optional subset of `prospect_ids`. ```bash SNAPSHOT=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/audience-snapshots" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data "{ \"key\": \"anz-revops-2026q3\", \"name\": \"ANZ RevOps leaders\", \"prospecting_job_id\": \"$PROSPECTING_JOB_ID\" }") AUDIENCE_ID=$(printf '%s' "$SNAPSHOT" | jq -er '.id') ``` The create namespace is project, API-key environment, and `key`. An exact replay returns the original resource with HTTP 200; different normalized input under the same key returns `audience_idempotency_conflict`. The server stores a hash of the normalized source result and copies only validated prospect fields. A later provider or Job change cannot rewrite the snapshot. Operation `list_audiences_v1_audience_snapshots_get` lists snapshots newest first with cursor pagination. Operation `get_audience_v1_audience_snapshots__audience_id__get` reads one snapshot. Resources in another project or `live`/`test` environment resolve as not found. ## Review members Operation `list_audience_members_v1_audience_snapshots__audience_id__members_get` pages the frozen members. Filters include text query, review, qualification, enrichment and outreach states, minimum score (`min_score`), evidence or work-email presence, and exact prospect ID. Cursors are bound to the filter set; restart pagination when a filter changes. `min_score` compares each member's `qualification.score`, the search agent's own fit score for its run, so a `min_score` filter can drop qualified members. Filter on `qualification_status` instead of the score unless you have checked the scores in your snapshot. Operation `review_audience_members_v1_audience_snapshots__audience_id__reviews_post` records an append-only `included` or `excluded` decision for 1 through 100 member IDs. Generate one `review_key` per logical decision and retain it for retries. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/audience-snapshots/$AUDIENCE_ID/reviews" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data "{ \"review_key\": \"review-20260717-batch-1\", \"member_ids\": [\"$AUDIENCE_MEMBER_ID\"], \"decision\": \"included\", \"reason_code\": \"verified-fit\" }" ``` Review means curation, not consent or delivery permission. Every snapshot and member returns `outbound_authorized: false`, including included members. ## Export and safety Operation `export_audience_csv_v1_audience_snapshots__audience_id__export_csv_get` exports the current filtered snapshot as CSV. Members keep the prospect's `enrichment.phone` when the run found one, but the snapshot CSV has no phone column; use the prospecting run export when you need phone numbers. Every list surface has a CSV export: this snapshot export, the live audience candidate export above, and the [prospecting run export](https://engine.neraperla.com/docs/prospecting). Treat names, emails, profile details, generated drafts, and evidence as personal or untrusted application data. Apply your own lawful-basis, suppression, consent, access-control, retention, and dispatch-time checks outside Blackpearl. Common failures are `not_ready`, `job_expired`, `audiences_result_unavailable`, `prospecting_job_not_found`, `synthetic_prospecting_result`, `audience_idempotency_conflict`, `invalid_cursor`, entitlement, quota, and budget errors. Follow [Errors and safe retries](https://engine.neraperla.com/docs/errors). --- # Playbooks > Configure a Playbooks request and interpret every part of its typed result. Canonical guide: Raw Markdown: OpenAPI: Playbooks creates a tailored sales playbook for one target account. Start with the complete [quickstart](https://engine.neraperla.com/docs/getting-started), then use this guide to choose inputs and render more of the result. Generation is asynchronous and typically completes in about 10–20 minutes in current production operation; occasional runs take longer. Poll the returned job at a steady 15–30 second interval, keep the job ID so polling can resume after any interruption, and treat an individual failed poll as retryable rather than as a failed job — see [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs). This timing is operational guidance, not a completion-time promise. ## Playbook templates The catalog is OpenAPI operation `list_playbook_templates_v1_playbook_templates_get`. `playbook_template_key` selects a playbook template: either one of your organization's own templates (created in the console under **Playbook Templates**, or via `POST /api/orgs/{org_id}/playbook-templates`) or a curated catalog entry. `GET /v1/playbook-templates` lists both — your templates first — along with the merged stage vocabulary. An organization template fixes the offer, brand profile, deal stage (your own stage names are accepted — any short lowercase slug), sales approach guidance, and an offer canon that the generation backend treats as human-approved seller facts (seller research is skipped when a canon exists). Unknown keys fail the run with `playbook_template_not_found`. ### The template lifecycle A template is created from a name, an offer/brand binding, and one natural-language **brief** (stage, motion, audience, approach — anything), plus optional uploaded supporting documents. A one-time research job then produces the template's artifact set: 1. **Offer research pack** — markdown documents (canon, competitors, objections, benchmarks, plus scraped sources and your uploads) reused by every run, so the seller is never re-researched per prospect. 2. **Document template** — the Jinja HTML template runs render through. 3. **Payload schema** — a per-template JSON Schema whose field descriptions guide generation. There is no approval step: research (or an artifact edit in the console) finishing is the release. Each org template exposes `template_state`: `ready` and `draft` templates run; `researching` and `research_failed` fail the run with `409 playbook_template_not_ready` (not retryable — wait for research or retry it) only while nothing is live yet. Re-running research over a live template requires an explicit refresh because research is paid work; the live version keeps serving until the new one lands. ## Request inputs Provide at least one of `target_company` or `target_company_domain`. A domain must be a hostname such as `acme.example`, without a scheme or path. | Field | Requirement and allowed values | |---|---| | `target_company` | Optional non-empty company name; required when the domain is omitted. | | `target_company_domain` | Optional valid hostname; required when the name is omitted. | | `anchor_company` | Optional seller name, up to 160 characters. Defaults from the selected brand profile. | | `product_info` | Optional seller/product context, up to 12,000 characters. | | `tone` | `consultative` (default), `direct`, or `technical`. | | `model` | `default`; this is the only current value. | | `playbook_template_key` | Optional template key from `GET /v1/playbook-templates`; see [Playbook templates](#playbook-templates). | | `stage` | Optional deal stage, any short lowercase slug such as `discovery` or `renewal`. Defaults from the selected template. A catalog template key must agree with it when both are sent. | | `offer_id` | Optional active [Offer](https://engine.neraperla.com/docs/offers) whose value propositions and proof points guide generation. | | `campaign_id` | Optional [Campaign](https://engine.neraperla.com/docs/campaigns) to frame the playbook; its offer is used when `offer_id` is omitted. | | `intelligence` | Optional model tier for the generation agents: `low`, `medium`, `high`, or `ultra`. Defaults from the selected playbook template, else `high`. Higher tiers are charged more and research and write better. | | `sections` | One to ten unique section values. Omit it for the complete result. | | `brand_profile_id` | Optional organization brand-profile ID. When neither brand selector is sent, the selected organization template's brand is used, then the project's `default_brand_profile_id`, then the organization's default brand. See [Give each client its own brand](https://engine.neraperla.com/docs/projects#give-each-client-its-own-brand). | | `brand_profile_key` | Optional stable brand-profile key. If both selectors are present, they must identify the same profile. | Allowed `sections` values are `summary`, `objective`, `value_props`, `sales_angles`, `personas`, `services`, `tech_stack`, `integrations`, `objections`, and `meeting_note`. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/playbooks" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: playbook-20260714-acme" \ --header "Content-Type: application/json" \ --data '{ "target_company_domain": "acme.example", "anchor_company": "Northstar Analytics", "product_info": "Revenue-intelligence software for enterprise sales teams.", "tone": "consultative", "sections": ["summary", "sales_angles", "personas", "objections"], "model": "default" }' ``` This is OpenAPI operation `create_playbook_v1_playbooks_post` with request schema `PlaybookInput` and response schema `PublicPlaybookJobResponse`. Generate a unique `Idempotency-Key` before the first attempt and retain it until the job ID is safely stored. The same key and normalized input replay the original response for 24 hours. Reusing it with different input returns `idempotency_key_reused`. Common create failures are `capability_disabled`, `insufficient_credits`, `quota_exceeded`, `budget_exceeded`, and `project_archived`; `playbook_template_not_found` and `playbook_template_not_ready`; `offer_not_found`, `offer_archived`, and `campaign_not_found`; and, for the brand, `brand_profile_not_found`, `brand_profile_mismatch`, `brand_profile_not_ready`, and `brand_profile_archived`. A project whose `default_brand_profile_id` has been archived refuses runs that name no brand with `409 brand_profile_archived` rather than falling back to the organization's default. Follow [Errors and retry decisions](https://engine.neraperla.com/docs/errors). Canceling a playbook from the web console does not stop its generation. The job turns `canceled` at once and returns no result or document, but it is charged in full when the generation finishes. ## Interpret a successful result When `status` is `succeeded`, `result` is a `PublicPlaybookResult`. Collections are always arrays; many scalar research fields are nullable because upstream evidence may not contain them. | Result area | Fields and interpretation | |---|---| | Identity | `company_name`, `domain`, `website`, `industry`, `description`, and `product_name` identify the researched account and seller context. | | Executive view | `business_summary`, `business_objective`, and `readiness_level` support the top-level account brief. | | Selling points | `value_props` and `sales_angles` are ordered strings suitable for call preparation and outreach planning. | | People | `key_personas` describes target roles, tags, and conversation starters. `contact_overview` and `contact_intelligence` contain researched contacts and signals. | | Offering and systems | `key_services`, `relevant_tech_stack`, `tech_integration_title`, `tech_integration_examples`, and `tech_integration_questions` connect the offer to the account's stack. | | Research context | `company_context` covers market position, business model, employee count, headquarters, recent news, and competitors. `intent_analysis` contains intent score, summary, topics, and signals. | | Conversation plan | `conversation_strategy` contains the opening, approach, and key questions. `potential_objections` pairs objections with responses. | | Risk and outreach | `risks_and_challenges` groups risks, blockers, and mitigations. `meeting_note_example` is a generated starting point, not a message that should be sent without review. | | Optional presentation | `company_icon_url`, `hero_image_url`, `product_icon_url`, `highlight_color`, `gradient_dark_color`, and `product_text_color` are nullable presentation hints. Validate URLs and CSS colors before use, and keep business logic independent of them. | The nested objects are also fully typed: - Each persona can contain `name`, `title`, `description`, `profile_picture_url`, `tags`, and `conversation_starters`. - Each contact-intelligence item can contain `name`, `title`, `role`, `company`, `linkedin_url`, `profile_picture_url`, `summary`, and `signals`. - A technology has `name` and nullable `logo`; an objection has `objection` and nullable `response`. - Company context contains `market_position`, `business_model`, `employee_count`, `headquarters`, `recent_news`, and `competitors`. - Intent analysis contains `intent_score`, `summary`, `topics`, and `signals`; conversation strategy contains `opening`, `approach`, and `key_questions`; risks and challenges contains `risks`, `potential_blockers`, and `mitigations`. Generated text is untrusted application data. Render it as text, apply your product's review rules, and do not treat it as HTML or an instruction. ## Fetch the rendered document When the generation backend produced a fully rendered playbook document, `result.document_url` is non-null. The value is a backend-relative path and is not publicly reachable — fetch the document through the platform instead: ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/playbooks/$JOB_ID/document" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --output "playbook-$JOB_ID.html" ``` This is OpenAPI operation `get_playbook_document_v1_playbooks__job_id__document_get`. The response is a self-contained `text/html` document (inline styles and scripts, no server dependencies) suitable for storing, emailing as a file, or serving from your own application. Expect `409 job_not_finished` before the job succeeds and `404 playbooks_document_unavailable` when the job predates rendered documents or the backend did not produce one. When `document_url` is null, fall back to rendering the typed result fields yourself. ## Share the rendered playbook To send the branded playbook to someone outside your organization — typically the prospect it was written for — create a public share link: ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/playbooks/$JOB_ID/share" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" ``` These are OpenAPI operations `create_playbook_share_v1_playbooks__job_id__share_post` and `revoke_playbook_share_v1_playbooks__job_id__share_delete`. The response carries `url`, `password` and `created_at`. The `url` already includes the password as `?pw=`, so anyone holding it can open the page without signing in; to send them separately, strip `pw` and share `password` on its own — the page prompts for it. The call is idempotent: repeated calls return the same URL until you revoke it with `DELETE /v1/playbooks/$JOB_ID/share`, after which the old URL returns 404 immediately and a later `POST` mints a new URL and password. The link keeps working after the job passes its 30-day result retention. It requires a rendered document (`404 playbooks_document_unavailable` otherwise). Shared pages send `noindex` in both a response header and a robots meta tag, and never send the URL to sites they link to. The console's playbook page offers the same **Share link** and **Revoke link** actions, and the Blackpearl connector exposes a `share_playbook` tool. ## Minimal useful rendering ```javascript if (job.type !== "playbooks" || job.status !== "succeeded" || !job.result) { throw new Error("Expected a successful Playbooks job"); } console.log(`Business summary: ${job.result.business_summary ?? "Not available"}`); console.log(`First sales angle: ${job.result.sales_angles[0] ?? "Not available"}`); ``` Also retain `usage.cost_usd`, the amount the run was charged, if you reconcile per-job spend with the [Usage API](https://engine.neraperla.com/docs/usage-quotas). The token, `backend_requests`, and `backend_runtime_ms` fields are retained for compatibility and are always `0`. --- # Playbooks integration kit > Run the standalone reference product or import an OpenAPI-derived request collection. Canonical guide: Raw Markdown: OpenAPI: The integration kit is a complete, server-side Playbooks example plus request tooling generated from the same OpenAPI contract as the API reference. It uses only public HTTP behavior and published types; it has no dependency on gateway or console internals. ## Standalone reference product The [reference app source](https://engine.neraperla.com/docs/integration-kit/reference-app/src/index.ts), [package file](https://engine.neraperla.com/docs/integration-kit/reference-app/package.json), [lockfile](https://engine.neraperla.com/docs/integration-kit/reference-app/package-lock.json), and [TypeScript configuration](https://engine.neraperla.com/docs/integration-kit/reference-app/tsconfig.json) form the complete sample. Download those files into the same layout, then run: ```bash npm ci export BLACKPEARL_API_BASE_URL="https://engine.neraperla.com" export BLACKPEARL_API_KEY="replace-with-your-development-project-key" npm run serve ``` Open `http://127.0.0.1:8787` after the command reports success. The browser receives rendered result text, never the project key. The app sends no `Blackpearl-Project` header, so give it a project key. The app persists its exact request, idempotency key, job ID, latest typed job, and successful result in `.blackpearl-reference/state.json`. Restarting resumes an active job or renders the stored result without creating new work. Use `npm run reset` only when you intentionally want a new job. The implementation demonstrates: - Bearer authentication read only from the server environment. - An idempotency key persisted before the first POST and reused with identical input after an ambiguous transport failure. - A job ID persisted before bounded polling, with restart-safe resume. - Two-second initial polling and exponential backoff with jitter capped at ten seconds. - Separate handling for transient `rate_limit_exceeded`, non-retryable `quota_exceeded` and `budget_exceeded`, authentication errors, failed/canceled jobs, and `410 job_expired`. - Runtime validation before rendering `business_summary`, `sales_angles`, and `value_props`; generated text is HTML-escaped. The same `run` command targets any gateway whose Playbooks backend is configured, including an isolated local service or a hosted development project. Calls perform real capability work and record real usage; an unconfigured backend fails closed. ## Postman collection Download the [Blackpearl Public API Postman collection](https://engine.neraperla.com/docs/integration-kit/blackpearl-public-api.postman_collection.json), import it, and set its `baseUrl` and `apiKey` collection variables. Set `idempotencyKey` to a unique retained value before a job-creation request. If a create response is ambiguous, resend the unchanged request with that same value. The collection contains every current public OpenAPI operation, HTTP method, path and query parameter, `Idempotency-Key` and `X-Request-ID` header, JSON request example, and documented success status. It does not add the `Blackpearl-Project` header: use a project key as `apiKey`, or, with a company-level key, add `Blackpearl-Project` with the project's id or slug yourself (see [Authentication](https://engine.neraperla.com/docs/authentication)). Its metadata records the exact OpenAPI document version and SHA-256 digest. `make integration-kit-check` regenerates it in memory and fails on contract drift. ## Client support policy The [Python and TypeScript quickstarts](https://engine.neraperla.com/docs/getting-started#python-and-typescript-versions) and this product are deliberately dependency-light reference clients, not supported SDK packages. Broad official SDK generation remains deferred until API stability and adoption justify the compatibility and release burden. Their automated tests use explicit test-only HTTP fixtures; the shipped clients contain no simulation path. --- # Documents > Turn a brief, Brand Pack, and optional Offer into downloadable PPTX, DOCX, or PDF files. Canonical guide: Raw Markdown: OpenAPI: Documents is a GA generation capability for finished sales collateral. It runs a managed document agent asynchronously and stores the resulting files with the Job. It does not create account dossiers: the separate Company Dossier Specifications operations remain Preview planning contracts. ## Create a document Job Operation `create_document_job_v1_documents_post` accepts `POST /v1/documents`. `brief` is required and describes the artifact, audience, and content. The other inputs constrain or enrich the run: | Field | Behavior | |---|---| | `document_type` | Optional `proposal`, `playbook`, `deck`, `gtm_strategy`, `report`, or `one_pager`. The agent chooses when omitted. | | `format` | Optional `pptx`, `docx`, or `pdf`. The agent chooses when omitted. | | `target_domain` | Optional focus-account domain. Schemes, `www.`, and paths are normalized to a bare domain. | | `brand` | Optional Brand profile ID or key. When omitted, the project's `default_brand_profile_id` is used, then the organization's default Brand. See [Give each client its own brand](https://engine.neraperla.com/docs/projects#give-each-client-its-own-brand). | | `offer` | Optional Offer ID or key whose value propositions, proof points, pricing, ICP, and stage fit are attached. | | `template_urls` | Up to three HTTP(S) reference documents whose structure, tone, and layout should be followed. | | `title` | Optional title retained with the Job and result. | | `external_ref` | Optional caller correlation value echoed in the result. | The selected Brand must have a completed guideline so the platform can freeze its Brand Pack into the run. If the project's default brand has been archived, a request that names no `brand` fails with `409 brand_profile_archived` rather than using the organization's default. An attached Offer must be active and belong to the same organization. ```bash JOB=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/documents" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: document-20260720-acme-proposal" \ --header "Content-Type: application/json" \ --data '{ "brief": "Create a first-meeting proposal for Acme RevOps. Lead with pipeline visibility, explain our 90-day rollout, and close with pricing.", "document_type": "proposal", "format": "docx", "target_domain": "acme.example", "brand": "northstar", "offer": "analytics_suite", "template_urls": ["https://cdn.example/templates/enterprise-proposal.docx"], "title": "Acme RevOps proposal", "external_ref": "crm-account-123" }') JOB_ID=$(printf '%s' "$JOB" | jq -er '.id') ``` The endpoint returns `202 Accepted` with a typed `DocumentJobResponse`. Generate and persist the `Idempotency-Key` before the first attempt. Matching retries within 24 hours replay the original response; using the key with changed input returns `idempotency_key_reused`. ## Poll and interpret the result Poll `GET /v1/jobs/{job_id}` using the bounded flow in [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs). The `documents` Job variant retains the normalized input, three execution stages, usage, and a typed result after success. The result contains: - `files`: stored file references with `file_id`, `filename`, `format`, `size_bytes`, and an informational Console download path; - `brand` and optional `offer`: the exact selling context resolved for the run; - `progress`: up to 50 curated agent milestones; - `duration_seconds`, `request_echo`, `title`, `target_domain`, and `external_ref` for traceability (`model` is retained for compatibility and is always `null`). The Job's `usage.cost_usd` reports the amount the run was charged. A succeeded Job can contain more than one file. Treat generated claims and downloaded content as reviewable application data, not publishing or outreach authority. If document generation is not configured, the Job fails closed with a configuration error and produces no synthetic file. ## Download files Operation `download_document_job_file_v1_documents__job_id__files__file_id__get` returns `GET /v1/documents/{job_id}/files/{file_id}`. Use the IDs from the successful Job result: ```bash COMPLETED_JOB=$(curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/jobs/$JOB_ID" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY") FILE_ID=$(printf '%s' "$COMPLETED_JOB" | jq -er '.result.files[0].file_id') curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/documents/$JOB_ID/files/$FILE_ID" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --output acme-proposal.docx ``` The response is the raw file with a format-specific `Content-Type` and an attachment filename. Unknown formats use `application/octet-stream`. Files share the Job's 30-day retention window and are visible only to the owning project. Common create failures are `capability_disabled`, `insufficient_credits`, `quota_exceeded`, `budget_exceeded`, `project_archived`, `brand_not_found`, `brand_profile_archived`, `brand_profile_not_ready`, `brand_guideline_missing`, `offer_not_found`, and `offer_archived`. A missing or cross-project Job or file returns `not_found`. Follow [Errors and retry decisions](https://engine.neraperla.com/docs/errors) and never repeat an ambiguous create request without its original idempotency key. ## Preview dossier planning contracts **Specification preview** — this surface accepts and stores typed plans; execution is not yet available. Storing a dossier specification never produces a dossier. Company Dossier Specifications remain Preview and contract-only. They freeze a target company, connector revision, requested sections, collection budgets, purpose, and policy version; they perform no provider request, research, model call, or rendering. Preview operation `create_company_dossier_specification_v1_company_dossier_specifications_post` creates an immutable plan. Preview operation `list_company_dossier_specifications_v1_company_dossier_specifications_get` lists plans with cursor pagination. Preview operation `get_company_dossier_specification_v1_company_dossier_specifications__specification_id__get` reads one plan. Do not interpret a stored dossier specification as collected evidence, generated collateral, permission to crawl a site, or authorization to publish. --- # Message Templates > Turn approved GTM context and prospect evidence into quality-gated, approval-only outreach copy. Canonical guide: Raw Markdown: OpenAPI: Message Templates creates reusable structural email revisions and personalized prospect drafts. It is deliberately approval-only: every response reports zero messages enqueued and sent, and the capability has no provider-delivery, tracking, attachment, or CRM-write authority. ## Generate a template revision `generate_message_template_revision_v1_message_template_revisions_generate_post` starts `POST /v1/message-template-revisions/generate`. Send an `Idempotency-Key`, a focused audience and objective, an approved offer or offer summary, and the desired next step. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/message-template-revisions/generate" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: revops-template-20260717" \ --header "Content-Type: application/json" \ --data '{ "template_key": "revops-first-touch", "name": "RevOps first touch", "language": "en-nz", "audience": "Revenue operations leaders at B2B software companies", "objective": "Start a relevant discovery conversation", "offer_summary": "Reduce manual forecasting work and surface account risk earlier", "desired_next_step": "a short comparison", "options": { "tone": "direct", "locale": "New Zealand English", "max_words": 90, "max_links": 0, "forbidden_claims": ["guaranteed outcomes"] }, "reason": "Create the governed first-touch baseline for review." }' ``` The response is a typed asynchronous job with `type: "message_templates"`. Poll it as described in the [Jobs guide](https://engine.neraperla.com/docs/jobs). A successful result has `status: "DRAFT_READY"`, the next immutable revision, and a 100-point rubric covering relevance, evidence, clarity, recipient value, CTA, trust, and mobile readability. The server converts only its allowlisted placeholders into the closed template structure and saves nothing below the quality threshold. You can also create an already-reviewed closed structure through `create_message_template_revision_v1_message_template_revisions_post`, list revisions with `list_message_template_revisions_v1_message_template_revisions_get`, inspect one with `get_message_template_revision_v1_message_template_revisions__revision_id__get`, and render exact escaped text/HTML through `render_message_template_revision_v1_message_template_revisions__revision_id__render_post`. ## Personalize a retained prospect `generate_prospect_message_v1_message_template_revisions__revision_id__prospect_message_post` starts `POST /v1/message-template-revisions/{revision_id}/prospect-message`. Select one prospect from an unexpired succeeded Prospecting job and provide sender/reply/postal identity plus the exact retained evidence and policy references. The caller cannot declare policy approval or suppression state. For real-recipient copy, the platform requires the exact policy reference and version in its operator-controlled allow-list, verifies basis and address-provenance IDs against the prospect's retained qualification/enrichment evidence, derives the address-source class from that evidence, and checks the project/environment Outcome ledger for an unsubscribe. It returns those facts in `compliance_verification`. Identity, evidence, sender, offer, next-step, company/jurisdiction, and privacy-notice gates still fail closed. The result status is: - `DRAFT_READY` when every real-recipient gate and quality check passes. - `NEEDS_INPUT` when required context is incomplete. - `BLOCKED` for a platform suppression match, rejected qualification, or non-demo synthetic use. - `DEMONSTRATION_ONLY` for any explicitly requested preview; synthetic data always requires it. Personalization makes no model request. `NEEDS_INPUT` and `BLOCKED` return no subject or body. A passing request maps governed retained values to the selected revision's declared variables and uses the deterministic renderer, producing exactly one selected-revision subject. The server validates the complete returned subject/body for evidence and approved-value anchors, recipient relevance, numeric claims, word and link limits, one CTA, mobile structure, prohibited language, and the canonical final opt-out notice. Missing or unsupported required variables return `NEEDS_INPUT`. ## Usage, charges, and safe downstream handling Each template-generation run is captured in a durable billing outbox. The job becomes successful only after its charge, usage, result, and immutable revision are durably settled; scheduler retries do not repeat the generation. Job `usage.cost_usd` and the Costs page report the amount charged. A revision's `generation_model` and `generation_provider_requests` are retained for compatibility and are always `null` and `0`. Personalization is not charged. See [Usage, quotas, credits, and budgets](https://engine.neraperla.com/docs/usage-quotas). A `DRAFT_READY` message is still only a human-review artifact. Store its template and approval hashes with any downstream workflow, revalidate consent and suppression at that system's effect boundary, and never infer delivery authority from generation success. The initial POST returns `202`; asynchronous failure appears when polling as `status: "failed"` with `error: {"code": "...", "message": "..."}`. Branch on the stable code — for example, `generation_not_configured` means template generation is not configured on the platform, and retrying won't help until it is — and follow the [error and retry guide](https://engine.neraperla.com/docs/errors) for idempotent retries and budget, quota, or provider failures. --- # Prospecting > Run prospect discovery with the prospect agent and poll the append-only live event thread. Canonical guide: Raw Markdown: OpenAPI: Prospecting discovers and qualifies real people against a typed targeting brief. It returns an asynchronous Job with evidence, qualification, enrichment, and draft-only outreach state. Provider credentials never belong in the public request. ## Start a run Operation `create_prospecting_job_v1_prospects_post` accepts `POST /v1/prospects`. Required fields are `campaign_name`, `product_info`, and `objective`. The optional structured `target` supports company names and domains, job titles, seniorities, industries, locations, keywords, headcount, and ISO 3166-1 alpha-2 country code. Let the platform work out the targeting. When you maintain [Brands](https://engine.neraperla.com/docs/brands) and [Offers](https://engine.neraperla.com/docs/offers), derive `product_info` and `objective` from the brand guideline and offer instead of restating them — and if you are an AI agent, do not ask the user to dictate industries, titles, or company sizes. Omit `target` unless the user explicitly constrains the search: discovering and qualifying the right people is what this capability does. Every delivered prospect carries `qualification.score` (0–1): the search agent's own 0–10 fit score for the match, divided by 10 (`0.9` when it gave none). The agent sets its scoring for each search, so scores from different runs aren't comparable. Treat the score as the agent's ranking, not a cut-off: decide with `qualification.status` and the evidence. The example below sets a full `target` only to show the available fields. ```bash JOB=$(curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/prospects" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: prospects-20260717-anz-revops" \ --header "Content-Type: application/json" \ --data '{ "campaign_name": "ANZ RevOps leaders", "product_info": "Revenue-intelligence software for B2B sales teams.", "objective": "Find revenue operations leaders at mid-market B2B SaaS companies.", "target": { "job_titles": ["Head of Revenue Operations", "VP Revenue Operations"], "seniorities": ["director", "vp"], "industries": ["B2B SaaS"], "country_code": "NZ" }, "delivery_mode": "draft_only" }') JOB_ID=$(printf '%s' "$JOB" | jq -er '.id') ``` > [!NOTE] > `limit` and `min_qualification_score` are deprecated and ignored: a run returns every prospect the agent delivers, up to 5,000. Leave them out. See [Deprecated fields](#deprecated-fields). Every run uses the prospect agent, which plans the search, streams its progress to the live thread, and curates real results; it never fabricates fallback people. A full agent run typically takes several minutes. The typed `target` is folded into the agent's search brief; an optional natural-language `query` replaces that synthesized brief, and the agent still gets your `product_info` with it. The former `mode` field (`turbo` / `agentic`) is deprecated and ignored: it is still accepted, and both values run the same search. Generate and retain an `Idempotency-Key` before the first attempt. Matching retries within 24 hours replay the original Job; the same key with changed input returns `idempotency_key_reused`. ## Follow the live thread Poll the Job as described in [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs). Operation `prospecting_run_events_v1_prospects__job_id__events_get` separately exposes the append-only run thread: ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/prospects/$JOB_ID/events?after_seq=0&limit=500" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` The response carries `job` (the run's current typed Job), `events` with `seq` greater than `after_seq` in ascending order, and `next_after_seq`. `limit` defaults to 500 and is capped at 2,000. Persist `next_after_seq` and pass it as the next `after_seq` so reconnects fetch only newer events. Event polling does not replace Job polling: the Job remains the authority for terminal status and the final typed result. Each event has `seq`, `type`, `data`, and `created_at`. The `data` fields depend on `type`, and any field can be absent: | `type` | `data` | |---|---| | `task_status` | `label`: the step the agent is on. | | `text` | `text`: the agent's narration, grouped into readable messages. | | `search_topics` | `topics` or `value`: what the agent is searching for. | | `lead` | `company_name`, `domain`, and `contacts` (each with the contact's name and title): a company the agent found. | | `table` | `title`, `message`, `totalCount`, `validCount`, `resultCount`: the agent produced its results table. | | `complete` | `total_count`, `valid_count`, `satisfied_early`, `message`: the search finished. | | `stopped` | `message`: the search was stopped. | | `error` | `message`, always `The search reported an error.` The Job's `error` explains the outcome. | | `suggestions` | `value`. Safe to ignore. | | `result` | `title`. Safe to ignore. | Any other type has an empty `data`; ignore types you don't handle. `lead` events are a live preview, and the counts in `table` and `complete` are the agent's own: the Job result is the list of prospects the run delivered. Treat every contact detail as unverified: the search does not verify contacts, emails, or phone numbers, and the agent's prose is served without claims that it did. ## When a run delivers nothing A run that delivers no prospects succeeds, and is charged, only when the agent finished a search and found no matches. Otherwise it ends `failed` and is not charged: when the run was interrupted before it returned results, when the search finished but its results could not be retrieved, or when the agent replied without running a search. The Job's `error` message explains which (`error_code` is `null`), and you can run the same request again with a new `Idempotency-Key`. ## When a run is canceled The API has no cancel operation; a run can be canceled from the web console. A canceled run ends `canceled` and returns no result. It stops its search and is charged for the work done before the cancel; a run canceled before its search started, for example while it was still waiting to start, is not charged. See [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs#ownership-and-billing) for when the charge appears. ## How many prospects you get A run returns every prospect the agent delivers, up to 5,000. The agent builds the full list it can find, as it does for searches in its own app (typically well over a hundred prospects), and a run is priced for the whole search, not per prospect. There is no setting for how many you get: `limit` is deprecated and ignored. For more prospects from the same search, create a [continuation](https://engine.neraperla.com/docs/prospecting-extensions); its `additional_prospect_limit` is the most new prospects the continuation returns. Each contact is one prospect. Through the Claude connector, `get_job_results` returns a prospecting result's prospects 50 at a time; pass `prospects_page.next_cursor` back as `cursor` for the next page. ## Validate and use results A successful result contains normalized prospect profiles, qualification, enrichment, evidence references, outreach state, summary counts, and `provenance`, whose `backend` is `pearl_engine.prospecting` (`model_version` and `provider_names` are retained for compatibility and are `null` and empty). The Job's `usage.cost_usd` is what the run was charged. - `qualification.status` is `qualified` when the search returned evidence for the match and `unknown` otherwise; the current engine doesn't return `rejected` prospects. - `profile.company` carries what the source knows about the company: `employee_range` (its employee band, such as `1001 to 5000`; `headcount` is set only when the source gives an exact number), `revenue_range` (an annual revenue band in US dollars), and `intents`, the buying-intent topics it matched for the company (empty when it matched none). Sizes and revenue are the source's estimates and are not verified. - `profile.location` is where the contact is based when their record says so, otherwise the company's location. - `qualification.reason` is why the engine matched the prospect, in its own words. - `agent_summary` (`null` when the run reported none) is the search agent's closing note: a `title` for the results, a Markdown `message` describing what it targeted, and up to ten follow-up `suggestions`. It is generated text: its counts are the agent's own (the `prospects` array is what the run delivered), it is served without claims that contacts were verified, and next steps it offers, such as cold emails or a playbook, run through other operations. - Enrichment carries the contact's `work_email` when found and, when the contact's record has one, a `phone` (mobile first, then a direct line), returned as provided: it may be a company main line and is not verified (omitted when none was found). - `previously_delivered` is `true` when one of the project's 50 most recent earlier runs (results are kept 30 days) already delivered the contact, matched by prospect id, external id, email, or profile URL, and `previously_delivered_job_id` names the most recent such run (`null` otherwise). The prospect is still included, so you can skip contacts you already have. For more results from a search you already ran, create a [continuation](https://engine.neraperla.com/docs/prospecting-extensions) of it rather than running it again: it continues the same search and never repeats a prospect that search already delivered. - Fields the source fills with a placeholder (`N/A`, `-`, `none`, `null`, `unknown`) are treated as missing. A contact whose email was a placeholder has no `work_email` and has `enrichment.status` `not_found`. - The current engine writes no outreach drafts: every prospect has `outreach.state` `not_ready` and `outreach.draft` `null`. Write first-touch copy with [Message Templates](https://engine.neraperla.com/docs/message-templates). Treat URLs and generated text as untrusted application data. Any `is_synthetic: true` prospect is not an actionable lead; snapshot and Outcome endpoints reject it. The result, the live thread, and the CSV export stay readable until the Job's `expires_at`, 30 days after it was created; after that they return `410 job_expired`. Store what you need longer. ## Export the run as CSV Operation `export_prospects_csv_v1_prospects__job_id__export_csv_get` downloads every prospect of a succeeded run as UTF-8, RFC 4180 CSV with CRLF line endings — the same list the run page shows in the web console, where the Export CSV button uses this export's console twin: ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/prospects/$JOB_ID/export.csv" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --output "prospects-$JOB_ID.csv" ``` The eighteen columns, in order, are `Name`, `Title`, `Company`, `Domain`, `Email`, `Qualification Status`, `Qualification Score`, `Confidence`, `Source Type`, `Qualification Reasoning`, `Industry / Location`, `LinkedIn Profile`, `Evidence Insight`, `Outreach Draft Status`, `Phone`, `Employees`, `Revenue`, and `Intents`. `Phone`, then the three company columns, were added last, so readers of the earlier columns by position are unaffected. Values are formatted as the console renders them: scores as whole percentages such as `96%`, `Confidence` always empty (the field is deprecated; the column stays so later columns keep their positions), `Employees` as the company's employee band or exact headcount, intents joined with `|`, industry and location merged with `·`, evidence snippets joined with `|`, and a human-readable outreach draft status sentence. Rows follow the result's prospect order, so repeated exports of one run are byte-identical. Cells whose first meaningful character is `=`, `+`, `-`, or `@` receive a leading apostrophe to neutralize spreadsheet formulas. A run that has not succeeded returns `not_ready`; treat exported names, emails, and generated text as personal or untrusted application data. Never infer fit from provider failure, missing email, or silence. Keep operational failures separate and record observed downstream facts through [Outcomes](https://engine.neraperla.com/docs/outcomes). Bounded continuations and reusable qualification policies are [Preview extensions](https://engine.neraperla.com/docs/prospecting-extensions), not part of the GA workflow. ## Deprecated fields These fields will be removed in a future API version, announced in the API changelog. Until then they are still accepted or returned, so existing integrations keep working, but don't rely on them: | Field | What it does now | |---|---| | `limit` (request) | Ignored. It doesn't change the search or cap the result. | | `min_qualification_score` (request) | Ignored. No prospect is dropped for its score. | | `qualification.confidence` | Always `null`. Use `qualification.score` and `qualification.status` instead. | | `enrichment.confidence` | Always `null`. Emails aren't validated, so treat every `work_email` as unverified. | | `evidence[].confidence` | Always `0.75` (`0.7` for a match rationale): a placeholder, not a measurement. | Results from before the deprecation can still show placeholder confidence values until they expire. --- # Prospecting extensions > Explore bounded continuation Jobs and immutable qualification rubrics without treating either contract as GA. Canonical guide: Raw Markdown: OpenAPI: These Prospecting extensions are Preview. They are useful for integration testing, but their contracts may change incompatibly. Build the GA workflow around [Prospecting](https://engine.neraperla.com/docs/prospecting), Jobs, and Outcomes first. ## Create a bounded continuation Preview operation `create_prospecting_continuation_v1_jobs__parent_job_id__continuations_post` creates one immutable child of a succeeded real Prospecting Job. It does not mutate or resume the parent. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/jobs/$PARENT_JOB_ID/continuations" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data '{ "continuation_key": "more-anz-revops-20260717", "additional_prospect_limit": 20, "max_rounds": 2, "min_new_prospects_per_round": 1 }' ``` Use a continuation to get more results from a search you already ran, instead of running the same search again. A continuation of a run made by the prospect agent continues in that run's own search: each round is a follow-up asking the agent for that many more new prospects, with the companies the search already delivered listed as excluded. The child returns only prospects that search hasn't delivered (through the original run or any continuation of it), at most `additional_prospect_limit` of them. Rounds stop when the child has `additional_prospect_limit` new prospects (`target_reached`), when a round finds fewer than `min_new_prospects_per_round` (`min_new_prospects_not_met`), after `max_rounds` or when another round could not finish within the run's time limit (`max_rounds_reached`), or when a round is interrupted (`provider_unavailable`). Each round takes as long as a run, typically several minutes. The child's `research` trace reports each round, and it is charged like a run for the search work of every round. A continuation that finds nothing new fails and is not charged. A search runs one continuation at a time: creating another while one is queued or running returns `409 prospecting_continuation_in_progress`. To keep going, continue the child once it finishes. The parent and bearer key must share project and `live`/`test` environment. A company-level key needs no `Blackpearl-Project` header: the parent run selects the project, and the continuation is charged there. The parent must be a succeeded Prospecting Job with a valid normalized, non-synthetic result. The child binds the parent ID, result hash, normalized result snapshot, connection revision, and constraints so later changes cannot alter its provenance. Reusing the continuation key with the same request replays the child; changed constraints conflict. ## Store qualification policy contracts **Specification preview** — this surface accepts and stores typed plans; execution is not yet available. No scorer exists: storing a policy never scores a prospect. Preview operation `create_qualification_policy_v1_qualification_policies_post` stores an immutable five-dimension rubric. A policy freezes its target taxonomy, exact integer weights, evidence and freshness rules, score bands, and expected policy version. It does not score prospects or authorize downstream action. Preview operation `list_qualification_policies_v1_qualification_policies_get` lists policies in the current project and environment with cursor pagination. Preview operation `get_qualification_policy_v1_qualification_policies__qualification_policy_id__get` reads one policy. Use the returned policy hash when a future executor requires optimistic binding; never infer that creating a policy means a scorer is available. Preview resources should remain isolated behind a feature flag and observability boundary. Do not persist assumptions about their schema into irreversible workflows. --- # Infinite Intent > Run an intent-driven audience programme, follow the run's progress and open the interactive results page in your browser. Canonical guide: Raw Markdown: OpenAPI: ## Use Infinite Intent In a connected Claude session, say: ```text Find leads for World of Claudecraft using Infinite Intent. ``` or upload an intent file and describe the activation, for example: ```text Attached is an intent file of people registering interest in "coastal retreat" keywords. Which part of the list should get "Book Now" discount offers? ``` Two programmes exist today. `world-of-claudecraft` delivers the World of Claudecraft audience report from the configured audience dataset, intent signals, recorded contact checks and qualification notes. `coastal-retreat` activates a client-supplied intent file of hashed emails (HEMs) against the coastal-retreat intent graph and scores each identity on the L0–L4 purchase funnel. A programme must be enabled for the key's project. Research dates describe the underlying data; run timestamps describe delivery of the page. Connected Claude sessions using the Blackpearl custom connector can start runs with the `run_infinite_intent` tool (passing the uploaded file's name and row count) and poll with `get_job_status`; API-key sessions use the endpoints below. ## Agent procedure 1. Reuse the session's working `BLACKPEARL_API_KEY`. If connection is needed, follow [agent setup](https://engine.neraperla.com/docs/agent-setup). Do not display the key. 2. Check `GET /v1/capabilities` for `infinite_intent` with `enabled: true`; the capability description names the programmes enabled for this project. Start immediately when the user requests an enabled programme; no extra interview, planning approval or skill installation is needed. If absent, explain that this project needs access; do not replace keys or substitute a paid capability. 3. When the user uploaded an intent file, count its data rows and pass `audience_file` with the filename and hashed-email count — progress milestones echo them. Never paste file contents into the request, and do not analyze the file locally: hashed email identifiers carry no readable signal, so segments and geography cannot be derived from the file itself. Do not ask clarifying questions before starting — the completed report contains the funnel, segment and geography breakdowns that answer targeting questions. 4. Use a unique `Idempotency-Key`, POST below, save the job ID and announce the run. 5. Poll `infinite_intent_events` at `events_url?after_seq=0` every 3 seconds; use `next_after_seq`. Share new milestone messages while the run progresses. Avoid hiding the whole run inside one long, silent command. 6. Continue through `queued` and `running`. On `succeeded`, retrieve `status_url` to get `result`. On `failed` or `canceled`, stop and report the status/error. The response's `estimated_duration_seconds` is the target execution time (277 seconds for `world-of-claudecraft`, about 10 seconds for `coastal-retreat`); queueing/deployments can add time. 7. **Open `result.report_url` in a new browser tab** using the client's browser tool or supported desktop URL opener. Give the user a clickable **View leads** link; do not download or recreate HTML. If this Claude client cannot open browser tabs, present that link and say it is ready to open; never claim a tab opened without tool confirmation. ### Start a run Operation: `create_infinite_intent`. Accepted scenarios are `world-of-claudecraft` and `coastal-retreat`; do not imply a different audience was researched. ```bash curl --fail-with-body --silent --show-error --request POST \ "$BLACKPEARL_API_BASE_URL/v1/infinite-intent" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --header "Idempotency-Key: $INFINITE_INTENT_RUN_ID" \ --data '{"scenario":"world-of-claudecraft"}' ``` For an intent-file activation, include the file summary: ```bash curl --fail-with-body --silent --show-error --request POST \ "$BLACKPEARL_API_BASE_URL/v1/infinite-intent" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --header "Idempotency-Key: $INFINITE_INTENT_RUN_ID" \ --data '{"scenario":"coastal-retreat","audience_file":{"filename":"coastal-retreat-intent-hems.csv","hashed_email_count":9847}}' ``` Accepted response (truncated): ```json {"id":"job_123","type":"infinite_intent","status":"queued","result":null} ``` On completion, `GET /v1/jobs/{job_id}` returns `result.report_url`, `report_url_expires_at`, title, `lead_count`, source and export metadata. ### Access, usage and resuming The hosted page requires the designated viewer's Blackpearl browser login. Signed-out visitors sign in and return to the page; other accounts receive 404. The URL grants no access by itself. Legacy share tokens no longer grant access. Claude's API key does not sign the browser in. Availability ends at the job's 30-day retention deadline (`report_url_expires_at`). `billing.actual_charge_usd` and `billing.credits_used` are the actual charge and credits deducted, currently zero for this programme. Do not infer a charge from lead counts. Billing status moves from `reserved` to `settled` on success or `released` on failure/cancellation. `/v1/usage` retains actual request counts and the existing account balance. To cancel, call `cancel_infinite_intent`: `POST /v1/infinite-intent/{job_id}/cancel`; repeating it is safe. For an explicitly requested HTML export, use authenticated `infinite_intent_artifact`: `GET /v1/infinite-intent/{job_id}/artifact`. ### Errors - 401: missing, invalid or revoked API key; follow [authentication](https://engine.neraperla.com/docs/authentication). - `capability_disabled` (403): the key's project needs access; do not retry blindly. - `invalid_request` (400/422): fix the scenario or required Idempotency-Key. - `conflict` (409): another run is active. Resume `error.details.job_id`. - `idempotency_in_progress` (409): retry the same POST/key shortly. `idempotency_key_reused` (409): the same key was used for different input. Identical retries reuse the job for 24 hours and return its current state. - `job_not_finished` (409): the export is available only on success. - `rate_limit_exceeded` (429): honor `Retry-After`. `quota_exceeded` (429) requires resolving the request quota. - Unknown or cross-project jobs return 404. Jobs, events and exports expire after 30 days with `job_expired` (410). The hosted page returns 410 to its authorized viewer after retention; other signed-in accounts always receive 404. - Network errors/5xx: use bounded backoff and preserve the job ID/idempotency key. Disconnecting does not cancel the run; restarts resume the persisted timeline. After ten minutes of polling, report the current state and retain the ID for resumption. Do not silently start another run. See [jobs](https://engine.neraperla.com/docs/jobs), [errors](https://engine.neraperla.com/docs/errors) and [usage](https://engine.neraperla.com/docs/usage-quotas). --- # Prospect Research > Retrieve structured company intelligence, analyze an unindexed website, and optionally add lookalikes. Canonical guide: Raw Markdown: OpenAPI: Account research is a GA synchronous lookup. It returns one typed website-intelligence record for a normalized company domain. The Prospect Research Specifications operations on this page remain separate Preview planning contracts and do not execute research. ## Retrieve an account record Operation `public_account_research_v1_account_research_post` accepts `POST /v1/account-research`: ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/account-research" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data '{ "domain": "hubspot.com", "analyze": true, "include_similar": true }' | jq . ``` `domain` is required. Schemes, `www.`, paths, queries, fragments, and a trailing dot are removed before lookup. Invalid hostnames return `invalid_domain` without recording usage. By default, an unindexed domain returns `404 account_not_found` and consumes no request unit. Set `analyze: true` to invoke the provider's on-miss website analysis, then retrieve the newly indexed record. A successful on-demand analysis consumes one additional `prospect_research` request and sets `analyzed: true`. A website that cannot be fetched returns `account_unanalyzable`; upstream analysis quota exhaustion returns `account_research_backend_quota`. Set `include_similar: true` to add up to ten `similar_companies` with normalized identity details and a similarity score from 0 to 1. Lookalikes are best-effort enrichment: provider failure produces an empty list and does not fail the account lookup. The requested domain is removed from its own lookalikes. ## Interpret and meter the result The response groups fields by purpose: | Area | Contents | |---|---| | `identity` | Name, domain, URL, summary, history, industry, structure, founders, values, and descriptive language. | | `scale` | Employee and office counts, stated users, revenue, TAM, and primary location. | | `market` | B2B/B2C posture, target customers, products, services, customers, competitors, and testimonial presence. | | `digital` | Important site URLs, social links, integrations, detected technology, languages, support, API, trial, app, content, commerce, and subscription signals. | | `signals` | AI, compliance, awards, CSR, inclusion, environmental, geographic, IP, IPO, disruption, and hiring signals. | | `contacts` | Up to ten provider-surfaced names, titles, business emails, and professional profile URLs. Fields may be null. | | `similar_companies` | Optional lookalikes requested with `include_similar`. | Also retain `domain`, `retrieved_at`, `schema_version`, `analyzed`, and `provenance`. Successful responses come from the configured research backend; an unconfigured integration fails closed instead of returning synthetic company evidence. Every successful lookup consumes one `prospect_research` request. An on-miss analysis consumes one additional request before the successful lookup. Validation, entitlement, quota, and not-found failures do not consume a successful lookup unit. Similar-company enrichment does not add a unit. Provider-derived facts can be incomplete, stale, or incorrect. Preserve provenance and retrieval time, render values as untrusted data, and review material claims before using them in generated collateral or decisions about people. ## Errors and retry behavior `capability_disabled`, `invalid_domain`, `account_not_found`, and `account_unanalyzable` require a caller or source change. `quota_exceeded` and `account_research_backend_quota` require a reset or capacity change. `account_research_not_configured` and `account_research_unauthorized` require an operator configuration fix. Retry `account_research_unavailable` or `account_research_backend_error` only with bounded backoff. See [Errors and retry decisions](https://engine.neraperla.com/docs/errors). ## Preview research-planning contracts **Specification preview** — this surface accepts and stores typed plans; execution is not yet available. Storing a research specification never runs research; only the synchronous account lookup above performs work. Prospect Research Specifications are Preview, contract-only plans. They bind reviewed Audience members to closed business-research lenses, evidence policy, and hard collection budgets. Creating one performs no web search, provider request, model call, enrichment, scoring, or generation. Preview operation `create_prospect_research_specification_v1_prospect_research_specifications_post` creates an immutable plan. Preview operation `list_prospect_research_specifications_v1_prospect_research_specifications_get` lists plans with cursor pagination. Preview operation `get_prospect_research_specification_v1_prospect_research_specifications__specification_id__get` reads one plan. Do not interpret a specification as researched evidence or use it to make claims about a person. Any future person-level executor must retain source attribution, freshness, confidence, lawful purpose, and review controls. --- # Professional Network > Bind reviewed Audience members to an official Sales Navigator connection contract without scraping or execution. Canonical guide: Raw Markdown: OpenAPI: **Specification preview** — this surface accepts and stores typed plans; execution is not yet available. No operation on this page contacts a professional network or reads any data from one. Professional Network Specifications are Preview, contract-only plans for future official-API access. They bind reviewed Audience members, an approved connector revision, display fields, purpose, and policy version. They prohibit scraping, copied cookies, password automation, private endpoints, messaging, and profile mutation. Preview operation `create_professional_network_specification_v1_professional_network_specifications_post` requires a caller key, Audience ID and exact result hash, member selection, connection binding, allow-listed display components, purpose, expected policy version, and reason. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/professional-network-specifications" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data @professional-network-specification.json ``` Preview operation `list_professional_network_specifications_v1_professional_network_specifications_get` lists specifications in the current project and environment. Preview operation `get_professional_network_specification_v1_professional_network_specifications__specification_id__get` reads one. Responses report provider execution unavailable and zero access counters. A stored connector or specification does not establish LinkedIn approval, product tier, member consent, organization role, or permission to reuse data. --- # Account Coordination > Derive an immutable account-level preflight from a reviewed Audience and its Outcome evidence. Canonical guide: Raw Markdown: OpenAPI: Account Coordination is a Preview, deterministic assessment over existing Blackpearl data. It detects risks such as contacting too many people at one account, stale evidence, restrictive feedback, and retry timing. It does not generate copy, assign a sender, create a task, mutate a CRM, or authorize contact. Preview operation `create_account_coordination_assessment_v1_account_coordination_assessments_post` binds a caller key, `audience_id`, exact Audience result hash, company domain, expected policy version, and audit reason. The Audience must belong to the current project and API-key environment. Its immutable member snapshot and relevant append-only Outcomes are evaluated atomically. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/account-coordination-assessments" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data "{ \"key\": \"acme-preflight-20260717\", \"audience_id\": \"$AUDIENCE_ID\", \"expected_audience_result_hash\": \"$AUDIENCE_RESULT_HASH\", \"company_domain\": \"acme.example\", \"expected_policy_version\": \"2026-07-15\", \"reason\": \"Preflight before external campaign review\" }" ``` An exact key/request replay returns the existing assessment; a changed request under the same key conflicts. The result preserves evidence references, derived flags, decision, and any `retry_after` bound to the assessment policy version. Preview operation `get_account_coordination_assessment_v1_account_coordination_assessments__assessment_id__get` reads one immutable assessment. Treat the decision as a preflight signal for a separately governed delivery system, never as consent or send authority. --- # Enrichment > Fill contact and company fields from the platform's data — post identifiers you hold, synchronously or as a batch of up to 1,000. Canonical guide: Raw Markdown: OpenAPI: Enrichment fills contact and company fields from the platform's own data. Post the identifiers you already hold — say, for a contact in your CRM — and get values back for exactly the fields you requested, including business-email discovery through `work_email`. Enrichment has a `level` that sets how hard the platform works: `lookup` (a direct data match) is available now; `research` and `verify` return `enrichment_level_unavailable` until they ship on these same endpoints. ## Enrich contacts synchronously Preview operation `create_enrichment_v1_enrichments_post` enriches 1–10 contacts in one call and returns the completed result in the response — no polling. Each contact needs `email`, or `linkedin_url`, or `full_name` plus `company_name` or `company_domain`. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/enrichments" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --header "Idempotency-Key: enrich-jane-1" \ --data '{ "level": "lookup", "contacts": [ { "full_name": "Jane Doe", "company_domain": "acme.example" } ], "fields": ["work_email", "person_job_title", "company_industry", "company_headcount"] }' ``` The result carries one entry per submitted contact, index-aligned. A matched contact reports `match_level` (`person`, or `company` when only the company was identified — person fields are never filled from a company-level match) and `matched_on` (the identifier that matched). Unmatched contacts return `matched: false` with no fabricated data and are never charged. Re-read a completed run with `get_enrichment_v1_enrichments__enrichment_id__get` inside the 30-day retention window. ## Enrich up to 1,000 contacts as a batch Preview operation `create_enrichment_batch_v1_enrichment_batches_post` takes the identical request shape with a larger `contacts` array and returns an accepted asynchronous run. Poll `get_enrichment_batch_v1_enrichment_batches__batch_id__get` until the run reaches a terminal state; a succeeded batch carries the same per-contact `results` array as the synchronous response. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/enrichment-batches" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --header "Idempotency-Key: enrich-crm-sync-1" \ --data '{ "level": "lookup", "contacts": [ { "email": "jane.doe@acme.example" }, { "full_name": "Alex Chen", "company_name": "Acme Corporation" } ], "fields": ["work_email", "company_industry"] }' ``` ## Fields and billing `fields` is any subset of the lookup catalog: `work_email`, `person_job_title`, `person_linkedin_url`, `company_name`, `company_domain`, `company_linkedin_url`, `company_description`, `company_industry`, `company_headcount`, `company_revenue`, `company_city`, `company_state`, `company_zip`. Fields that need a higher level — `company_latest_funding`, `work_email_verification`, `person_seniority` — are rejected at create with `enrichment_fields_unsupported`, naming the offending fields. Enrichment never returns personal emails, phone numbers, or personal locations at any level. (A [Prospecting](https://engine.neraperla.com/docs/prospecting) run can return a contact's phone number in `enrichment.phone`.) A contact bills one flat data-record fee only when its result carries a value for at least one requested field — the result's `contacts_billed` is that count. Matches that serve no requested value, unmatched contacts, and failed runs are free. Runs pass the standard admission gates and appear under the `enrichment` capability in usage and billing surfaces. --- # Data Intake > Store immutable source, selection, field, deduplication, purpose, and retention contracts without executing intake. Canonical guide: Raw Markdown: OpenAPI: **Specification preview** — this surface accepts and stores typed plans; execution is not yet available. No operation on this page uploads, processes, or moves any data. Data Intake Specifications are Preview planning records. They freeze an allow-listed source and exact version, bounded selection, requested fields, deduplication policy, declared purpose, and retention before a source executor exists. They do not upload, download, process, export, or sync records. Preview operation `create_data_intake_specification_v1_data_intake_specifications_post` creates an immutable, project- and environment-scoped specification. The request requires a caller key, source, selection, fields, deduplication rules, purpose, `retention_days`, expected policy version, and auditable reason. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/data-intake-specifications" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data @data-intake-specification.json ``` Preview operation `list_data_intake_specifications_v1_data_intake_specifications_get` lists specifications with opaque cursor pagination. Preview operation `get_data_intake_specification_v1_data_intake_specifications__specification_id__get` reads one. Responses explicitly report execution unavailable and zero I/O or processing counters. A valid specification does not establish source rights, data-subject consent, data quality, or the availability of a connector. Keep Preview resources out of production ingestion paths. --- # Site Intelligence > Run bounded, robots-respecting website crawls distilled into typed company intelligence, and store contract-only site-audit plans. Canonical guide: Raw Markdown: OpenAPI: Site Intelligence has two Preview surfaces: an executable crawl-and-extract run that turns a company website into one typed intelligence report, and the contract-only Site Audit Specification resource that freezes a future readiness audit without performing any work. ## Run a site-intelligence crawl Preview operation `create_site_intelligence_job_v1_site_intelligence_post` accepts a target website plus crawl options and returns an asynchronous job. The platform performs a bounded, robots-respecting crawl of the website's own HTTPS origin — never leaving that origin, never executing JavaScript, and never sending credentials or cookies — then a platform-managed model distills the fetched pages into one structured report. Page content is treated as untrusted evidence: instructions embedded in pages are ignored, and every populated section cites the crawled `source_urls` that evidence it. Request fields: - `website_url` (required): the target site. The crawl is pinned to this URL's HTTPS origin; a `www.` variant of the same host is treated as the same site. - `max_pages` (default 8, range 1-25): maximum HTML pages fetched, including the start page. - `max_depth` (default 2, range 1-3): maximum link depth from the start page. Depth 1 fetches only the start page. - `include_paths`: up to 20 path prefixes (each starting with `/`) crawled with priority before other discovered links. - `exclude_paths`: up to 20 path prefixes that are never fetched. - `focus_areas`: sections to prioritize. Allowed values are `overview`, `products`, `pricing`, `customers`, `technology`, `team`, `hiring`, `contact`, and `content`. Omitting the field (or null) means every section. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/site-intelligence" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --header "Idempotency-Key: site-intel-acme-1" \ --data '{ "website_url": "https://acme.example", "max_pages": 8, "max_depth": 2, "include_paths": ["/pricing"], "focus_areas": ["overview", "products", "pricing"] }' ``` The request is accepted with HTTP 202 and a typed `site_intelligence` job. Send `Idempotency-Key` so an ambiguous retry replays the original response for 24 hours. ### Poll the job Poll `get_job_v1_jobs__job_id__get` until the job reaches a terminal state (`succeeded`, `failed`, or `canceled`). The job reports the ordered stages `prepare`, `crawl`, `extract`, and `finalize`, and its `result` stays null until the run succeeds. Disconnecting the client does not stop the run; the crawl and extraction continue and the result is retained for the standard 30-day job window, after which `GET /v1/jobs/{job_id}` returns HTTP 410 with `job_expired`. Runs are bounded by server-side crawl and extraction deadlines; a run that cannot fetch the start page fails with a stable error message rather than fabricating a report. ```bash curl --fail-with-body --silent --show-error \ --request GET "$BLACKPEARL_API_BASE_URL/v1/jobs/$JOB_ID" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" ``` ### The typed report A succeeded job's `result` contains: - `crawl`: what actually happened — pages crawled and discovered, bytes received, depth reached, duration, and a bounded sample of skipped URLs with stable reasons (`robots_disallowed`, `excluded_path`, `page_limit_reached`, `depth_limit_reached`, `byte_limit_reached`, `fetch_failed`, `not_html`). - `pages`: every fetched page with its URL, title, meta description, HTTP status, link depth, and visible word count. - `intelligence`: the structured report — `company` (identity, locations, social links, published contact channels), `products`, `pricing` (model, plans, free tier and trial signals), `customers` (segments, named customers, case studies), `technology` (detected technologies and integrations), `team` (leadership and hiring signals), `content` (publishing activity), and `positioning` (value propositions, differentiators, competitors mentioned) — plus an overall `confidence` grade and explicit `limitations`. Scalar fields are null and collections empty when the site provides no evidence. Job `usage.cost_usd` reports the amount the run was charged. Crawls honor `robots.txt` disallow rules for the platform's identified crawler user agent, and a site that blocks all crawlers fails rather than being fetched anyway. Crawling a website does not prove ownership or permission; callers remain responsible for targeting sites they are authorized to analyze. ## Store a contract-only site-audit plan **Specification preview** — this surface accepts and stores typed plans; execution is not yet available. Storing an audit plan never audits a site; only the site-intelligence crawl above performs work. Site Audit Specifications remain Preview, contract-only resources. They freeze an authorized HTTPS target and allow-listed check profile for a future readiness audit. The gateway does not resolve DNS, fetch pages, execute scripts, scan infrastructure, or evaluate the site for these resources. Preview operation `create_site_audit_specification_v1_site_audit_specifications_post` requires a caller key, target, check profile, expected policy version, and auditable reason. Target validation rejects credentials, fragments, unsupported schemes, unsafe addressing, and scope outside the declared origin. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/site-audit-specifications" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data @site-audit-specification.json ``` Preview operation `list_site_audit_specifications_v1_site_audit_specifications_get` lists project/environment specifications with cursor pagination. Preview operation `get_site_audit_specification_v1_site_audit_specifications__specification_id__get` reads one. Every specification response states that execution is unavailable and reports zero fetch, evaluation, and finding counts. A stored plan does not prove site ownership or permission; callers remain responsible for explicit authorization and a future executor must revalidate the target at execution time. --- # Feedback and outcomes > Append external prospect, account, or campaign results and aggregate them across the GTM graph. Canonical guide: Raw Markdown: OpenAPI: Outcomes is the append-only feedback ledger. Your delivery, CRM, or calendar tooling records what happened; Blackpearl validates its attribution and returns deterministic aggregates. Recording an Outcome does not verify the assertion, send a message, update a CRM, or train a model. ## Record an outcome Operation `create_outcome_v1_outcomes_post` accepts exactly one logical event at `POST /v1/outcomes`. Recording requires the `feedback` capability: without it the request fails with `capability_disabled` (403) while the listing and insights reads below keep working. Call `GET /v1/capabilities` to see which capabilities are enabled, and follow [Errors and safe retries](https://engine.neraperla.com/docs/errors). ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/outcomes" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Content-Type: application/json" \ --data "{ \"source\": \"manual\", \"external_event_id\": \"meeting-20260717-018f6f\", \"type\": \"meeting_booked\", \"occurred_at\": \"2026-07-17T02:15:00Z\", \"prospecting_job_id\": \"$PROSPECTING_JOB_ID\", \"prospect_id\": \"$PROSPECT_ID\", \"campaign_id\": \"$CAMPAIGN_ID\", \"offer_id\": \"$OFFER_ID\", \"channel\": \"email\" }" ``` At least one subject is required: | Subject | Required fields | Boundary | |---|---|---| | Prospect | `prospecting_job_id` and `prospect_id` together | The Job must be a succeeded, non-synthetic Prospecting run and the prospect a real row in its result. | | Account | `account_domain` | A valid bare domain, normalized to lowercase. | | Campaign | `campaign_id` | A Campaign in the API key's project. | Optional `campaign_id`, `offer_id`, `brand_profile_id`, `audience_id`, `playbook_job_id`, and `message_template_revision_id` references are validated before insertion. A prospect subject can also carry these attribution fields. For manual events, omit `connector_id`. A non-manual `source` requires a project Connection whose provider key matches the source. Connections are currently Preview; see [Connector inventory](https://engine.neraperla.com/docs/connectors) before depending on provider ingestion. ## Taxonomy and learning safety Preference types are `qualification_approved`, `qualification_rejected`, `draft_approved`, and `draft_rejected`. Commercial types are `positive_reply`, `negative_reply`, `meeting_booked`, `sales_qualified`, `opportunity_created`, `closed_won`, `closed_lost`, and `ghosted`. Operational types are `delivered`, `bounced`, `unsubscribed`, `email_not_found`, and `provider_failed`. The server derives `classification` and whether the type is a possible `learning_candidate`. Every currently accepted row is still `verification_status: unverified` and `eligible_for_learning: false`. Operational events and `ghosted` are never learning candidates; provider availability and silence must not be mistaken for poor fit. `amount_usd_cents` is a strict integer accepted only for `closed_won`. Raw webhook bodies, credentials, prompts, message content, and arbitrary metadata are rejected. ## Idempotency and listing The idempotency namespace combines project, API-key environment, source connection or manual namespace, and `external_event_id`. An exact retry returns HTTP 200 with `idempotent_replay: true`; different normalized data under the same namespace returns `outcome_idempotency_conflict`. Operation `list_outcomes_v1_outcomes_get` lists rows newest first. Filter by type, classification, subject kind, prospecting Job, prospect, account domain, Campaign, or Offer. Use `next_cursor` unchanged and restart pagination when filters change. ## Aggregate insights Operation `outcome_insights_v1_outcomes_insights_get` groups the ledger by `campaign`, `offer`, `brand_profile`, `audience`, `playbook_job`, `message_template_revision`, `type`, `channel`, or `account_domain`. Optional `since` is inclusive and `until` is exclusive. ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/outcomes/insights?group_by=campaign&campaign_id=$CAMPAIGN_ID" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` Aggregates report counts, classification distribution, positive replies, meetings, wins, losses, win rate, closed-won revenue, and learning-candidate count. They summarize unverified submitted facts; they do not make them verified. --- # Authentication and project environments > Protect project and company-level Bearer keys and isolate environments or clients in projects. Canonical guide: Raw Markdown: OpenAPI: ## Authenticate public API calls Every `/v1` operation requires an API key as an HTTP Bearer credential: ```bash curl "$BLACKPEARL_API_BASE_URL/v1/capabilities" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" ``` The API's OpenAPI document defines one global HTTP Bearer security scheme. Do not send the key as a query parameter or JSON field. ## Choose a key type There are two kinds of API key. Both perform real work and record real usage, and neither has a test mode. | Key type | Console choice | Acts in | Use it when | |---|---|---|---| | Project key | **This project** | Its own project, always. | One application or environment uses one project. Start here. | | Company-level key | **Company (all projects)** | The project each request names, or the key's default project. | One integration runs work in several projects, for example one per client. It can also create projects and manage their allowances and limits over the API. | Owners and administrators create both kinds under **API keys**. A company-level key holds authority over every project in your organization, so protect it like an administrator credential. ## Name the project with a company-level key A company-level key finds the project for each request in this order: 1. The `Blackpearl-Project` request header, set to the project's id or slug. 2. For a request about one job, campaign, or audience (for example `GET /v1/jobs/{job_id}` or a prospecting continuation), the project that owns it. Polling therefore needs no header. 3. The key's default project, if one was chosen when the key was created. The default choice is **None**. ```bash curl "$BLACKPEARL_API_BASE_URL/v1/capabilities" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Blackpearl-Project: client-a" ``` When none of these supplies a project, a request that creates work or reads project data (including `GET /v1/capabilities` and `GET /v1/usage`) fails with `400 project_required`. Company-wide requests need no project: the projects and limits operations (`/v1/projects` and `/v1/limits`), `GET /v1/charges` (every project unless you narrow it), and `GET /v1/pricing-estimates`. A project key may send `Blackpearl-Project` only with its own project's id or slug; any other value returns `403 forbidden`, whether or not that project exists. ## Projects are environments or clients A project is the isolation boundary for keys, ownership, usage attribution, quotas, budgets, and allowances. Create separate development, staging, and production projects when those workloads must not affect each other. A project can also be one of your clients. With a company-level key you create a project per client, give each its own allowance, daily and monthly limits, and default brand, and read what each was charged. Your company keeps one prepaid balance. See [Managing your clients with projects](https://engine.neraperla.com/docs/projects) and [Billing and auto-recharge](https://engine.neraperla.com/docs/billing). An archived project runs no work, and its project keys are refused with `403 project_archived`. It is read-only, not hidden: a company-level key that sends no `Blackpearl-Project` header can still read its jobs, results, campaigns, and audiences by id, but can't change them or start work in it. A key prefix does not change execution behavior: every hosted request performs real capability work and records real usage. Automated tests should inject explicit test doubles at integration boundaries or target an isolated gateway configured with test services. ## Create, store, and rotate keys For AI sessions, the [agent setup flow](https://engine.neraperla.com/docs/agent-setup) delivers a key directly to the agent after you approve in the browser. This avoids copying credentials into chat. - Create a key from **API keys** in the console and copy it immediately; the secret is shown once and stored hashed. - Store the value in a server-side secrets manager and expose it to the process as `BLACKPEARL_API_KEY`. - Never commit a key, log it, paste it into support tickets, or embed it in browser or mobile code. - Rotate without downtime by creating and deploying a replacement before revoking the old key. - A revoked or expired key stops authenticating immediately. ## Authentication and project failures | Code | Status | Meaning | Action | |---|---:|---|---| | `missing_api_key` | 401 | The Bearer header is absent. | Add `Authorization: Bearer ...`. | | `invalid_api_key` | 401 | The credential is malformed, unknown, or revoked. | Load an active key from the correct secret. | | `expired_api_key` | 401 | The key passed its configured expiry. | Rotate to a new active key. | | `project_required` | 400 | A company-level key made a request that needs a project without naming one, and has no default project. | Send the `Blackpearl-Project` header. | | `forbidden` | 403 | A project key named another project, or called an operation only a company-level key can use. | Use the project's own key or a company-level key. | | `project_archived` | 403 | The key's project, the project named by the header, or the company-level key's default project is archived. | Use an active project, or restore it with a company-level key. | | `project_not_found` | 404 | No project with that id or slug exists in your organization. | Check the id or slug, or list projects with `GET /v1/projects`. | | `not_found` | 404 | The job, campaign, or audience doesn't exist where the key can see it: in your organization for a company-level key, in its own project for a project key. | Check the id and the key. | These are configuration failures, not transient failures. Do not retry them without changing the credential or project. See the complete [error and retry matrix](https://engine.neraperla.com/docs/errors) and discover enabled features with [Capabilities and entitlements](https://engine.neraperla.com/docs/feature-flags). The capabilities request uses OpenAPI operation `capabilities_v1_capabilities_get` and schema `PublicCapabilitiesResponse`. --- # Jobs and resumable polling > Persist asynchronous job IDs, poll with bounded backoff, and stop on every terminal status. Canonical guide: Raw Markdown: OpenAPI: [Infinite Intent](https://engine.neraperla.com/docs/infinite-intent) also uses `GET /v1/jobs/{job_id}`, with type `infinite_intent`. Open `result.report_url` in a new browser tab. Its `billing` fields report actual charge and credits used. Playbooks, Audiences, Brand research, Prospecting, Documents, Message Templates, Site Intelligence, and Enrichment batches return asynchronous jobs. The shared `type` field selects the typed `input` and `result`: `playbooks` uses `PublicPlaybookJobResponse`, `audiences` uses `PublicAudienceJobResponse`, `brands` uses `PublicBrandJobResponse`, `prospecting` uses `ProspectingJobResponse`, `documents` uses `DocumentJobResponse`, `message_templates` uses `MessageTemplateJobResponse`, `site_intelligence` uses `PublicSiteIntelligenceJobResponse`, `enrichment` uses `PublicEnrichmentJobResponse`, and `infinite_intent` uses `InfiniteIntentJobResponse`. ## Lifecycle | Status | Terminal | Client behavior | |---|---:|---| | `queued` | No | Wait before polling again. | | `running` | No | Report `progress` if useful and keep polling. | | `succeeded` | Yes | Validate and render the typed `result`. | | `failed` | Yes | Stop and handle `error_code` when present, then surface the job's `error` message. | | `canceled` | Yes | Stop. Runs are canceled from the web console; the API has no cancel operation except Infinite Intent's. | Do not wait only for `succeeded`, because that creates infinite loops after failures or cancellation. ## Typical durations Generation jobs run for minutes, not seconds. In current production operation, Playbooks jobs typically complete in about 10–20 minutes and Prospecting runs typically take several minutes; Audiences jobs can run substantially longer depending on scope. These are operational observations to size polling intervals and client deadlines, not completion-time promises. ## Resumable polling algorithm 1. After a successful create response, persist `id` before the first poll. 2. Poll `GET /v1/jobs/{job_id}` after 2 seconds. 3. Back off exponentially with jitter, capped at 10 seconds. For capabilities that typically run for many minutes, such as Playbooks, settle at a steady 15–30 second interval — polling faster does not make the job finish sooner. 4. Set a local deadline appropriate to the caller and generous relative to the typical duration above. A deadline stops the client, not server work. 5. Keep the ID when the deadline expires and resume it later rather than creating duplicate work. 6. Stop on `succeeded`, `failed`, or `canceled`. Before the create request, persist an `Idempotency-Key`. If the connection fails before the response arrives, repeat the exact job-creation operation and input with that key during its 24-hour replay window. This recovers the original response instead of creating duplicate work. The [Quickstart](https://engine.neraperla.com/docs/getting-started) includes a complete cURL implementation. Tested Python and TypeScript implementations under `docs/examples` add jitter and use the same terminal-state rules. ## Ownership and billing A project key sees only its own project's jobs. A company-level key reads any job of your company: without a `Blackpearl-Project` header the job's own project is used, and with one the job must belong to that project. A missing or cross-project ID returns `not_found`. Jobs in an archived project stay readable by id to a company-level key that sends no `Blackpearl-Project` header, so a run in progress when the project was archived can still be polled to its end. Creating a job records accepted work and its eventual capability usage. Poll requests are subject to request rate limits but are not billed as new generation requests. Job creation requires a positive spendable credit balance, but does not quote the run's price; for a typical price before you submit, see [Billing](https://engine.neraperla.com/docs/billing). A project with an allowance also needs enough of it left to start a run; see [Projects](https://engine.neraperla.com/docs/projects). The run is priced and charged when it finishes, and `usage.cost_usd` reports that charge: `0` while the run is in progress and for a failed run, the full price (including any data-record fee) for a succeeded run, and the charge for the work done before the cancel for a canceled run (`0` for a prospecting run canceled before its search started). Most canceled runs stop within seconds and their charge follows. A canceled Playbooks run is the exception: its generation keeps running, and it is charged in full when the generation finishes. Until a canceled run's charge is recorded, `usage.cost_usd` reads `0`: read the job again later, or find the charge in `GET /v1/charges`. If the charge exceeds the remaining balance, the full amount is still charged and the job succeeds with its result: the balance goes negative, configured auto recharge is triggered, and new jobs are rejected with `insufficient_credits` until a top-up restores a positive balance. `progress` is coarse and is not a completion-time promise. Do not build an SLA from it. Timestamps (`created_at`, `started_at`, `finished_at`, `expires_at`) are ISO-8601 UTC ending in `Z`. Every public job includes `expires_at`, exactly 30 days after `created_at`. Job metadata, input, and results remain readable through that timestamp. Store any result your application needs longer. After `expires_at`, direct job and Audience candidate reads return `410` with `error.code` `job_expired`. Cleanup removes retained input, result, failure detail, stages, and private diagnostics, but preserves the minimal ownership tombstone plus usage, charge, credit, and audit records. Expiry does not cancel work, reverse billed usage, or erase accounting history. ## Poll errors Safe GET requests may be retried for `rate_limit_exceeded` after `Retry-After` and for documented transient `5xx` failures with bounded exponential backoff. Fix authentication, entitlement, quota, and budget errors before retrying. See [Errors](https://engine.neraperla.com/docs/errors). Over a run lasting many minutes, an individual poll can also fail in transit — a connection error, a timeout, or a `502`, `503`, or `504` produced by network infrastructure between your application and the platform (CDN edge, load balancers, or an outbound proxy on your side) — while the job continues normally on the platform. Treat any such failure as retryable: retry the same `GET /v1/jobs/{job_id}` with bounded backoff, and never conclude that the job failed or create a replacement job because one poll did not succeed. The job's `status` in a successful response is the only authoritative signal, and the result remains retrievable until `expires_at` even if your poller stops for an extended period. Job retrieval is OpenAPI operation `get_job_v1_jobs__job_id__get`. Its response is the same `type`-discriminated union of the Job schemas listed at the top of this page. Documents results contain file references; download their bytes through the authenticated endpoint documented in [Documents](https://engine.neraperla.com/docs/documents) before the Job expires. --- # Errors and retry decisions > Branch on stable error codes and retry only operations that are safe and transient. Canonical guide: Raw Markdown: OpenAPI: Public API failures use OpenAPI schema `ErrorResponse`: ```json { "error": { "code": "invalid_request", "message": "A readable explanation of what went wrong.", "request_id": "req_example", "docs_url": "https://engine.neraperla.com/docs/errors" } } ``` Use `error.code`, not HTTP status alone, to decide what happens next. Preserve `request_id` for diagnostics. Validation failures, quota refusals, and budget refusals also include structured `details`. Every `/v1` path returns this envelope, including an unknown path (`404 not_found`) and a method the path doesn't support (`405` with `invalid_request`). A failed job reports its failure in the job body rather than as an HTTP error: `error` carries the message, and `error_code` carries a code from this vocabulary when one applies. ## Error and retry matrix | Codes | Status | Retry? | Caller action | |---|---:|---|---| | `invalid_request`, `invalid_cursor`, `invalid_domain`, `brand_profile_mismatch`, `invalid_campaign_key`, `invalid_campaign_metadata`, `invalid_campaign_name`, `invalid_campaign_objective`, `invalid_campaign_status`, `campaign_relation_mismatch`, `invalid_stage` | 400 or 422 | No | Correct the request. `invalid_request` also answers `405` when the path doesn't support the HTTP method. | | `project_required` | 400 | No | A company-level key without a default project made a request that needs a project without naming one: send the `Blackpearl-Project` header with the project's id or slug. See [Authentication](https://engine.neraperla.com/docs/authentication) and [Managing your clients with projects](https://engine.neraperla.com/docs/projects). | | `missing_api_key`, `invalid_api_key`, `expired_api_key`, `authentication_required` | 401 | No | Supply an active API key. | | `insufficient_credits` | 402 | No | Let auto-recharge complete or add credits. Admission only requires a positive balance; a run that finishes above the remaining balance still succeeds and takes the balance negative, which blocks new runs until a top-up. | | `forbidden`, `project_archived`, `capability_disabled` | 403 | No | Change the key, project state, or access. `forbidden` includes a project key naming another project (in `Blackpearl-Project` or a `/v1/projects/{project_ref}` path) and a project key calling an operation only a company-level key can use. `project_archived` means the key's project, the named project, or a company-level key's default project is archived; restore it or use an active project. For `capability_disabled`, call `GET /v1/capabilities` to see which capabilities are enabled; the capability exists but is not enabled for the organization, so request access. | | `project_not_found` | 404 | No | The project named by `Blackpearl-Project` or the path doesn't exist in the organization; check the id or slug, or list projects with `GET /v1/projects`. | | `not_found`, `result_unavailable`, `playbooks_document_unavailable`, `brand_not_found`, `brand_profile_not_found`, `offer_not_found`, `account_not_found`, `playbook_job_not_found`, `message_template_revision_not_found`, `company_dossier_specification_not_found` | 404 | No | Check the ID or domain, project ownership, environment, and retained data. A resource in another project returns `not_found` to a project key. `not_found` also answers an unknown `/v1` path. | | `job_expired` | 410 | No | Use the result stored by the client or create a new job. | | `not_ready`, `job_not_finished`, `audiences_result_unavailable`, `idempotency_in_progress`, `prospecting_continuation_in_progress` | 409 | Yes, after delay | Continue the documented read/poll flow or repeat the same idempotent request. For `prospecting_continuation_in_progress`, another continuation of the same search is still running: poll its child Job and retry when it finishes. | | `conflict`, `idempotency_key_reused`, `campaign_archived`, `campaign_key_exists`, `invalid_campaign_transition`, `cycle_in_progress`, `offer_archived`, `brand_profile_archived`, `brand_profile_not_ready`, `brand_guideline_missing`, `missing_default_brand_profile`, `playbook_template_not_ready` | 409 | No | Read or repair resource state; use a new idempotency key for changed input. `conflict` includes a project slug that is already in use, an allowance top-up or reduction `reference` already used for a different amount or for the other kind of entry, and a reduction that would take a project's total granted below zero. `brand_profile_archived` also answers a run that names no brand when its project's default brand is archived. For `playbook_template_not_ready`, wait for the template's one-time research to finish (or retry it from the template page). | | `account_unanalyzable` | 422 | No | Check that the domain serves a fetchable public website or continue without on-demand analysis. | | `rate_limit_exceeded` | 429 | Yes | Wait at least `Retry-After`, then retry with backoff and jitter. | | `quota_exceeded` | 429 | No automatic retry | Inspect `error.details` for scope, counters, and `resets_at`; wait for reset or change the quota. | | `budget_exceeded` | 429 | No automatic retry | Inspect `error.details`: `scope` (`organization`, `project`, or `usage_tier`), `kind` (`day`, `month`, `allowance`, or `min_to_start`), `project_id`, `period`, charged `spend_usd`, `limit_usd`, `remaining_usd`, and `resets_at`. For a daily or monthly limit, raise the hard budget or limit, or wait for `resets_at`. A project's allowance (`kind` `allowance` or `min_to_start`) has no reset, so `period` and `resets_at` are null and `held_usd` and `min_to_start_usd` show what runs in progress hold and what a new run needs: top it up (see [Managing your clients with projects](https://engine.neraperla.com/docs/projects)). When `scope` is `"usage_tier"`, the organization's tier-based monthly cap was reached — the cap rises automatically as the organization purchases credits and builds account history (see [Rate limits](https://engine.neraperla.com/docs/rate-limits) for the ladder), or support can adjust the tier. | | `account_research_backend_quota` | 429 | No automatic retry | Wait for the research capacity to reset or ask an operator to increase it. | | `audiences_backend_error`, `audiences_backend_invalid_response`, `audiences_backend_unavailable` | 502 or 503 | Bounded retry for safe reads | Back off with jitter; report persistent failures with `request_id`. | | `enrichment_backend_error`, `enrichment_backend_invalid_response`, `enrichment_backend_unavailable` | 502 or 503 | Bounded retry | The run is failed and never billed. `enrichment_backend_unavailable` also covers a deploy restart and briefly saturated synchronous capacity — honor the `Retry-After` header when present, otherwise back off with jitter; report persistent failures with `request_id`. | | `enrichment_backend_not_configured` | 503 | No | Enrichment is not configured on this deployment; ask an operator. | | `account_research_backend_error`, `account_research_unavailable` | 502 or 503 | Bounded retry | Back off with jitter; report persistent failures with `request_id`. | | `account_research_unauthorized` | 502 | No | Ask an operator to repair the platform's research-backend credential. | | `account_research_not_configured` | 500 | No | Ask an operator to configure the organization's research-backend identity. | | `internal_error` | 500 | Safe reads only | Retry a GET with bounds. Do not automatically repeat job creation. | ## Endpoint-specific codes The OpenAPI `PublicErrorCode` enum is the authoritative finite vocabulary. The matrix above describes the shared codes; the more precise endpoint codes below preserve which resource, snapshot, policy, or idempotency rule failed. These codes are non-retryable unless the endpoint guide explicitly describes the state change required before retrying. Clients should still retain a default branch for forward-compatible additions. - Capability failures (`403`): `documents_capability_disabled`, `professional_network_capability_disabled`, `prospect_research_capability_disabled`. - Scoped resource failures (`404`): `assessment_not_found`, `audience_member_not_found`, `audience_not_found`, `campaign_not_found`, `company_dossier_connection_not_found`, `connection_not_found`, `data_intake_specification_not_found`, `playbook_template_not_found`, `professional_network_connection_not_found`, `professional_network_specification_not_found`, `prospect_not_found`, `prospect_research_specification_not_found`, `prospecting_job_not_found`, `qualification_policy_not_found`, `site_audit_specification_not_found`. - State, version, idempotency, and limit conflicts (`409`): `account_coordination_evidence_too_large`, `account_coordination_idempotency_conflict`, `account_coordination_policy_not_current`, `audience_idempotency_conflict`, `audience_result_changed`, `audience_review_idempotency_conflict`, `audience_source_changed`, `company_dossier_connection_credentials_changed`, `company_dossier_connection_incomplete`, `company_dossier_connector_manifest_changed`, `company_dossier_policy_not_current`, `company_dossier_specification_idempotency_conflict`, `company_dossier_specification_limit_exceeded`, `company_dossier_specification_limit_reached`, `data_intake_policy_not_current`, `data_intake_specification_idempotency_conflict`, `data_intake_specification_limit_exceeded`, `data_intake_specification_limit_reached`, `enrichment_input_invalid`, `message_template_hash_conflict`, `message_template_key_revision_limit_reached`, `message_template_policy_not_current`, `message_template_previous_hash_conflict`, `message_template_revision_idempotency_conflict`, `message_template_revision_limit_exceeded`, `message_template_revision_limit_reached`, `message_template_revision_renderer_unavailable`, `message_template_revision_sequence_conflict`, `offer_key_exists`, `offer_limit_exceeded`, `outcome_idempotency_conflict`, `professional_network_audience_changed`, `professional_network_audience_source_changed`, `professional_network_audience_source_invalid`, `professional_network_connection_incomplete`, `professional_network_connector_manifest_changed`, `professional_network_connector_unavailable`, `professional_network_credentials_changed`, `professional_network_policy_not_current`, `professional_network_selection_too_large`, `professional_network_specification_idempotency_conflict`, `professional_network_specification_limit_exceeded`, `professional_network_specification_limit_reached`, `prospect_research_audience_changed`, `prospect_research_audience_source_changed`, `prospect_research_audience_source_invalid`, `prospect_research_policy_not_current`, `prospect_research_selection_too_large`, `prospect_research_specification_idempotency_conflict`, `prospect_research_specification_limit_exceeded`, `prospect_research_specification_limit_reached`, `prospecting_continuation_idempotency_conflict`, `prospecting_continuation_unavailable`, `prospecting_job_not_ready`, `prospecting_parent_changed`, `prospecting_result_unavailable`, `qualification_policy_idempotency_conflict`, `qualification_policy_limit_exceeded`, `qualification_policy_limit_reached`, `qualification_policy_not_current`, `site_audit_policy_not_current`, `site_audit_specification_idempotency_conflict`, `site_audit_specification_limit_exceeded`, `site_audit_specification_limit_reached`. `audience_source_unavailable` can be `409` or `422` depending on whether the source changed or is invalid for the requested operation. - Endpoint validation failures (`422`): `audience_empty`, `enrichment_fields_unsupported`, `enrichment_level_unavailable`, `invalid_insight_group`, `invalid_offer_field`, `invalid_offer_key`, `invalid_offer_name`, `invalid_offer_stage`, `invalid_offer_status`, `message_template_body_too_long`, `message_template_empty_body`, `message_template_empty_subject`, `message_template_required_variables_missing`, `message_template_subject_too_long`, `message_template_unknown_variables`, `message_template_variable_too_long`, `outcome_connector_required`, `outcome_predates_prospecting_job`, `outcome_source_mismatch`, `professional_network_audience_source_unavailable`, `professional_network_member_prerequisites_missing`, `professional_network_members_unavailable`, `professional_network_selection_empty`, `prospect_research_audience_source_unavailable`, `prospect_research_member_prerequisites_missing`, `prospect_research_members_unavailable`, `prospect_research_selection_empty`, `prospecting_result_too_large`, `synthetic_prospect`, `synthetic_prospecting_result`. - Audiences backend failures (`502`, bounded retry for safe reads): `audiences_backend_generation_failed`, `audiences_backend_timeout`. ## Safe retries - GET operations are read-only and may be retried when the code is transient. - `rate_limit_exceeded` includes `Retry-After`; the other `429` codes require a state or configuration change. Every request made with a valid key counts against that key's rate limit, including requests the API then refuses (for example `project_required`, `project_not_found`, `project_archived`, or `forbidden`), and those responses carry the `RateLimit-*` headers too. Repeated requests with an unknown or revoked key from one address are also throttled with `429 rate_limit_exceeded`. - Before a job-creation POST, generate and persist a non-sensitive `Idempotency-Key` of at most 255 characters. The key is scoped to the authenticated project and operation. - If the connection is lost or the response is ambiguous, repeat the exact operation, input, and key. Matching retries within 24 hours return the original response without creating or billing another job. - `idempotency_key_reused` means the input differs from the original request. Use the exact original input or a new key. `idempotency_in_progress` means the first matching request has not stored its response yet; retry the same request after a short delay. - After 24 hours, the same key can create new work. Persist the returned job ID and do not use idempotency as long-term job storage. - Set retry and total-operation limits. Jitter prevents synchronized clients from retrying together. ```javascript const retryAfter = Number(response.headers.get("Retry-After") ?? "1"); if (response.status === 429 && body.error?.code === "rate_limit_exceeded") { await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000)); } ``` See [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs) for client deadlines and [Limits, budgets, and usage](https://engine.neraperla.com/docs/usage-quotas) for the three distinct `429` cases. --- # Rate limits > Recover from transient request-rate limits without confusing them with quota or budget exhaustion. Canonical guide: Raw Markdown: OpenAPI: Rate limits control request pace for one API key, whether a project key or a company-level key. A company-level key has one window for every project it serves. They are separate from monthly usage quotas, hard budgets, credits, and billed capability work. Every request that successfully authenticates to `/v1` consumes one place in that key's rolling 60-second window. This includes reads, polling, validation failures, idempotent replays, and calls to Usage. Missing, invalid, revoked, and expired credentials do not enter a key's window because no key can be identified. The limit per 60 seconds comes from your organization's usage tier (see [Usage tiers](#usage-tiers)); 120 requests per 60 seconds applies only when a deployment has no usage tiers. Use the policy and live window values returned by the API: | Response value | Meaning | |---|---| | `RateLimit-Limit` | Requests allowed in the current 60-second window. | | `RateLimit-Remaining` | Requests still available after the current request. | | `RateLimit-Reset` | Whole seconds until the oldest request leaves the current window. | | `Retry-After` | On `rate_limit_exceeded` only, the minimum whole seconds to wait before retrying. | The three `RateLimit-*` headers appear on authenticated success and error responses. `GET /v1/usage` also returns `rate_limit.limit` and `rate_limit.window_seconds` for policy discovery. The per-minute limit is set by the organization's **usage tier**, which advances automatically with cumulative credit purchases and account age. `GET /v1/usage` returns the current tier as `usage_tier` (`key`, `name`, `rank`, `rate_limit_per_minute`, `monthly_cost_cap_usd`). Each tier also carries a monthly spend cap, counted in what the organization is charged during the UTC calendar month (`monthly_cost_cap_usd` is the cap that applies: the tier's, or the organization's lifetime gifted credit when that is higher): when it is reached, job creation fails `429 budget_exceeded` with `error.details.scope` of `"usage_tier"` — like budget exhaustion, this is not transient and resets at `error.details.resets_at`. The refusal's `details` also carry `tier` (the tier key), `limit_usd` (the cap that applies), `spend_usd` (charged this month), and `reserved_usd`. ## Usage tiers Organizations move up the tier ladder automatically as they build history — no request or review is needed. Advancement is based on two signals: **lifetime credit purchases** (settled payments; promotional credits never advance the tier) and **days since your first payment**. Both thresholds must be met. The ladder: | Tier | Qualification | Requests/min | Monthly spend cap | |---|---|---|---| | Free | New organization | 60 | $100 | | Tier 1 | $50 purchased | 120 | $500 | | Tier 2 | $500 purchased, 7+ days | 300 | $2,500 | | Tier 3 | $2,500 purchased, 14+ days | 600 | $10,000 | | Tier 4 | $10,000 purchased, 30+ days | 1,200 | No monthly cap | Two adjustments can apply to an individual organization: - **Promotional credits raise the cap.** An organization granted promotional credit can always consume it: the effective monthly cap never sits below the total promotional credit granted, even on the Free tier. - **Support can pin a tier.** Limits set by support override the computed tier in both directions and are shown on the Limits page. On a tier with a monthly spend cap, your organization runs one job at a time, across all of its projects and keys. A job holds the rest of the month's cap from the moment it is accepted until it finishes, because its price isn't known until then. Another job submitted meanwhile is refused with `429 budget_exceeded`, `details.scope` of `"usage_tier"`, a `reserved_usd` above zero and a `spend_usd` below `limit_usd`: submit it again when the first job finishes. Tier 4, which has no monthly spend cap, has no such limit: its jobs can run at the same time. Your current tier, effective monthly cap, and progress to the next tier are on the console **Settings → Limits** page. If you need higher limits than your tier allows, contact support. When request pace is too high, the API returns `429` with `error.code` set to `rate_limit_exceeded`. Wait at least the larger of `Retry-After` and `RateLimit-Reset`, then retry with bounded exponential backoff and jitter. Polling consumes request-rate capacity but does not create or bill another generation run. `quota_exceeded` and `budget_exceeded` also return `429`, but neither is a transient request-rate failure and neither carries `Retry-After`. Use `error.details.resets_at` and the counters in [Limits, budgets, and usage](https://engine.neraperla.com/docs/usage-quotas) to decide whether to wait for the next UTC month or ask an administrator to change the control. The complete decision table is in [Errors](https://engine.neraperla.com/docs/errors). --- # Limits, budgets, and usage > Distinguish request rate, monthly quota, hard budget, credits, and Usage API counters. Canonical guide: Raw Markdown: OpenAPI: Six controls can affect whether work starts. They are checked in the order below, and the first that refuses is the error you get: | Control | Purpose | Failure and recovery | |---|---|---| | Request rate | Limits request pace per API key. A company-level key has one budget for every project it serves. | `rate_limit_exceeded`; retry after `Retry-After`. | | Usage quota | Limits accepted job requests, or the amount charged, at organization, project, API-key, and optional capability scope for a UTC calendar month. | `quota_exceeded`; use `error.details.resets_at`, wait for reset, or ask an administrator to change the quota. | | Project allowance | Stops new work in one project once its allowance, a never-resetting spending limit you top up, can't cover a run or its minimum to start. Other projects keep running. | `budget_exceeded` with `error.details.kind` of `allowance` or `min_to_start`; top up the project's allowance. See [Managing your clients with projects](https://engine.neraperla.com/docs/projects). | | Hard budget | Stops new capability work once the charges for runs in an organization or project scope, optionally for one capability, reach a daily or monthly ceiling. The daily and monthly limits you set for a project or for the whole company with the projects and limits API are hard budgets. | `budget_exceeded`; use `error.details`, wait for reset, or ask an owner, administrator or billing member to change the budget. | | Usage-tier spend cap | Stops new capability work once the organization's charges this month reach its tier-based monthly spend ceiling. The cap rises with the tier ladder (earned by credit purchases and account age) and never sits below the organization's total granted promotional credit. On a capped tier, the organization runs one job at a time: a job in progress holds the rest of the month's cap until it finishes. | `budget_exceeded` with `error.details.scope: usage_tier`. When `error.details.reserved_usd` is above zero and `spend_usd` is below `limit_usd`, another job holds the cap: start this one when that job finishes. Otherwise wait for reset, purchase credits to advance the tier, or ask support for a tier change. See [Rate limits](https://engine.neraperla.com/docs/rate-limits#usage-tiers). | | Prepaid credits | Requires a positive spendable balance when billing is enabled; no future job price is estimated or reserved. | `insufficient_credits`; add credits or let auto-recharge complete. | Only the rate-limit case is a transient automatic retry. See [Errors](https://engine.neraperla.com/docs/errors). Quota periods and monthly budgets begin at `00:00:00 UTC` on the first day of a calendar month and reset at the next month's boundary. Daily budgets begin at `00:00:00 UTC` and reset at the next UTC midnight. An error's structured `details` reports the applicable scope, limit, current value, remaining value, and `resets_at`. Do not automatically retry either code merely because its HTTP status is `429`: an administrator may change a control before reset, but only `rate_limit_exceeded` is transient by itself. ## What each counter records One newly accepted Playbooks job or Audience cycle adds exactly `1` to Usage `requests`. Idempotent replay returns the original job without adding another request. Rejected job creation, campaign setup, reads, polling, candidate retrieval, and Usage calls add `0` to this monthly counter. They can still consume the API-key request-rate window. When a job finishes, the amount it was charged is added to `cost_usd`; it does not add a second request. A run that fails is not charged and adds `0`. A request quota checks whether the next new job would exceed its limit. A cost quota stops new jobs once the amount charged in its scope has reached the limit. Work already accepted continues even if a later completion crosses a cost or budget threshold. `tokens` is retained in usage objects for compatibility and is always `0`. Token quotas can no longer be created, and an existing token quota reports `used: 0`. Budgets count what runs are charged (the debits on the prepaid balance), independently of Usage quotas. A soft budget records alerts but does not reject work. A hard budget rejects new work once the period's charges reach its ceiling; runs already accepted are never cut off, so the runs in progress when the ceiling is reached can take the total past it. `budgets` in `GET /v1/usage` lists monthly budgets only; read daily limits with `get_project_limits` and `get_company_limits` (see [Managing your clients with projects](https://engine.neraperla.com/docs/projects#daily-and-monthly-limits)). Prepaid billing is separate: any positive spendable balance permits work to start, with no admission estimate or price reserve. At completion, the run's price is charged in full, and that charge is the `cost_usd` reported for the job. If that price exceeds the remaining balance, the job still succeeds with its result and the balance goes negative; auto-recharge is then triggered, and new work is rejected with `insufficient_credits` until a top-up restores a positive balance. `credits.balance_usd` is the current ledger balance, which can be negative, not a monthly counter. Usage records are append-only. The public Usage API returns the authenticated project's current monthly rollup and capability breakdown: ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/usage" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` ```json { "project_id": "proj_example", "period": "2026-07", "period_start": "2026-07-01T00:00:00Z", "period_end": "2026-08-01T00:00:00Z", "rollup": { "requests": 12, "tokens": 0, "cost_usd": 1.243 }, "by_capability": [ { "capability_key": "playbooks", "requests": 12, "tokens": 0, "cost_usd": 1.243 } ], "usage_tier": { "key": "tier_2", "name": "Tier 2", "rank": 2, "rate_limit_per_minute": 300, "monthly_cost_cap_usd": 2500.0 }, "rate_limit": { "limit": 300, "window_seconds": 60 }, "quotas": [ { "metric": "requests", "period": "month", "scope": "project", "capability_key": "playbooks", "limit_value": 1000, "used": 12, "remaining": 988, "resets_at": "2026-08-01T00:00:00Z" } ], "budgets": [ { "period": "month", "scope": "project", "capability_key": null, "limit_usd": 50, "spend_usd": 1.243, "remaining_usd": 48.757, "hard_limit": true, "resets_at": "2026-08-01T00:00:00Z" } ], "credits": { "billing_enabled": true, "balance_usd": 98.757, "topup_increment_usd": 100.0 } } ``` `period_start` is inclusive and `period_end` is exclusive. `rollup` totals the project, while `by_capability` reconciles those counters by capability key. Every `cost_usd`, `spend_usd`, and `limit_usd` is an amount charged to the prepaid balance, so these figures reconcile with your transactions and statements. `usage_tier` is nullable and reports the organization's resolved rate and monthly spend cap when tiering applies. `quotas` includes every organization, project, or API-key quota that can affect this key; `budgets` includes every organization or project budget that can affect this project. Empty arrays mean no matching control is configured. Compare a completed job's `usage` with these rollups while allowing for other jobs in the same period. Usage retrieval is OpenAPI operation `usage_v1_usage_get` with schema `PublicUsageResponse`. --- # Billing and auto-recharge > How prepaid credit is charged, how to cap spend, and how to keep the balance topped up automatically. Canonical guide: Raw Markdown: OpenAPI: Billing is prepaid. Your organization has one credit balance, shared by every project and API key. Every amount on this page is what your balance is charged. ## How charging works - A job starts only when the balance is above zero. Nothing is estimated or reserved from the balance up front. (A project's allowance can also require a minimum to start; see [Managing your clients with projects](https://engine.neraperla.com/docs/projects).) - When the job finishes, its actual price is deducted from the balance. - If the price is more than the remaining balance, the job still finishes and keeps its result. It is charged in full, so the balance goes below zero. - While the balance is zero or below, new jobs are rejected with `402 insufficient_credits`. Your next top-up clears the amount owed first; new jobs start again once the balance is back above zero. - Your billing contacts are emailed when a job takes the balance below zero, with the amount charged and a top-up link. A failed job is never charged. A job you cancel in the console is charged for the work done before you cancelled it. A canceled Playbooks job is the exception: its generation keeps running, and it is charged in full when the generation finishes, without a result. See [Jobs and polling](https://engine.neraperla.com/docs/jobs). ## See typical prices before you run `GET /v1/pricing-estimates` returns what one unit of each capability is typically charged at your organization's rates, so you can show your own users a price before you submit work. Any API key can call it, and a company-level key needs no `Blackpearl-Project` header. ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/pricing-estimates" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` ```json { "capabilities": [ { "capability_key": "playbooks", "name": "Playbooks", "docs_slug": "playbooks", "units": [ {"unit": "per_playbook", "label": "per playbook", "approx_usd": 4.9, "low_usd": 2.3, "high_usd": 7.9} ] } ] } ``` - `approx_usd` is the typical charge for one unit, rounded to two significant figures: the recency-weighted median of what recent runs would be charged at your rates, including any data-record fee. - `low_usd` and `high_usd` are the typical range: about 80% of recent runs were charged between them, at your rates. - It is a guide, not a quote, and `high_usd` is not a cap. Each run is charged for the work it actually does, and about one run in ten is charged more than `high_usd`. To bound what one client can spend, give their project an allowance and limits. - Units depend on the capability: `per_run` for prospecting, `per_playbook` for playbooks, and `per_setup`, `per_cycle` and `per_record` for Audiences, for example. - Only capabilities that `GET /v1/capabilities` lists for your organization appear. A capability or unit without enough recent runs to price is left out rather than shown as free, so `capabilities` can be an empty list. - Connected Claude clients get the same figures from the `get_pricing_estimates` tool. This is OpenAPI operation `pricing_estimates_v1_pricing_estimates_get` with schema `PublicPricingEstimatesResponse`. ## Cap your spend Budgets cap what you're charged per UTC day or per UTC month, for the whole organization, one project, or one capability. Every budget emails your billing contacts as its period's charges pass its alert thresholds: 50%, 80%, and 100% by default, or the percentages you choose. Each threshold is emailed at most once per period. A soft budget only alerts. A hard budget also rejects new jobs with `429 budget_exceeded` once its period's charges reach the limit. A job that has already started is never cut off: jobs in progress when the limit is reached all finish and are charged, so they can take the total past the limit. Owners, admins, and billing members manage budgets on the console **Costs** page. Over the API you can set the hard daily and monthly limits of each project (`set_project_limits`) and of the whole company (`set_company_limits`). These limits are budgets too, so they also appear on the **Costs** page. Soft budgets, custom alert thresholds, and budgets for one capability are set in the console only. See [Limits, budgets, and usage](https://engine.neraperla.com/docs/usage-quotas). If you resell to your own clients, give each client a project with its own allowance and daily and monthly limits, so one client running out never stops the others. See [Managing your clients with projects](https://engine.neraperla.com/docs/projects). ## Add credits Credit is bought in the console; there is no API for it. Owners, admins, and billing members can buy it. 1. Go to **Settings → Billing → Payment methods** and choose **Add a card**. Card details are entered on our payment processor's secure page. 2. On **Settings → Billing**, choose **Add credits** and pick an amount: $100 to $10,000, in $100 steps. It is charged to your default card. 3. The credit is added to your balance once the payment is confirmed, and a receipt is emailed. If the balance was below zero, the purchase clears the amount owed first. Credits never expire. Each payment, with its receipt and invoice, is listed under **Settings → Billing → Invoices & receipts**. ## Turn on auto-recharge Auto-recharge charges your saved card whenever the balance falls below a threshold you set. 1. Sign in to the console as an owner, admin, or billing member. 2. Add a card under **Settings → Billing → Payment methods**, as above. Auto-recharge can't be turned on without a default card. 3. Go to **Settings → Billing → Auto-recharge** and turn on **Enable auto-recharge**. 4. Set **When balance falls below (USD)**, up to $10,000, and **Recharge amount (USD)**. Recharges start at $100 and go up in $100 steps, to a maximum of $10,000. The defaults are a $50 threshold and a $100 recharge. 5. Choose **Save settings**. The balance is checked each time a job is charged, and every few minutes. Set the threshold above the price of your largest single job, so the balance rarely dips below zero. If a job leaves the balance further below the threshold than one recharge covers, auto-recharge charges again on the next check until the balance is back above the threshold. ## If a card payment fails - Jobs keep running on the remaining balance. - After the first failure the charge is retried 1 hour later, and after the second failure 6 hours later, if the balance is still below the threshold. You are emailed after each failure. - After the third failure in a row, auto-recharge is suspended and you are emailed. Update the card in **Payment methods**, then choose **Retry now** on the **Auto-recharge** page. - If your bank asks for extra verification, choose **Confirm payment** on the **Auto-recharge** page. This does not count as a failure. - When the balance reaches zero or below, new jobs are rejected with `insufficient_credits` until credit is added. ## Check your balance - Console: **Settings → Billing**. When the balance is below zero, the page shows the amount owed and the top-up that brings it back above zero. - API: `GET /v1/usage` returns `credits.balance_usd`, which can be negative. It reports on one project, so a company-level key without a default project names any project with the `Blackpearl-Project` header (the balance is the company's), or reads `balance_after_usd` on the newest `GET /v1/charges` entry. - A refund to your card that hasn't completed yet can't be spent, so a job can be refused with `402 insufficient_credits` while `credits.balance_usd` still includes that amount. - Per-client charges: `GET /v1/projects/{project_ref}/charges` lists what each of a project's jobs was charged, in the same shape and with the same signs as `GET /v1/charges` below. ## Read your charge history `GET /v1/charges` lists every change to your balance, newest first: what each job was charged (`debit`), credit you bought (`topup`), promotional credit (`gift`), corrections (`adjustment`), refunds to your card (`refund`), and refunds that failed and came back (`refund_reversal`). `amount_usd` is signed, negative for money out of the balance, and `balance_after_usd` is the balance right after the entry, so the newest entry's balance matches `credits.balance_usd`. ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/charges?type=debit&from=2026-10-01T00:00:00Z" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` ```json { "charges": [ { "id": "ctx_5a8b2c9d1e0f3a4b", "type": "debit", "amount_usd": -2.43, "balance_after_usd": 412.57, "job_id": "job_0b1c2d3e4f5a6b7c", "capability": "prospecting", "project_id": "proj_3f9c1a7d2b8e4c11", "project_slug": "client-a", "project_name": "Client A", "created_at": "2026-10-08T12:00:00Z" } ], "has_more": false, "next_cursor": null } ``` - Filter with `type` (repeatable), `from` and `to` (UTC; `to` is exclusive), and `project` (id or slug). Page with `limit` (50 by default, up to 200) and `cursor`; a cursor that isn't a `next_cursor` from this listing returns `400 invalid_cursor`. - A company-level key sees the whole company, or one project with `project` or the `Blackpearl-Project` header. Naming two different projects that way returns `400 invalid_request`, and an unknown project `404 project_not_found`. A key's default project never narrows the listing. A project key sees only its own project's job charges; naming another project returns `403 forbidden`. - Every amount is what you were charged or credited: a job's `debit` is its `usage.cost_usd`, as a negative amount. - Connected Claude clients get the connected project's charges from the `list_charges` tool. This is OpenAPI operation `list_charges` with schema `PublicChargeList`. ## Statements and refunds - **Settings → Billing → Invoices & receipts** shows a statement for each UTC calendar month: opening balance, credit purchased, promotional credit, refunds, corrections, what jobs were charged by capability, and closing balance, with a CSV download. - Refunds to your card are made by Blackpearl support; the console and API don't offer them. A refund leaves your balance and appears as a `refund` entry. Until it completes, its amount can't be spent. ## Billing emails Billing emails go to the **Billing email override** on **Settings → Billing**, if you set one, and otherwise to every active owner, admin, and billing member. | Email | When it is sent | |---|---| | Low balance | After a job is charged, if auto-recharge is off and the balance is at or above $0 but below $25. At most once per UTC calendar month. | | Balance below zero | When a job's charge takes the balance from $0 or above to below zero. Further jobs that deepen the same overdraft don't send another. | | New runs refused | The first time in a UTC calendar month that a job is refused with `insufficient_credits`. | | Payment receipt | Each time bought credit or an auto-recharge is added to the balance. | | Auto-recharge failed, suspended, or needs confirmation | See [If a card payment fails](#if-a-card-payment-fails). | | Card expiring | Once per card, about 30 days before a saved card expires. | | Refund issued | When a refund to your card completes. | | Monthly statement | Early each month, for the previous month, if your balance changed during it. | | Budget alert | When a budget's charges pass one of its alert thresholds. | | Project allowance low or used up | See [Managing your clients with projects](https://engine.neraperla.com/docs/projects#alerts). | | Usage tier | When your organization moves up a usage tier, and the first time in a month its tier's spend cap stops a job. See [Rate limits](https://engine.neraperla.com/docs/rate-limits#usage-tiers). | See [Errors](https://engine.neraperla.com/docs/errors) for `insufficient_credits` and `budget_exceeded`. --- # Managing your clients with projects > Run one project per client with a company-level key, give each an allowance, daily and monthly limits and its own brand, top it up or reduce it, and read what it was charged. Canonical guide: Raw Markdown: OpenAPI: If you resell Blackpearl to your own clients, give each client a project. Your company keeps one balance, card, and auto-recharge, and each project gets its own spending controls, so one client running out never stops the others. Every amount on this page is what your company balance is charged, in US dollars. ## Use a company-level API key A company-level key acts in any of your projects. Owners and administrators create one in the console under **API keys**, by choosing **Company (all projects)**. Project keys keep working exactly as before. When you create the key, choose its **default project**: the project used when a request doesn't name one. The default choice is **None**, which means every request must name its project. Keep None if you run a project per client: a forgotten header is then refused, instead of being run and charged against the wrong client. With a company-level key, name the project on each request with the `Blackpearl-Project` header. It takes the project's id or its slug. One company-level key has one request-rate budget for every project it serves (see [Rate limits](https://engine.neraperla.com/docs/rate-limits)): ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/prospects" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Blackpearl-Project: client-a" \ --header "Idempotency-Key: client-a-20261008-austin-pm" \ --header "Content-Type: application/json" \ --data '{ "campaign_name": "Austin property managers", "product_info": "Commercial security guard services.", "objective": "Find facilities and property managers at commercial real-estate firms in Austin, TX." }' ``` - When a request has no header, the project comes from the job, campaign, or audience it is about, then from the key's default project. Polling `GET /v1/jobs/{job_id}` therefore works with or without the header. - Without a header and with no default project, requests that create work, and project-scoped reads and lists, fail with `400 project_required`. - The projects and limits endpoints below work without it. - An unknown id or slug returns `404 project_not_found`. Naming an archived project returns `403 project_archived`. - If a key's default project is archived, requests that name no project and need one return `403 project_archived`; company-wide requests (projects, limits, charges, price estimates, and restoring the project) still work. - A project key may send the header only with its own project's id or slug; any other value returns `403 forbidden`. Idempotency keys are scoped per project, so reusing one for two clients never replays the wrong client's job. ## Create a project per client Operation `create_project` creates a project. Pass your own client id as the `slug` if you like: up to 64 letters, digits, `.`, `_` and `-`, starting with a letter or digit, unique within your company, and not starting with `proj_`. Without a slug, one is made from the name, with `-2`, `-3` and so on added if it is taken. A slug can't be changed later, and an archived project keeps its slug. ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/projects" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Content-Type: application/json" \ --data '{"name": "Client A", "slug": "client-a"}' ``` The response is the project with its `limits`. A new project starts with your company's new-project defaults (see [Company limits and defaults](#company-limits-and-defaults)). A slug already in use returns `409 conflict`. `list_projects` returns your active projects, oldest first; pass `include_archived=true` to include archived ones. `get_project` reads one by id or slug. `update_project` renames a project, sets its default brand (see below), archives it with `{"archived": true}` so it can't run work, or restores it with `{"archived": false}`. Archiving keeps the project's history, allowance, and charges. An archived project runs no work from anywhere: the API, the console, connected Claude clients, or a campaign's schedule. It is read-only, not hidden: with a company-level key and no header, its jobs, results, events and exports stay readable, so a run in progress when you archive it can still be polled; a change addressed to its resources returns `403 project_archived`. The project operations on this page still work on it by id or slug with a company-level key: you can read it and its charges, rename it, top up or reduce its allowance, change its limits, and restore it. Its own project keys stop working. If an archived project is a company-level key's default project, the key keeps working for everything else, and a request that names no project is refused with `403 project_archived`. ## Give each client its own brand Playbooks and documents are written as a seller: a brand profile. A request can name one with `brand_profile_id` or `brand_profile_key` (playbooks) or `brand` (documents). When it doesn't, the run sells as your company's default brand: the first brand your company created, unless you made another the default, or a placeholder "Blackpearl" profile if it has none. If you resell, that's your client's seller identity, so give each client project its own default brand: 1. Create the client's brand with `POST /v1/brands` (operation `create_brand_v1_brands_post`), naming the client's project in the `Blackpearl-Project` header. It returns a brand research job whose `input.brand_profile_id` is the new brand's id; the brand exists straight away, and the research fills in its guideline. Wait for the job to succeed before running the client's work: playbooks then get the researched brand as well as its name, and documents need it. Research is a run like any other: it needs the `brands` capability (check `GET /v1/capabilities`) and is charged to that project. Leave `is_default` false: it would change your company's default brand, not the client's. Brands belong to your company, not to a project: any of your keys, including a project key, can list and read every brand. If brand names are sensitive, don't give a client a project key of its own. See [Brands](https://engine.neraperla.com/docs/brands). ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/brands" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Blackpearl-Project: client-a" \ --header "Idempotency-Key: client-a-brand" \ --header "Content-Type: application/json" \ --data '{"company_name": "Client A Security", "website_url": "https://client-a.example"}' ``` 2. Set it as the project's `default_brand_profile_id`, when you create the project or later with `update_project`: ```bash curl --fail-with-body --silent --show-error \ --request PATCH "$BLACKPEARL_API_BASE_URL/v1/projects/client-a" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Content-Type: application/json" \ --data '{"default_brand_profile_id": "brand_9d2e4f6a8b0c1d3e"}' ``` The response is the project, with `"default_brand_profile_id": "brand_9d2e4f6a8b0c1d3e"`. Send `null` to clear it; leave the field out to keep it unchanged. From then on, a playbook or document for that project that names no brand sells as the client. The brand is chosen in this order: 1. the brand in the request; 2. for playbooks, the brand of the organization playbook template the request selects, if it has one; 3. the project's `default_brand_profile_id`; 4. your company's default brand. The default must be an active brand of your company: another company's brand or an unknown id returns `404 brand_profile_not_found`, and an archived one `409 brand_profile_archived`. If you archive a brand that is still a project's default, that project's runs that name no brand are refused with `409 brand_profile_archived` rather than written for the wrong seller. Set a new default, or name a brand in the request. The number of active brands per company is limited; past the limit, creating a brand returns `409 conflict`. Archive brands you no longer use, or contact support if you need more for your clients. ## Give the project an allowance An allowance is a spending limit for one project. It isn't money: the money stays in your company balance. It never resets, and you top it up when your client renews. Turn it on with `set_project_limits`. Every field is required; send `null` for no limit (a daily or monthly limit must be above $0, and a `min_to_start_usd` of `0` means no minimum): ```bash curl --fail-with-body --silent --show-error \ --request PUT "$BLACKPEARL_API_BASE_URL/v1/projects/client-a/limits" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Content-Type: application/json" \ --data '{ "allowance_enabled": true, "min_to_start_usd": 5, "daily_limit_usd": 50, "monthly_limit_usd": null }' ``` Then top it up with `top_up_project_allowance`: ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/projects/client-a/allowance" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Content-Type: application/json" \ --data '{"amount_usd": 100, "reference": "invoice-1042", "note": "October renewal"}' ``` `amount_usd` is from $0.01 to $1,000,000; outside that range returns `422 invalid_request`. `reference` is your own id for the top-up, such as an invoice or payment id: up to 128 letters, digits, `.`, `_`, `:`, `/` and `-`, starting with a letter or digit. It makes the call safe to retry: - A new reference adds the amount and returns `201` with `"replayed": false`. - The same reference and amount again adds nothing and returns `200` with the original top-up and `"replayed": true`. - The same reference with a different amount, or a reference already used for a reduction, returns `409 conflict`. Every top-up is kept in an append-only log. `get_project_allowance` returns the allowance and its log, newest first, with cursor pagination, so you can reconcile it against your clients' payments and refunds. ### Reduce an allowance when you refund a client When you refund your client, take the refunded amount off their project's allowance with `reduce_project_allowance`. Send the amount as a positive number: ```bash curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/projects/client-a/allowance/reductions" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Content-Type: application/json" \ --data '{"amount_usd": 40, "reference": "refund-1042", "note": "Refund of unused October allowance"}' ``` - `amount_usd` and `reference` follow the same rules as for a top-up. The same reference and amount again takes nothing more off and returns `200` with `"replayed": true`. References are unique per project across top-ups and reductions, so a reference already used for a different amount or for a top-up returns `409 conflict`. - A reduction can't take the project's total granted below zero. Taking off more than has been granted returns `409 conflict` and records nothing. - It can take what remains below zero when the client has already spent more than the new total. Runs in progress finish and are charged; the project's next runs are refused with `budget_exceeded` until you top it up. Other projects aren't affected. A reduction appears in the log with `"kind": "reduction"` and a negative `amount_usd`; top-ups have `"kind": "top_up"`. The amounts in the log add up to `granted_usd`. The allowance object reports: - `granted_usd`: the total of every top-up less every reduction; - `charged_usd`: what the project's runs were charged since the allowance was first enabled. Turning the allowance off and on again doesn't restart this count: charges made while it was off still count; - `held_usd`: what runs still in progress hold (see below); - `remaining_usd`: granted minus charged, which can go negative after an overshooting run or a reduction; - `available_usd`: remaining minus held. This is what a new run is checked against. ## Minimum to start and parallel runs A run's price isn't known until it finishes, so the minimum to start (`min_to_start_usd`) sets how much allowance a run needs before it starts. Each run in progress holds that amount until it is charged, so starting several runs at once needs that many times the minimum. For example, with $12 available and a $5 minimum, two runs can start and a third is refused until one finishes. Without a minimum, a run starts whenever the available allowance is above $0. Runs then hold nothing, so several runs started at the same moment can all start and together take the allowance further below zero. Set a minimum if you start runs in parallel. The minimum applies only while the project's allowance is on. Several runs, in one project or in different ones, can be in progress at the same time when your company is on an uncapped usage tier, as reseller accounts are. On a capped tier, the whole company can have only one run in progress at a time: another start is refused with `429 budget_exceeded` (`details.scope: usage_tier`) until that run finishes. See [Rate limits](https://engine.neraperla.com/docs/rate-limits#usage-tiers). A run that has started is never cut off. It finishes, keeps its results, and is charged in full, even if that takes the project's allowance below zero. The project's next runs are refused until you top it up. Other projects aren't affected. ## Daily and monthly limits `daily_limit_usd` and `monthly_limit_usd` cap a project's charges per UTC day and per UTC month. They reset at `00:00:00 UTC` each day and on the first of each month. They work alongside the allowance: a run must pass both. A limit is checked when a run starts, against what has already been charged; unlike the minimum to start, it holds nothing for runs in progress. Runs already in progress when a limit is reached all finish and are charged, so with several runs in parallel the total can pass the limit by more than one run. A run's charge counts toward the UTC day and month in which it finishes. `get_project_limits` returns every limit with what is left: ```json { "project_id": "proj_3f9c1a7d2b8e4c11", "allowance": { "enabled": true, "granted_usd": 200.0, "charged_usd": 63.1, "held_usd": 5.0, "remaining_usd": 136.9, "available_usd": 131.9, "started_at": "2026-10-01T09:30:00Z" }, "min_to_start_usd": 5.0, "daily": {"limit_usd": 50.0, "spend_usd": 12.4, "remaining_usd": 37.6, "resets_at": "2026-10-09T00:00:00Z"}, "monthly": {"limit_usd": null, "spend_usd": 63.1, "remaining_usd": null, "resets_at": "2026-11-01T00:00:00Z"} } ``` Daily and monthly limits are hard budgets, so email alerts go out at 80% and 100%, and they also appear in the budgets list on the console **Costs** page. Editing or deleting one there changes or removes the limit, and turning off its hard limit there leaves only an alert, so `get_project_limits` then reports no limit. ## Company limits and defaults `get_company_limits` and `set_company_limits` manage limits across all of your projects, plus what new projects start with. Both need a company-level key. As with a project's limits, every field of `set_company_limits` is required, including every field of `new_project_defaults`; send `null` for no limit: ```bash curl --fail-with-body --silent --show-error \ --request PUT "$BLACKPEARL_API_BASE_URL/v1/limits" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" \ --header "Content-Type: application/json" \ --data '{ "daily_limit_usd": 300, "monthly_limit_usd": 3000, "new_project_defaults": { "allowance_enabled": true, "starting_allowance_usd": 0, "daily_limit_usd": null, "monthly_limit_usd": null, "min_to_start_usd": 5 } }' ``` When a company limit is reached, every project's new runs are refused until it resets. New-project defaults apply only to projects created afterwards, over the API or in the console. With `allowance_enabled: true` and a `starting_allowance_usd` of `0`, a new client can't run anything until you top up its allowance. A starting allowance above `0` is recorded as the project's first top-up, with the reference `starting-allowance`, so don't use that reference for your own top-ups. Until you set defaults, new projects have no allowance and no limits, which is how projects behaved before. ## When a run is refused Every limit refuses with the existing `429 budget_exceeded` error. Don't retry it automatically: top up, raise the limit, or wait for `resets_at`. `error.details` says which limit refused the run. When several would, it reports one, in this order: the project's allowance (only a top-up restores it), the project's monthly then daily limit, then the company's monthly then daily limit. A hard budget for one capability, set in the console, comes after the all-capability limits of the same scope: | `details` field | Meaning | | --- | --- | | `scope` | `project` for a project's allowance or limits, `organization` for a company limit. | | `kind` | `allowance` (used up), `min_to_start` (less available than the minimum), `day`, or `month`. | | `project_id` | The project, for project-scope refusals. | | `limit_usd`, `spend_usd`, `remaining_usd` | In charged amounts. For an allowance, `limit_usd` is the total granted and `remaining_usd` is the available amount. | | `held_usd`, `min_to_start_usd` | Allowance refusals only. | | `resets_at` | When a daily or monthly limit resets; `null` for an allowance, which only a top-up restores. | ```json { "error": { "code": "budget_exceeded", "message": "A spending limit for this scope has been reached", "request_id": "req_6f1c2d3e4a5b", "details": { "scope": "project", "kind": "min_to_start", "project_id": "proj_3f9c1a7d2b8e4c11", "period": null, "capability_key": null, "limit_usd": 200.0, "spend_usd": 196.2, "held_usd": 0.0, "remaining_usd": 3.8, "min_to_start_usd": 5.0, "hard_limit": true, "resets_at": null } } } ``` The company balance still applies: when it reaches $0, every project's runs are refused with `402 insufficient_credits`, unless one of the limits above refuses the run first. See [Limits, budgets, and usage](https://engine.neraperla.com/docs/usage-quotas). ## Read a project's charges `list_project_charges` lists what each of a project's runs was charged, newest first. Filter with `from` and `to` (UTC) and page with `cursor`. Each entry is exactly the entry the company's charge history shows for that run, with the same fields and signs: a run charge is a `debit` whose `amount_usd` is negative, because it takes money from the company balance, and `balance_after_usd` is the company balance right after it. ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/projects/client-a/charges?from=2026-10-01T00:00:00Z&limit=100" \ --header "Authorization: Bearer $BLACKPEARL_COMPANY_KEY" ``` ```json { "charges": [ { "id": "ctx_5a8b2c9d1e0f3a4b", "type": "debit", "amount_usd": -2.43, "balance_after_usd": 412.57, "job_id": "job_0b1c2d3e4f5a6b7c", "capability": "prospecting", "project_id": "proj_3f9c1a7d2b8e4c11", "project_slug": "client-a", "project_name": "Client A", "created_at": "2026-10-08T12:00:00Z" } ], "has_more": false, "next_cursor": null } ``` Match `job_id` to the job you created to attribute each charge to your client's request. A client's spend is the sum of its entries' `amount_usd` with the sign flipped. ## Read the company's charge history `list_charges` (`GET /v1/charges`) lists every change to your company balance, newest first, each with the balance after it: run charges, credit purchases, gifts, adjustments, and refunds. See [Read your charge history](https://engine.neraperla.com/docs/billing#read-your-charge-history) for the fields and filters. - Narrow it to one client with `project=client-a` (id or slug) or the `Blackpearl-Project` header. Only run charges belong to a project, so a project's entries are exactly what `list_project_charges` lists: the same entries, fields and signs. Use either to reconcile a client's spend. - A company key that names no project sees every entry, even if it has a default project. A project key sees only its own project's run charges; naming another project returns `403 forbidden`. ## Alerts Your billing contacts get an email when a project's remaining allowance falls below 20% of everything granted to it, and again when it is used up or below its minimum to start, including straight after a reduction. Each alert is sent once per allowance level; a top-up or reduction re-arms it. Daily and monthly limits send budget alerts at 80% and 100%; a project limit's alert names the project, and a company limit's alert says it covers every project. ## Who can manage projects - Over the API, only a company-level key can create, rename, or archive projects, set their default brand, and change allowances and limits. A project key can read only its own project, limits, allowance, and charges; any other projects or limits call returns `403 forbidden`. - A project key still sees some company-wide information: every brand of your company (brands belong to the company, not a project), the company balance (`credits.balance_usd` in `GET /v1/usage`, and `balance_after_usd` on each charge), company-wide monthly budgets and the usage tier in `GET /v1/usage`, and price estimates. Give a client a project key of its own only if it may see these. - In the console, owners and administrators create and archive projects and keys. Restore an archived project over the API with `update_project`. Owners, administrators, and billing members manage allowances and limits on **Settings → Projects**. --- # Troubleshooting and request diagnostics > Correlate a failed call, inspect organization request records, and prepare a support-safe diagnostic package. Canonical guide: Raw Markdown: OpenAPI: ## Capture a request ID Every response includes `X-Request-ID`; every public error repeats the same value as `error.request_id`. The gateway generates a value when the client does not send one. To correlate your own logs, send an ASCII identifier of 1-128 characters that starts with a letter or digit and then uses only letters, digits, `.`, `_`, `:`, or `-`: ```bash REQUEST_ID="checkout:20260714:7f20" curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/capabilities" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "X-Request-ID: $REQUEST_ID" \ --dump-header - ``` The response echoes a valid client value. An invalid value is rejected as `422 invalid_request`, and the response carries a newly generated safe ID. Request IDs are correlation values, not authentication or idempotency controls; use `Idempotency-Key` separately on job creation. For accepted or rejected generation work, an organization console user can open **Logs**, paste the exact request ID into the search box, and inspect method, path, status, capability, time, and latency. What each run was charged is on the **Costs** page and in `GET /v1/charges` (see [Billing and auto-recharge](https://engine.neraperla.com/docs/billing)). Completion accounting can appear as another record correlated to the job ID. Read-only polling and authentication failures do not create Usage log rows, so retain the response ID for the support workflow below. ## Diagnose by failure class | Symptom or code | Check | Next action | |---|---|---| | `missing_api_key` | The request has no Bearer header. | Add `Authorization: Bearer $BLACKPEARL_API_KEY` from the server-side secret store. | | `invalid_api_key` or `expired_api_key` | Key was copied incorrectly, revoked, or expired. | Rotate to an active key; do not retry the unchanged credential. | | `project_required` | A company-level key with no default project sent a request that needs a project, without the `Blackpearl-Project` header. | Send the header with the project's id or slug. Polling a job by its ID needs no header. | | `project_not_found` | The `Blackpearl-Project` header or `project_ref` names a project that doesn't exist in the organization. | Check the id or slug with `GET /v1/projects`. | | `project_archived` or `forbidden` | The project is archived, or a project key named another project or called an operation only a company-level key can use. | Use an active project, or the right key for it. A project key's request for another project's job or campaign returns `not_found`: cross-project IDs deliberately look missing. | | `capability_disabled` | `GET /v1/capabilities` shows the capability with `enabled: false`, or doesn't list it. | Request access for your organization; organization roles can't enable a capability themselves. | | `rate_limit_exceeded` | `RateLimit-Remaining` is `0`. | Wait at least `Retry-After`/`RateLimit-Reset`, then retry with jitter. | | `quota_exceeded` | `error.details` identifies metric, scope, used, limit, and `resets_at`. | Wait for the UTC month reset or ask an administrator to change the quota. | | `budget_exceeded` | `error.details` identifies the `scope`, the `kind` of limit (`day`, `month`, `allowance`, or `min_to_start`), the `project_id`, charged spend, limit, and `resets_at`. | Wait for `resets_at`, or ask an owner, administrator, or billing member to raise the budget or limit. A project allowance doesn't reset: top it up (see [Managing your clients with projects](https://engine.neraperla.com/docs/projects)). Do not use a rate-limit retry loop. | | `insufficient_credits` | The billed organization had no positive balance at admission. A completed run whose charge exceeded the remaining balance still succeeds and leaves the balance negative. | Let auto-recharge complete or have an owner, administrator, or billing member add prepaid credit before creating new work. | | Job status `failed` | The job's public `error` and request ID are safe to record. | Stop polling, preserve the job ID, and correct non-transient input/configuration causes before creating new work. | | Audience `502` or `503` | Capability service returned an invalid response/error or was unavailable. | Retry a safe read with bounded backoff. For ambiguous creation, repeat the exact request with its persisted `Idempotency-Key`. | | Transient `502`/`503`/`504`, timeout, or connection error while polling a job | The failure occurred in transit (CDN edge, load balancer, or an outbound proxy on your network); the platform job continues regardless. | Retry the same `GET /v1/jobs/{job_id}` with bounded backoff and resume with the persisted job ID. Do not create a replacement job. If it recurs, capture the full response headers and body and include them in the support package below. | Never infer failure from a local polling timeout: it stops only the client. Keep the job ID and resume `GET /v1/jobs/{job_id}`. See [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs), [Errors](https://engine.neraperla.com/docs/errors), and [Limits, budgets, and usage](https://engine.neraperla.com/docs/usage-quotas). ## Prepare a support-safe package If the documented action does not resolve the problem, send the account's established support contact these values: - `error.request_id` or the `X-Request-ID` response value; - UTC timestamp, HTTP method, and path without sensitive query values; - HTTP status and `error.code`; - organization/project ID, the `Blackpearl-Project` value if you sent one, and the API-key prefix (never the secret key); - job/campaign ID and the non-secret `Idempotency-Key`, when relevant; and - a short reproduction sequence and whether the failure is repeatable. Do not include the Bearer credential, cookies, full request bodies, candidate exports, or other confidential data. Support can correlate the request ID with platform request records; the package does not require you to access internal logs or source code. No public status-page or generic support URL is configured in the current deployment metadata. Use the support channel named in your account agreement; public documentation will link dedicated destinations when they exist. --- # Connections > Read the provider catalog and redacted project connection metadata while live connector operations remain unavailable. Canonical guide: Raw Markdown: OpenAPI: Connectors is a Preview inventory surface, not a finished integration runtime. The catalog describes provider manifests and credential fields. Connections are encrypted, project-scoped configuration records created and rotated by organization owners and administrators in the Console. The public API is read-only. Plainly: catalog entries are not yet verifiable or consumable. No operation — public API or Console — can verify a provider credential, read provider records, write provider records, execute a sync, send a message, receive a webhook, or complete an OAuth callback; the Console's connection verify action returns "not implemented" for every provider. Catalog entries report verification as `unavailable`, and no public operation is bound to an executor. The one Console-only exception is the [CRM Schema preview](https://engine.neraperla.com/docs/crm-schema), which can read HubSpot or Salesforce schema metadata — never records — through a privately configured adapter; it does not make any catalog entry verifiable or consumable. Do not treat a configured Connection as proof that a provider is reachable, authorized, funded, or operational, and do not build a workflow that depends on a listed provider becoming consumable. ## Read the catalog Preview operation `connector_catalog_list_v1_connectors_get` returns `GET /v1/connectors`. Each entry describes a stable provider key, version, display metadata, credential field names, capabilities, limits, provenance, and verification mode. It never returns credential values. ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/connectors" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` Treat declared capabilities as reviewed inventory only. A future adapter must have its own execution, authorization, rate-limit, retry, audit, and data-rights review before a capability can become operational. ## Read configured connections Preview operation `connection_list_v1_connections_get` returns redacted `GET /v1/connections` rows for the request's project: a project key's own project, or the project a company-level key names with the `Blackpearl-Project` header (or its default project). A row identifies the provider, display label, status, catalog version, credential revision, configured field names, and timestamps. Secret values, ciphertext, key IDs, OAuth tokens, and raw verification responses are never returned. ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/connections" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` The Console stores provider credential documents encrypted with a dedicated rotation keyring. Provider secrets are distinct from the Blackpearl bearer key and must never appear in public Job inputs, URLs, free-text reasons, metadata, logs, or Outcome payloads. Because the surface is Preview, response fields and provider inventory can change incompatibly. Pin only opaque connection IDs when testing a Preview capability, and design a safe fallback when the associated executor is unavailable. --- # Inspect the CRM schema preview boundary > Understand the Console-only HubSpot and Salesforce metadata snapshot contract and its fail-closed service boundary. Canonical guide: Raw Markdown: OpenAPI: CRM Schema is a Console-only Preview capability; it has no public `/v1` operation. It is included here so Console documentation links resolve and integrators do not mistake a private adapter boundary for a supported public connector. The capability accepts only HubSpot or Salesforce Connection IDs owned by the same organization and project. Its intended scope is read-only object, field, enumeration, and relationship metadata. It cannot read CRM records, mutate a CRM, send messages, or broaden a provider token's permissions. The capability calls a private service adapter only when its service token is configured. Without that configuration the Job fails closed, makes no provider request, and persists no schema snapshot. A configured private adapter does not make the public Connector catalog operational. Treat typed issues literally, and never use incomplete or failed discovery data to configure irreversible production mappings. Provider credentials are decrypted only inside the private adapter path, must match the bound Connection revision, and must not appear in Job input, result, logs, audit metadata, or client responses. Until the capability gains a stable public contract and verified live implementation, keep it behind Console access controls and a Preview feature flag. --- # Capabilities and entitlements > Discover which capability keys the authenticated organization can use before creating work. Canonical guide: Raw Markdown: OpenAPI: Call capabilities before presenting a capability-specific workflow: ```bash curl --fail-with-body --silent --show-error \ "$BLACKPEARL_API_BASE_URL/v1/capabilities" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" | jq . ``` ```json { "capabilities": [ { "key": "playbooks", "name": "Playbooks", "description": "Generate AI sales playbooks for a target account.", "category": "Generation", "enabled": true, "status": "ga", "docs_slug": "playbooks" } ] } ``` The endpoint returns the capabilities visible to the key's organization, each with an `enabled` flag. A company-level key names a project with the `Blackpearl-Project` header (or uses its default project); without one the call returns `400 project_required`. Every generally available (`status: ga`) capability is listed whether or not it is enabled, so a client can distinguish a capability that exists but is disabled from one that does not exist. Capabilities that are not generally available appear only when they are enabled for the organization. Use `key` as the stable programmatic identifier and `docs_slug` to link to the corresponding guide. `status` is `ga` or `coming_soon`; the latter maps to Preview documentation, not a GA compatibility promise. Clients must still tolerate future additive enum values and optional response fields. Call this endpoint before planning work that spans capabilities — especially from an AI agent. Only use capabilities with `enabled: true`. When a user asks for something whose entry shows `enabled: false`, say that the capability exists but is not enabled for their organization and that access must be requested; do not retry or route around it. Organization owners and administrators can't enable capabilities themselves: Blackpearl enables them for the organization on request. A create request for a disabled capability returns `capability_disabled`. This is OpenAPI operation `capabilities_v1_capabilities_get` with schema `PublicCapabilitiesResponse`. Continue with [Prospecting](https://engine.neraperla.com/docs/prospecting), [Account research](https://engine.neraperla.com/docs/prospect-research), [Documents](https://engine.neraperla.com/docs/documents), [Audiences](https://engine.neraperla.com/docs/audiences), or [Playbooks](https://engine.neraperla.com/docs/playbooks). [Infinite Intent](https://engine.neraperla.com/docs/infinite-intent) is scoped to explicitly enabled projects. Its key is `infinite_intent`; use the guide to run an enabled programme (`world-of-claudecraft` or `coastal-retreat`) and open its hosted results page. --- # Agent connection procedure > Approve one browser request to connect your current AI session, verify access and credits, and start working. Canonical guide: Raw Markdown: OpenAPI: ## 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 `, 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. --- # Set up your AI agent > Copy the prompt, paste it into your AI chat, and approve access. Your agent handles the connection. Canonical guide: Raw Markdown: OpenAPI: ## Copy, paste, approve 1. Click **Copy connection prompt**. 2. Paste it into Claude, Cowork, Claude Code, or another AI agent and send it. 3. Open the approval link your agent gives you. Sign in, choose your project, and approve access. Approving needs the owner or administrator role in your organization. Finish any account or billing steps shown there. Your agent checks the connection and available credits, then you're ready to ask it to do work. You do not need to find an API key or install anything. The agent needs command execution with network access to complete this flow. ```text I'm setting up Blackpearl in this session. Connect me now using https://engine.neraperla.com and keep onboarding short and focused. I authorize you to check for a working Blackpearl key, request one through Blackpearl's browser approval flow if needed, and save it privately for this session. I will approve the account and project in the browser. A temporary workspace is fine; do not ask me to connect a folder. Read https://engine.neraperla.com/docs/raw/agent-setup.md and carry out that procedure. Use its API-key approval and polling flow. Start immediately without asking what to do with this prompt, proposing a plan for approval, or offering other setup methods. Reuse a working key or pending request if one already exists. Show me the approval link as soon as you have it and keep polling while I approve. Never display the key or ask me to paste one. Creating the key and checking access do not consume credits. Keep setup to those checks; do not start paid work or install or update skills, plugins, connectors, or standing instructions. Respect the host's required permissions. If a required tool or network request is unavailable, explain that specific blocker briefly; do not claim to be connected. When verified, briefly confirm the connected project and available credits. Then continue any task I've already requested, or ask what I'd like to do. ``` ## What to expect Your agent sends an approval link, waits while you approve, and confirms the connection. **Creating a key and checking access do not consume credits.** Paid work is charged to your organization's balance and counts against the chosen project's limits when you request it. A temporary workspace works for this session. A fresh session may need approval again. If a key is already available, your agent reuses it. You can revoke access from **API keys** in the Blackpearl console. If the agent cannot read the setup guide, paste the [connection instructions](https://engine.neraperla.com/docs/agent-setup) into the same chat. For an explicitly chosen connector or saved skill, see [Optional agent integrations](https://engine.neraperla.com/docs/agent-integrations). --- # Optional agent integrations > Configure an OAuth connector, documentation tools, or a saved skill when you specifically need one. Canonical guide: Raw Markdown: OpenAPI: Setting up an AI session for the first time? Use [Set up your AI agent](https://engine.neraperla.com/docs/agent-resources). The integrations below are optional and separate from that connection flow. Use them when the user explicitly chooses an integration or the session cannot run the API-key setup procedure; do not make them extra onboarding steps. ## Use the platform from claude.ai — the platform MCP connector The platform itself is available as a remote MCP connector: an OAuth-protected server at `https://engine.neraperla.com/mcp` that lets Claude run real platform work in your organization — no code and no API-key handling. 1. In claude.ai, open **Settings → Connectors** and choose **Add custom connector**. 2. Enter `https://engine.neraperla.com/mcp` as the remote MCP server URL. 3. Sign in to your Blackpearl account when prompted and approve the consent screen. Approving needs the owner or administrator role, and billing must be set up. Consent binds the connection to exactly one organization and one active project; every later tool call runs in that project. To work in a different project, connect again and choose it on the consent screen. 4. In a chat, project, or Cowork session, enable **Blackpearl Platform** from the tools menu. Any MCP client that supports OAuth 2.1 authorization with dynamic client registration can connect the same way. In Claude Code: ```bash claude mcp add --transport http blackpearl-platform https://engine.neraperla.com/mcp ``` ### Connector tools | Tool | What it does | |---|---| | `run_playbook` | Create an asynchronous Playbooks generation job for a target company, selling as the connected project's default brand when it has one. | | `run_prospecting` | Create an asynchronous prospecting run that discovers and qualifies prospects from a campaign name, product description, and objective, with an optional targeting `query` and `booking_url`. The run returns every prospect the agent delivers, up to 5,000. | | `run_campaign_cycle` | Start one Audience cycle for an existing saved campaign in the connected project. | | `run_infinite_intent` | Run an [Infinite Intent](https://engine.neraperla.com/docs/infinite-intent) programme enabled for the connected project (`world-of-claudecraft` or `coastal-retreat`), optionally naming an uploaded intent file and its row count. The result links to a hosted report that only its designated viewer can open after signing in. | | `enrich_contacts` | Fill contact and company fields from the platform's data: up to 10 contacts synchronously, up to 1,000 as an asynchronous batch. | | `get_job_status` | Poll an asynchronous job's status, progress, and stage timeline. | | `share_playbook` | Get the password-protected public share link for a succeeded Playbooks job's branded, rendered page. Repeated calls return the same link. | | `get_job_results` | Fetch a completed job's typed result; Audience results return cursor-paged candidates, and Prospecting results return their prospects 50 at a time (`prospects_page.next_cursor`). | | `get_usage_summary` | Month-to-date usage, quotas, usage tier, and prepaid-credit balance for the connected project. | | `get_pricing_estimates` | Typical price of one unit of each capability at the connected organization's rates, for quoting before running work. | | `list_charges` | What each of the connected project's runs was charged, newest first, with the organization's balance after each charge. | Creation tools return a job ID; Claude then polls `get_job_status` and fetches `get_job_results` — the same create → poll → result flow as the [Jobs API](https://engine.neraperla.com/docs/jobs), with the same durations, so expect a Playbooks run to take minutes, not seconds. Tools see only the connected project's jobs and campaigns. Prices from `get_pricing_estimates` are organization-wide, like `GET /v1/pricing-estimates`. ### Billing, gates, and tokens Connector runs are real runs. Every tool call passes the same admission gates as the `/v1` API — capability entitlement, quota, budgets, the connected project's allowance and daily and monthly limits, usage-tier cap, and prepaid credits — and completed work is charged to your company balance and counted against the connected project exactly like an API-key call in that project. A refused call returns a tool error that starts with the same `error.code` as `/v1`, for example `insufficient_credits` or `budget_exceeded`. Each connection has its own request-rate limit, sized by your usage tier like an API key's. If the connected project is archived, tool calls fail until it is restored. See [Limits, budgets, and usage](https://engine.neraperla.com/docs/usage-quotas), [Managing your clients with projects](https://engine.neraperla.com/docs/projects), and [Billing and auto-recharge](https://engine.neraperla.com/docs/billing). Connector access tokens are audience-bound: a connector token is rejected by `/v1/*`, and a `bp_live_` API key, project or company-level, is rejected by `/mcp`. Neither credential substitutes for the other. ### Manage and revoke connections Connections are listed in the console under **Settings → Connected apps**, where owners and administrators can revoke them. A connection never outlives the approving user's access: removing the approver from the organization (or deactivating them) revokes the connection, and reducing the approver's role below API-key-issuance rights blocks it until the role is restored. ## Connect the docs to your AI ### Claude (claude.ai and Cowork) The documentation is available as a claude.ai connector — two minutes, no code, no credentials: 1. In claude.ai, open **Settings → Connectors** and choose **Add custom connector**. 2. Enter `https://engine.neraperla.com/docs/mcp/` as the remote MCP server URL. The server is public and read-only, so no OAuth or API key is required. 3. In a chat, project, or Cowork session, enable the connector from the tools menu. Claude can then search and read every guide on this site. ### Claude Code ```bash claude mcp add --transport http blackpearl-docs https://engine.neraperla.com/docs/mcp/ ``` Run `/mcp` in Claude Code to confirm the server and its `search_documentation`, `get_documentation`, and `documentation_sources` tools are available. ### Codex Add the Streamable HTTP server to `~/.codex/config.toml`, or use `.codex/config.toml` in a trusted project: ```toml [mcp_servers.blackpearl_docs] url = "https://engine.neraperla.com/docs/mcp/" ``` ### Cursor Create `.cursor/mcp.json` for a project or `~/.cursor/mcp.json` globally: ```json { "mcpServers": { "blackpearl-docs": { "type": "http", "url": "https://engine.neraperla.com/docs/mcp/" } } } ``` ### VS Code agent mode Create `.vscode/mcp.json` in the workspace: ```json { "servers": { "blackpearl-docs": { "type": "http", "url": "https://engine.neraperla.com/docs/mcp/" } } } ``` Client configuration formats follow the current official setup references for [Claude Code](https://docs.anthropic.com/en/docs/claude-code/mcp), [Codex](https://learn.chatgpt.com/docs/extend/mcp), [Cursor](https://docs.cursor.com/context/model-context-protocol), and [VS Code](https://code.visualstudio.com/docs/agent-customization/mcp-servers). ## Optional: install the platform skill The skill below points agents to the relevant capability guides. Install this only when the user asks to retain the workflow for future sessions, using the host application's normal installation/review controls. It is not needed to connect or start work. In Claude Code, save it as `.claude/skills/blackpearl-platform/SKILL.md`; on claude.ai, it can be added to project instructions. Installation does not itself persist API credentials. ```markdown --- name: blackpearl-platform description: Drive the Blackpearl GTM data & intelligence API — create brand and offer context, run prospecting, generate playbooks and documents, record outcomes. Use when the user asks for prospecting lists, sales research, playbooks, audiences, campaigns, or GTM data and integrations. version: 2026-10-11.1 --- # Blackpearl Platform Blackpearl is the GTM data & intelligence API: evidence-backed prospecting, audiences, account research, stage-aware playbooks, sales documents, message templates, and an outcomes feedback loop, behind one API key. Authenticate every call with `Authorization: Bearer $BLACKPEARL_API_KEY` against `$BLACKPEARL_API_BASE_URL` (default `https://engine.neraperla.com`). With a company-level key, also send `Blackpearl-Project` (the project's id or slug) on requests that create work or read project data. ## Current guidance Fetch the current task's documentation from https://engine.neraperla.com/docs/raw/ as needed. The optional skill's canonical copy lives at https://engine.neraperla.com/docs/raw/agent-integrations.md. Do not automatically replace this skill or any standing instructions. Updates use the host application's normal review/installation flow when the user requests them; they never block a working connection. ## Rules 0. Credentials: authenticate with the key in `$BLACKPEARL_API_KEY` (or load `.env` explicitly). For setup or credential recovery, follow https://engine.neraperla.com/docs/raw/agent-setup.md. Reuse a verified key; transient network errors and billing/permission failures are not reasons to mint another. Never print a full key, a poll URL, or the raw key-delivery response. If using the authenticated platform MCP connector, use its tools within their granted scope; do not request an API key unless the user's task requires an API operation that connector does not expose. 1. Before planning, call `GET /v1/capabilities`. Use only capabilities with `enabled: true`. If the user asks for something listed with `enabled: false`, say it exists but is not enabled for their organization and must be requested — never silently work around it. 2. The only input you need from the user is their company website URL (plus anything they volunteer). Do not ask for industries, job titles, seniority levels, or company sizes — deriving targeting is the platform's job. 3. For a requested GTM task, reuse relevant Brand and Offer context. If it is missing, create a Brand from the company URL and run its research, then draft an Offer from that research. Confirm your draft in one message. Connection-only setup uses read-only checks and does not start paid work. 4. For prospecting, derive `product_info` and `objective` from the Brand and Offer. Leave the structured `target` empty unless the user explicitly constrains it. Don't send `limit` or `min_qualification_score`: both are deprecated and ignored. `qualification.score` is the search agent's own fit score for that run, not comparable across runs: don't cut prospects by score; use `qualification.status` and the evidence. 5. Read the operation's guide before executing it: some creates return stored objects or synchronous results; job-creating operations return an async job. Follow https://engine.neraperla.com/docs/raw/jobs.md for polling, timeouts, and recovery. Use `Idempotency-Key` where the operation supports it and reuse the same value on retries; never duplicate a run after a transient error. 6. Handle errors by `error.code` (machine-readable, documented per code). Never fabricate prospects or results; a prospect with `is_synthetic: true` is not an actionable lead. 7. Record real-world results through Outcomes so the system improves; the platform never sends outreach — delivery is your side of the integration. ## Where to look things up Fetch only what the task needs; every page is plain Markdown: - End-to-end workflow (start here): https://engine.neraperla.com/docs/raw/gtm-workflow.md - Quickstart and auth: https://engine.neraperla.com/docs/raw/getting-started.md and https://engine.neraperla.com/docs/raw/authentication.md - Jobs and polling: https://engine.neraperla.com/docs/raw/jobs.md - Errors and retries: https://engine.neraperla.com/docs/raw/errors.md - Projects, company-level keys, and charges: https://engine.neraperla.com/docs/raw/projects.md and https://engine.neraperla.com/docs/raw/billing.md - Capability contracts: https://engine.neraperla.com/docs/raw/prospecting.md, playbooks.md, brands.md, offers.md, campaigns.md, audiences.md, documents.md, message-templates.md, outcomes.md (same path pattern) - Guide index: https://engine.neraperla.com/llms.txt - Exact request/response schemas: https://engine.neraperla.com/v1/openapi.json - Documentation search (MCP): https://engine.neraperla.com/docs/mcp/ ``` ## Direct sources | Resource | URL | Use | |---|---|---| | Documentation index | [`llms.txt`](https://engine.neraperla.com/llms.txt) | Curated guide descriptions and direct Markdown links. | | OpenAPI | [Download JSON](https://engine.neraperla.com/v1/openapi.json) | Exact paths, authentication, fields, enums, constraints, and response schemas. | | Documentation MCP | `https://engine.neraperla.com/docs/mcp/` | Search and retrieve canonical public pages with citation URLs. | | Platform MCP connector | `https://engine.neraperla.com/mcp` | OAuth-protected; run playbooks, prospecting, campaign cycles, Infinite Intent, and enrichment, share playbooks, and read usage, prices, and charges from claude.ai or any MCP client. | Every guide is also available at `https://engine.neraperla.com/docs/raw/{slug}.md`, generated from the same canonical Markdown as the website. --- # Playbooks API primer for agents > Give a coding agent the minimum complete contract for creating, polling, and consuming a Playbooks job safely. Canonical guide: Raw Markdown: OpenAPI: Use this page with the canonical [OpenAPI document](https://engine.neraperla.com/v1/openapi.json). OpenAPI is authoritative for exact schemas; this primer is authoritative for the integration sequence and operational decisions. ## Contract at a glance - Base URL: `BLACKPEARL_API_BASE_URL`, configured for the deployment. - Authentication: `Authorization: Bearer $BLACKPEARL_API_KEY` on every `/v1` request. A project key needs nothing else. A company-level key also sends `Blackpearl-Project` (the project's id or slug) on the create, or fails with `400 project_required` unless it has a default project; polling by job ID needs no header. - Create: `POST /v1/playbooks` using operation `create_playbook_v1_playbooks_post` and schema `PlaybookInput`. - Poll: `GET /v1/jobs/{job_id}` using operation `get_job_v1_jobs__job_id__get`. - Create response: `202 Accepted` with schema `PublicPlaybookJobResponse`. - Create retry safety: send `Idempotency-Key`; matching retries replay the original response for 24 hours. - Result: when the job succeeds, `result` is schema `PublicPlaybookResult`. - Retention: `expires_at` is 30 days after creation; store results needed after that time. - Errors: schema `ErrorResponse`; branch on `error.code`, not HTTP status alone. Create separate projects and keys for development, staging, and production. Hosted development calls still perform real work and record real usage. ## Minimal request Set the configured API URL and a server-side project key: ```bash export BLACKPEARL_API_BASE_URL="https://engine.neraperla.com" export BLACKPEARL_API_KEY="replace-with-your-project-key" export BLACKPEARL_IDEMPOTENCY_KEY="playbook-$(date +%s)-$$" curl --fail-with-body --silent --show-error \ --request POST "$BLACKPEARL_API_BASE_URL/v1/playbooks" \ --header "Authorization: Bearer $BLACKPEARL_API_KEY" \ --header "Idempotency-Key: $BLACKPEARL_IDEMPOTENCY_KEY" \ --header "Content-Type: application/json" \ --data '{"target_company_domain":"acme.example"}' ``` Provide at least one of `target_company` or `target_company_domain`. A domain is a hostname without a scheme or path. Optional `tone` values are `consultative`, `direct`, and `technical`; `model` is currently `default`. Omit `sections` for the complete result. Persist the idempotency key before the first request and the returned `id` immediately after success. If the connection is lost or a server response is ambiguous, repeat the exact POST with the same key within 24 hours. A matching request returns the original response without creating or billing another job. A changed request returns `idempotency_key_reused`; `idempotency_in_progress` means retry the same request and key after a short delay. ## Poll every terminal state Wait 2 seconds before the first GET, then use exponential backoff with jitter and settle at a steady 15–30 second interval: Playbooks generation typically takes about 10–20 minutes, and faster polling does not shorten it. Apply a caller deadline generous relative to that duration and retain the job ID so polling can resume later. A client timeout does not cancel server work. A single poll that fails in transit (a connection error or a `502`/`503`/`504` from intermediary infrastructure) is retryable and does not mean the job failed; retry the same GET with backoff instead of creating a replacement job. | Status | Terminal | Action | |---|---:|---| | `queued` | No | Wait and poll again. | | `running` | No | Optionally show `progress`, then poll again. | | `succeeded` | Yes | Validate and consume the typed `result`. | | `failed` | Yes | Stop and surface the job `error`. | | `canceled` | Yes | Stop; there is no public cancel operation. | On success, useful first outputs are `result.business_summary` and the first item in `result.sales_angles`. Collections are arrays. Research-derived scalar fields can be null; follow `PublicPlaybookResult` rather than inventing fallback fields. ## Errors, retries, and usage - `rate_limit_exceeded` is transient. Wait at least the `Retry-After` value, then retry with bounded backoff and jitter. - `quota_exceeded` and `budget_exceeded` also use status `429`, but require a reset or configuration change. Do not automatically retry them. - Authentication, entitlement, and validation codes require the caller to change credentials, project state, access, or input. - A safe GET may be retried for a documented transient `5xx`. Repeat an ambiguous create POST only with its original idempotency key and exact input. - Polling is rate-limited but does not start another billed Playbooks generation. The completed job's `usage.cost_usd` is what it was charged (`0` for a failed job); reconcile project totals through `GET /v1/usage` and individual charges through `GET /v1/charges`. - A job or candidate read after `expires_at` returns `410 job_expired`. Create a new job if no client-stored result exists. ## Do not assume - Do not assume a key prefix creates a sandbox. - Do not assume a fixed completion-time SLA, fixed request-per-minute limit, or cancellation endpoint. - Do not assume an idempotency key remains replayable after 24 hours or can be reused with different input. - Do not wait only for `succeeded`; all three terminal states stop polling. - Do not treat every `429` or `5xx` as retryable. - Do not expose a project key in browser or mobile code. For complete examples, use the [Quickstart](https://engine.neraperla.com/docs/getting-started). For field interpretation and recovery details, use [Playbooks](https://engine.neraperla.com/docs/playbooks), [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs), [Errors and retry decisions](https://engine.neraperla.com/docs/errors), and [Limits, budgets, and usage](https://engine.neraperla.com/docs/usage-quotas). --- # Roles and console access > See what each console role can do, and how API keys are authorized separately from roles. Canonical guide: Raw Markdown: OpenAPI: Console users belong to an organization with one role: `owner`, `admin`, `member`, `billing`, or `viewer`. | Role | What it can do | |---|---| | `owner` | Everything an administrator can, plus invite owners, change an owner's role, and remove an owner. An organization always keeps at least one owner. | | `admin` | Everything `member` and `billing` can, plus: create, rename, and archive projects; create and revoke project and company-level API keys; approve AI-agent and connector access and revoke connections; invite and manage members other than owners; set quotas; manage brand profiles, offers, playbook templates, campaign schedules, and provider connections; and change organization settings. | | `member` | Run enabled capabilities, start campaign cycles, cancel jobs, share playbooks, and read the project's work. | | `billing` | Add credits; manage payment details and auto-recharge; create, change, and delete budgets; and manage project allowances (top-ups and reductions), project daily and monthly limits, and company limits. It can't run capabilities or manage projects, keys, or members. | | `viewer` | Read-only. | No organization role enables a capability. Capabilities are enabled for your organization by Blackpearl: when `GET /v1/capabilities` lists one with `enabled: false`, request access. See [Capabilities and entitlements](https://engine.neraperla.com/docs/feature-flags). ## API keys are not user sessions The console authenticates with an HTTP-only session cookie. Public `/v1` integrations don't use that cookie and don't inherit anyone's role: authority comes from the key type, as described in [Authentication](https://engine.neraperla.com/docs/authentication). - A project key acts only in its own project. It can read its own project, limits, allowance, and charges, but can't manage projects. - A company-level key acts in every project of the organization, and over the API it can create, rename, and archive projects and change their allowances and limits. See [Managing your clients with projects](https://engine.neraperla.com/docs/projects). Removing a member does not revoke the API keys they created; connector connections they approved are revoked. Revoke keys you no longer need under **API keys**. Organization invitations are deliberate and role-specific. Do not share personal credentials or API keys to work around missing membership. Administrators should issue the appropriate membership and create separate keys for deployed services: a project key per service and environment, or a company-level key for an integration that serves several projects. --- # Workbench guide > Run any enabled capability interactively in the console, inspect jobs and usage, then copy the exact API request for automation. Canonical guide: Raw Markdown: OpenAPI: The console is an interactive workbench over the same capability implementations as the public API. The sidebar groups capability pages into workspaces: **Prospecting** (prospecting runs, campaigns, and audiences), **Research** (playbooks and their templates, company research, enrichment, and site intelligence), **Outreach** (messages, message templates, and documents), and **Assets** (brands and offers). Other enabled capabilities have their own sidebar entries, and **All capabilities** lists every capability with its status. On each page you create work, watch job status, and review the result. Console actions expose the exact API request through **View code**, so a run you like can be handed to code or an agent unchanged. A typical exploration: 1. Select the project that should own usage and charges. 2. Open a capability page from its workspace in the sidebar and enter its documented inputs — a target company for Playbooks, identifiers to enrich for Enrichment, a brief for Documents. 3. Submit, watch job status and progress, then review the rendered result and its usage. 4. Use **View code** to copy the equivalent API call for automation. Workbench requests perform real work on hosted deployments and record real usage. A development project isolates that work but does not simulate it. A capability that is not enabled for your organization shows a locked state instead of executing, and specification-preview surfaces store plans without running anything — the console reflects the same execution boundaries as the API. For automation, start with the [Quickstart](https://engine.neraperla.com/docs/getting-started). Job behavior is in [Jobs and resumable polling](https://engine.neraperla.com/docs/jobs), failures are handled with [Errors and retry decisions](https://engine.neraperla.com/docs/errors), and each capability's exact request values are in its own guide — for example [Playbooks](https://engine.neraperla.com/docs/playbooks) or [Enrichment](https://engine.neraperla.com/docs/enrichment). --- # Security and data handling > Review credential boundaries, project isolation, capability data flow, retention, and logging behavior. Canonical guide: Raw Markdown: OpenAPI: ## Credential boundary Public API keys are secrets. A project key acts only in its own project; a company-level key can act in every project of your organization and, over the API, create and archive projects and change their allowances and limits, so protect it like an administrator credential. The console displays a new secret once; the gateway stores only its hash for later authentication. Keep the key in a server-side secret manager, inject it into the calling process at runtime, and send it only in the `Authorization: Bearer ...` header over HTTPS. Never commit it, put it in a URL, paste it into a support request, or embed it in browser, desktop, or mobile code where an end user can extract it. Rotate without downtime by creating a replacement key of the same type (in the same project, for a project key), deploying it to every server-side caller, confirming traffic on the replacement, and then revoking the old key. Revocation and configured expiry stop new authentication immediately. The platform's private capability-service credentials remain at the gateway and are not returned to API clients or forwarded from the client's Bearer key. ## Tenant and ownership boundaries Authentication resolves the organization from the key and one project for each request: a project key's own project, or, for a company-level key, the project named by the `Blackpearl-Project` header, else the project of the job, campaign, or audience the request addresses, else the key's default project. Public campaign and job operations enforce that boundary: a project key gets `404 not_found` for an ID owned by another project, including when the caller knows the ID, and a project key that names another project gets `403 forbidden`. Usage and charges are attributed to the project the work ran in, while matching organization-, project-, key-, and capability-scoped controls can govern new work. Brands and offers belong to the organization, not to a project: any of the organization's keys, including a project key, can list and read them. If you run a project per client and one client must not see another's brand names, don't give that client a project key of its own. See [Managing your clients with projects](https://engine.neraperla.com/docs/projects). Use separate projects and keys for development, staging, production, or customers whose jobs and accounting must be isolated. A key is not a user session and does not inherit console membership roles. See [Authentication and project environments](https://engine.neraperla.com/docs/authentication) for the lifecycle and [Roles and console access](https://engine.neraperla.com/docs/rbac) for the authorization model. ## Data sent for capability work The gateway stores the validated public input and sends the fields needed to the configured private capability service: | Capability | Data sent upstream | Data returned and retained by the platform | |---|---|---| | Playbooks | Target company name or domain, anchor-company and product context, requested tone/sections, a job correlation value, and the selected brand profile's branding snapshot when present. | Generated account research, personas, sales guidance, attributed usage, and private backend correlation diagnostics. | | Audiences | Campaign name and objective, website/product/ICP/additional context, target size and workflow settings, excluded domains, reusable campaign setup artifacts, and organization/job correlation values. | Candidate summary, candidate pages fetched from the capability service, reusable setup artifacts, delivered-domain deduplication data, stage state, usage, cost, and private backend correlation diagnostics. | | Message Templates | Template generation sends the validated audience, objective, offer summary, desired next step, copy controls, and selected Brand/Offer/Campaign snapshots to a third-party model provider with provider-side storage disabled. Prospect personalization sends no prospect identity, work email, retained evidence, sender identity, or compliance data to a model provider; it verifies platform ledgers and renders the selected immutable revision locally. | Immutable structural revisions, generation input/result, private billing attribution and response correlation IDs, plus personalization inputs and approval artifacts. Personalization job data can include prospect and sender identity, work email, retained evidence references, and compliance attestations/verifications. | Do not submit secrets or regulated personal data in free-text targeting, product, or additional-context fields unless your agreement explicitly permits it. Candidate output can include business contact data; apply your own access, lawful-use, export, and deletion controls after retrieval. The platform uses separately configured service credentials for upstream calls—your project API key is not sent to capability services. ## Retention and deletion Every public job publishes `expires_at`, exactly 30 days after creation. Until then, the gateway exposes owned job metadata, input, result, and Audience candidates. Client timeout does not cancel execution; retain the job ID and resume polling. Store any result your application must keep beyond `expires_at` in a system with your required security and deletion policy. Message personalization refuses a Prospecting source job as soon as its `expires_at` boundary is reached, both when accepting the request and again before execution. This prevents a queued job from reusing prospect PII after the source retention window closes. After expiry, public job and candidate reads return `410 job_expired`. Scheduled cleanup removes the platform-retained job input, result, error detail, stages, and private job diagnostics, while keeping a minimal ownership/status tombstone. Append-only usage, billing, credit, and audit ledgers remain for accounting and security requirements. The 30-day gateway cleanup is not a promise that a configured upstream capability service has deleted its own operational records; upstream deletion obligations are governed by the applicable service agreement. ## Logs, errors, and request IDs The gateway request log records request ID, method, path, status, latency, and client IP. It does not write the `Authorization` header, query string, or request/response body in that log. Public errors replace unexpected internal failures with a stable safe message. Usage and audit records can store request correlation metadata, principal IDs, operation names, status, and accounting values; job payload and private backend diagnostics are retained as described above. Send a valid `X-Request-ID` to correlate a call, or use the generated ID returned in the `X-Request-ID` response header and `error.request_id`. A request ID is not a secret, but it must never be used as a substitute for authentication. Follow [Troubleshooting and request diagnostics](https://engine.neraperla.com/docs/troubleshooting) to prepare a support-safe diagnostic package. ## Hosted Infinite Intent reports [Infinite Intent](https://engine.neraperla.com/docs/infinite-intent) reports require a valid Blackpearl browser session and an explicit viewer grant. Other signed-in users receive 404, including project members and platform admins. Signed-out visitors sign in before returning to the page. URLs and legacy share tokens grant no access. Reports expire with job retention, use private/no-store responses, and isolate report scripts from application cookies/storage while blocking network calls. --- # API compatibility and deprecation > Build tolerant v1 clients and understand additive changes, previews, deprecation notices, and support windows. Canonical guide: Raw Markdown: OpenAPI: ## The v1 compatibility boundary `/v1` is the public API version. Every OpenAPI operation carries `x-stability: ga` or `x-stability: preview`; stability is classified per operation rather than inferred from the URL version. The checked-in contract is generated, semantically linted, and compared with the prior contract in CI using the same rules described here. The platform can make these compatible additive changes within `/v1`: - add an operation, an optional request field, or an optional request header (for example `Blackpearl-Project`); - add an optional response field or response header; - add a new documented error code or optional structured error detail; - add a value to an enum; and - add a preview capability or operation without changing a GA operation. Clients must ignore unknown response object fields and unknown response headers. Treat enum values as open sets at runtime: preserve or surface an unknown value instead of crashing, even if generated types model the known values. Use a default branch for unknown `error.code` values and decide retry behavior conservatively from HTTP semantics and documentation. ## Changes that require another version The platform will use a new URL version rather than silently making a GA `/v1` change that removes or renames an operation or field, newly requires previously optional input, changes a field's type or established meaning, removes or narrows enum values, removes a successful response representation, or changes authentication and project-ownership semantics incompatibly. A new version can run alongside `/v1` during migration. Contract-diff CI automatically rejects mechanically detectable examples such as removed paths/operations/properties, newly required fields, narrowed enums, incompatible types, required parameters, required request bodies, and removed successful response codes or media types. Review is still required for semantic changes that a schema diff cannot identify. ## Preview and GA expectations GA operations receive the compatibility and deprecation protections on this page. Preview operations are identified by `x-stability: preview` in OpenAPI and a Preview label in documentation. Preview shapes can change or be withdrawn before GA, with changes recorded in the changelog, and do not receive the GA support window. Moving a preview operation to GA establishes its compatibility baseline; moving a GA operation back to preview is not compatible. ## Deprecation and removal An incompatible GA replacement is introduced under a new API version. The platform will support the superseded GA version for at least 12 months after its replacement reaches GA and will publish a deprecation notice at least 180 days before shutdown. The notice identifies affected operations, the replacement, migration guidance, and the earliest shutdown date. If the two windows imply different dates, the later date applies. Security or legal emergencies can require faster protective action. When feasible, the platform will prefer a compatible mitigation and communicate the exception through the same documentation channels. Review the published [API changelog](https://engine.neraperla.com/docs/api-changelog.md) for observable changes and the generated [OpenAPI contract](https://engine.neraperla.com/v1/openapi.json) for exact current shapes.