API Reference
The Papayya REST API. Base URL: https://api.getpapayya.com
The nouns match the rest of Papayya: an agent is the deployable unit; each run is one invocation that processes items; every item has an outcome, a cost, and a step trace; a trigger is an inbound invocation hook.
All protected endpoints require a Bearer token (JWT or API key) in the Authorization header:
Authorization: Bearer cpk_your_api_keyAgents
Create agent
POST /v1/agents{
"name": "research-agent",
"description": "Researches topics using web search",
"model": "claude-sonnet-4-20250514",
"instructions": "You are a research assistant...",
"max_steps": 10,
"budget_cents": 50,
"tools": [
{ "name": "web_search", "description": "Search the web", "parameters": {} }
]
}List agents
GET /v1/agents
GET /v1/agents?project_id=proj_abc123Get agent
GET /v1/agents/{agentId}Update agent
PATCH /v1/agents/{agentId}Create agent version
POST /v1/agents/{agentId}/versionsTwo counters, one of them dispatchable. An agent version is a snapshot of the agent's config — version 1 is written when the agent is created, and the number is bumped by this endpoint and by a config
PATCH. A deployment is a packaged code bundle, written bypapayya deploy. Runs execute the latest deployment; the agent-version number tells you nothing about what code will run.So an agent can carry config version 3 while the newest packaged bundle is version 1 — editing config without redeploying leaves the newer config unpackaged, and the run executes the deployed bundle. Anything that requires "a deployed agent" (creating a schedule, firing a trigger) is checking for a deployment, not an agent version.
Runs
Trigger a run
POST /v1/agents/{agentId}/runs(The wire path is transitional; the product noun is the run.)
{
"agent_id": "ag_abc123",
"input": "Research the latest AI agent frameworks",
"max_steps": 10,
"budget_cents": 100,
"timeout_seconds": 600,
"callback_url": "https://your-api.com/callbacks/run-complete"
}| Field | Required | Description |
|---|---|---|
agent_id | Yes | Agent to run |
input | No | Input data (JSON) |
max_steps | No | Max steps (default: 50) |
budget_cents | No | Budget cap in cents (default: 500) |
timeout_seconds | No | Wall-clock run timeout in seconds (default: 1800, min: 60, max: 86400). Runs past their deadline are terminated with error_code: "run_timeout". |
callback_url | No | URL to POST run result when the run reaches a terminal state (completed, failed, cancelled, budget_exceeded) |
The timeout clock starts when the run transitions from queued to running (i.e. at started_at, not created_at). Paused runs and runs waiting on tool results do not consume their timeout budget. There is a small window (up to ~30 seconds) between deadline expiry and the run being marked failed, because the enforcement sweeper runs on a periodic tick.
When callback_url is set, Papayya POSTs a summary of the run to that URL on every terminal transition (completed, failed, cancelled, budget_exceeded). Delivery is retried up to 3 times with exponential backoff (1s, 5s, 25s) and a 10s per-attempt timeout.
The payload is a fixed shape — not the full run row. Fetch GET /v1/durable/runs/{runId} if you need the item's input or output.
{
"run_id": "9c3e...",
"item_id": "b1a2...", // present per-item on a submitted run; omitted for a single-input run
"agent_id": "a4f7...",
"status": "completed",
"current_step": 4,
"total_input_tokens": 1832,
"total_output_tokens": 412,
"total_cost_cents": 3,
"error_code": null, // set on failed / budget_exceeded
"error_message": null,
"created_at": "2026-04-22T14:32:01Z",
"completed_at": "2026-04-22T14:32:47Z"
}Each request carries X-Papayya-Signature (HMAC-SHA256 over "<timestamp>.<body>" using your account's signing secret) and X-Papayya-Timestamp. Verify both before trusting the payload.
A run submitted over many items (runs submit) inherits the same callback_url to every item — a 1,000-item run with one callback_url produces up to 1,000 deliveries. Use the run_id field on the payload to correlate the items back to their run, and item_id to tell them apart.
To submit one run over a JSONL of many items, use POST /v1/batches (frozen wire name; the product noun is the run).
Each item takes an input, and optionally your own item_id and partition_key:
{ "agent_id": "…", "items": [
{ "input": {"text": "…"}, "item_id": "co_42", "partition_key": "acme" }
] }input is what your @agent function is called with and what a replay
re-executes. item_id is your id for the item — optional, at most 256
bytes, and never derived from the input. Over the limit is a 400 naming it;
omitted is simply absent, and every surface falls back to Papayya's item id.
POST /v1/runs takes the same item_id for a single item.
Terminal error codes
When a run ends in failed status, the error_code field identifies the cause. The full set:
error_code | Cause | Platform or agent responsibility |
|---|---|---|
run_timeout | Run exceeded timeout_seconds. Enforced by a DB sweeper; catches frozen shims and runaway loops that stay within budget. | Agent |
step_timeout | A single LLM call exceeded the per-step wall clock (default 180s). Enforced in the shim interceptor. | Agent (usually a stuck tool or a slow provider call) |
tool_calls_per_step_exceeded | A single LLM response contained more than the allowed number of tool calls (default 25). Enforced in the shim interceptor. | Agent |
max_steps_exceeded | Framework-driven (agent.run()) loop exceeded max_steps. Step-mode enforces this via its explicit loop; this code catches the equivalent in framework mode. | Agent |
thrash_detected | Same tool called with identical arguments repeatedly within a sliding window. Detected in the shim interceptor via canonical-JSON fingerprinting of tool arguments. | Agent |
budget_exceeded | Cumulative run cost reached budget_cents. Enforced at three layers: pre-call reservation (the shim estimates worst-case cost and reserves it against the run's budget before each LLM call fires — a rejected reservation aborts the call without spending real money), post-call reconciliation (the reservation is released atomically when the actual cost is reported), and a final DB fence at step insert time. | Agent |
heartbeat_timeout | The shim stopped sending heartbeats. The run may have finished on the container but failed to report. | Platform-ambiguous |
orphan_container_recovered | The run's lease expired while a container was still running; a new worker re-acquired the run and cannot safely resume without risking duplicate tool execution. Replay from the last successful step. | Platform |
container_start_failed | The run's container failed to start. | Platform |
Shim-side per-step limits can be disabled per run by setting the corresponding environment variable to 0 (or true for the thrash flag) in your agent's container, for agents that legitimately need unbounded values. The run-level timeout_seconds backstop remains in force regardless:
| Env var | Default | Disable with |
|---|---|---|
PAPAYYA_STEP_TIMEOUT_SECONDS | 180 | 0 |
PAPAYYA_MAX_TOOL_CALLS_PER_STEP | 25 | 0 |
PAPAYYA_THRASH_WINDOW_SIZE | 10 | 0 |
PAPAYYA_THRASH_MAX_REPEATS | 5 | 0 |
PAPAYYA_THRASH_DISABLED | false | true |
Thrash detection uses a sliding window: it trips when the same tool call signature (tool name + canonical-JSON of arguments) appears PAPAYYA_THRASH_MAX_REPEATS times within the last PAPAYYA_THRASH_WINDOW_SIZE tool invocations. Canonical JSON is order-independent for object keys, so {"a":1,"b":2} and {"b":2,"a":1} are treated as identical.
Disable thrash detection (PAPAYYA_THRASH_DISABLED=true) for agents with legitimate repeated-call patterns:
- Polling tools. An agent that calls
check_job_status(job_id=X)several times while waiting for an external job is not thrashing. - Deterministic verification. An agent that calls a tool and then re-verifies the same call to confirm idempotency.
- Idempotent retries. A tool that returns transient errors may legitimately be retried several times with identical arguments before the agent gives up.
If you hit a false positive, disable per run and file feedback so we can ship a per-tool opt-out (polling: true in the tool schema) in a future release.
Custom cost functions (BYO providers)
If you use a provider not in the built-in pricing table (e.g., a local model, a self-hosted endpoint, or an enterprise pricing deal), you can override the default cost calculation by setting environment variables on your agent container:
| Env var | Signature | Purpose |
|---|---|---|
PAPAYYA_COST_FN | (model, input_tokens, output_tokens) -> int | Actual cost in cents after a call completes. |
PAPAYYA_COST_FN_ESTIMATE | (model, kwargs) -> int | Worst-case cost in cents before a call fires (for pre-call budget reservation). |
Format: module.path:function_name (Python) or module-path:exportName (Node).
Python example:
# my_costs.py — deployed alongside your agent code
def my_cost(model: str, input_tokens: int, output_tokens: int) -> int:
"""Return cost in cents for your custom model."""
if "local" in model:
return 0 # self-hosted, no provider cost
return max(1, int((input_tokens * 100 + output_tokens * 300) / 1_000_000))Set PAPAYYA_COST_FN=my_costs:my_cost in your agent's environment.
Fallback: If the custom function fails to load or raises an exception at runtime, the shim falls back to the built-in pricing table. The row-4 DB fence (InsertStep) remains the authoritative backstop regardless of which cost function is active.
When to set PAPAYYA_COST_FN_ESTIMATE: Only if you need tighter budget reservation for your provider. The default estimation over-reserves conservatively (assumes Claude Sonnet pricing), which is safe but may produce false 402s on very cheap models. If you don't set this, the default estimation is used even when PAPAYYA_COST_FN is set.
Billing policy for terminal runs
Every terminal run is classified by cause and billed or forfeited accordingly. The rules are:
- Agent-cause failures bill for the compute-time they consumed. The customer's code, prompt, or configuration caused the run to stop being useful, but real provider calls were made and real compute was spent. Budget caps set via
budget_centsare hard-enforced at the cents level (pre-call reservation + DB fence), so billed amounts never exceed the declared budget even if the run tried to overspend. - Platform-cause failures forfeit to margin. Platform-side failures are always free — charging for infrastructure problems is how platforms lose customers.
- Customer cancellations bill for actual compute consumed up to the cancel point. Not billing cancels would create a perverse incentive to cancel runs about to complete.
The full decision table:
status / error_code | Category | Billed? | Notes |
|---|---|---|---|
completed | Agent | ✓ Billed | Successful run, normal path. |
cancelled | Customer | ✓ Billed | Customer cancelled the run (dashboard). Actual compute only, no cancel fee. |
budget_exceeded | Agent | ✓ Billed | Billed up to budget_cents. Fence guarantees spend ≤ budget. |
failed / run_timeout | Agent | ✓ Billed | Customer-configured timeout expired. |
failed / step_timeout | Agent | ✓ Billed | Single LLM step exceeded per-step wall clock. |
failed / tool_calls_per_step_exceeded | Agent | ✓ Billed | Runaway prompt emitted too many parallel tool calls. |
failed / max_steps_exceeded | Agent | ✓ Billed | Framework-mode loop didn't terminate. |
failed / thrash_detected | Agent | ✓ Billed | Shim detected repeated identical tool calls. |
failed / container_start_failed | Platform | ✗ Free | Container never started; no customer compute consumed. |
failed / orphan_container_recovered | Platform | ✗ Free | Platform-side lease recovery; replay run bills separately. |
failed / heartbeat_timeout | Platform | ✗ Free | Ambiguous root cause; customer-friendly default. |
failed with unknown error_code | Platform | ✗ Free | Conservative fallback. |
List runs
GET /v1/runsGet run
GET /v1/durable/runs/{runId}Returns the per-item execution record. (The wire path is transitional — durable/runs/{runId} is the item; the product noun is the run/item.)
Get run steps
GET /v1/durable/runs/{runId}/checkpointsGlobal step queries are GET /v1/steps (filterable) and GET /v1/steps/error-categories.
Each row carries the durable-execution fields (step_number, step_type, status, input, output, input_tokens, output_tokens, cost_cents, model, created_at, completed_at) plus three nullable BYOF observability fields populated when the SDK recognized the provider response on an llm_call step: llm_total_tokens, llm_stop_reason, llm_provider_shape. Non-LLM steps and unrecognized provider shapes leave the llm_* fields unset.
The same llm_* fields, plus llm_prompt_tokens / llm_completion_tokens / llm_model, populate on durable-run checkpoints returned by GET /v1/durable/runs/{runId}/checkpoints.
Stream run steps (Server-Sent Events)
GET /v1/durable/runs/{runId}/eventsLong-lived SSE stream. On connect the server backfills every existing
step as a step event, then tails new steps in real time. When the
run reaches a terminal status (completed, failed, cancelled,
budget_exceeded) the server emits a terminal event and closes the
connection.
Keepalive comments (: keepalive) land every 15 seconds so load
balancers don't idle-close the stream. The default response timeout
is disabled on this endpoint — the only lifetime is the client
connection.
Event types:
event: | data: shape | When |
|---|---|---|
step | full step row (same shape as GET /v1/durable/runs/{runId}/checkpoints elements) | each new step row |
terminal | {"status": "completed" | "failed" | "cancelled" | "budget_exceeded"} | run reaches a terminal state |
error | {"error": "<message>"} | server-side query failure |
Each step event carries id: <step_number>. To resume after a
transient disconnect, reconnect with Last-Event-ID: <highest seen step_number> — backfill will skip those rows.
event: step
id: 1
data: {"step_number": 1, "step_type": "llm_call", "status": "completed", ...}
event: step
id: 2
data: {"step_number": 2, "step_type": "llm_call", "status": "completed", ...}
event: terminal
data: {"status": "completed"}See client.runs.stream() in the Python SDK for a typed helper.
Run logs
There is no GET /v1/runs/{id}/logs REST endpoint. Retrieve a run's step trace from the CLI with papayya logs <run_id>, or stream steps live via GET /v1/durable/runs/{runId}/events.
Cancel a run
There is no run-cancel REST endpoint on the frozen wire. Cancel a run from the dashboard.
Replay an item
POST /v1/durable/runs/{runID}/replay?tenant=&latest=&force=Re-drive one item into a new run linked by replayed_from. The path
parameter is an item id — the name predates the vocabulary and the route is
published, so it keeps both. Only a terminal item replays; by default only
one that didn't work, unless force=true. latest=true re-runs on the
agent's current version.
For a cohort rather than an item, see Cohorts.
Signals: "this one was wrong"
POST /v1/durable/runs/{runID}/signals
GET /v1/durable/runs/{runID}/signalsItem that a person judged this item wrong — a thumbs-down, a support
ticket, a human edit, a refund, a downstream rejection. It changes no verdict
and re-runs nothing; it makes the item selectable with ?flagged=true on
every cohort verb.
{
"verdict": "bad",
"source": "ticket",
"reason": "refunded — the summary named the wrong policy",
"external_id": "zd-44711",
"occurred_at": "2026-08-13T11:04:00Z"
}| Field | |
|---|---|
verdict | good, bad, corrected. Required |
source | dashboard, thumbs, ticket, edit, refund, rejection. Required |
reason | Free text, optional — what the person knew |
external_id | Your own id for the signal (a ticket id, a webhook event id), optional |
occurred_at | When the judgement was made. Defaults to now |
An unknown verdict or source is a 400 naming the allowed set — never a
silent coercion, because this is evidence and there is no second copy to
correct it from. 201 when the signal is stored, 200 when it was already
stored: an external_id makes the write idempotent per item, so a
webhook retry returns the original row with the original reason rather than
overwriting it. A second complaint about a different item — the re-drive
of the same order, say — is a new signal, not a duplicate.
agent, item_id and partition_key are copied from the item itself and
are not accepted on the wire; a signal that disagreed with the item it points
at would be worse than no signal.
Takes an API key as well as a dashboard session, so a backend that holds our
run id can post its own. An item accumulates signals — bad today,
corrected next week — and GET returns all of them, newest first.
good is stored and nothing reads it yet. It is here because an accumulated
suite needs the passes as well as the failures, and a schema that only admits
complaints could never answer "did the fix work" from the world's own evidence.
Signals from your own app
POST /v1/durable/signalsThe same evidence, keyed on your id instead of ours. The route above needs
a Papayya run id, which your thumbs-down handler does not have; this one takes
the item_id you declared when you submitted the work.
{
"agent": "triage",
"item_id": "order-8813",
"verdict": "bad",
"source": "thumbs",
"partition_key": "acme",
"occurred_at": "2026-08-13T11:04:00Z"
}| Field | |
|---|---|
agent | The agent that produced the item. Required — an order id is only unique within one stream of work |
item_id | Your id for the item, as declared on submit. Required, 256 bytes |
partition_key | Required if you submitted under one — see below |
occurred_at | When the world judged. Defaults to now, and decides which item this names |
verdict, source, reason, external_id | As above |
The response says what it resolved to, right now:
{ "id": "…", "resolved_run_id": "a02a95d2-…", "candidates": 3, "other_partitions": 0 }Which item does it name? The one that had already produced output when the
world judged — the most recent one, if your order was re-driven. Re-drives are
the normal case, not an edge one: one of your ids legitimately maps to several
of our items over time, and a complaint at 11:15 belongs to whichever of them
had answered by 11:15. candidates tells you how many were eligible.
It is resolved when you ask, not when you post. resolved_run_id can be
null and the signal is still stored and still counted later — evidence you
posted before we finished recording the item is not lost, and a re-drive after
the fact does not rewrite what you were told. Nothing about the resolution is
frozen onto the row.
Partitions are not guessed. A signal with no partition_key names only
items submitted without one; it will not pick between your tenants. If your
order id exists under two partitions and you sent none, other_partitions says
so and resolved_run_id is null — a wire-up bug you can see on the first
call, rather than a complaint quietly filed against the wrong customer.
An unknown agent is a 400. An unknown item_id is not: no item will
ever appear under an agent you have not deployed, but one may well appear a
second later under an order id we have not seen yet.
external_id is your id for the signal, not for the item — a webhook
event id. Send it and a retried webhook stores one row. Without it, two calls
store two rows, deliberately: an item accumulates signals, and two people
complaining about one order is two pieces of evidence rather than a duplicate.
Do not use the order id here; a second, genuine complaint about it would be
treated as the first one arriving twice.
The SDK wraps this as papayya.signal().
Resume a paused run
POST /v1/durable/runs/{runID}/resumeContinue a run a fence paused. Only a paused run resumes (409 otherwise).
One transaction does three things: flips the status back to running, clears
the degraded-step streak, and unparks the run's queued item so a worker picks
it back up and replays from the last checkpoint.
It also re-runs the steps the fence objected to rather than replaying their cached results — otherwise the run resumes on the exact output it paused over and the operator's fix never reaches the work. The set is decided when the fence trips, not when you resume.
Returns the refreshed run envelope plus two fields:
| Field | Meaning |
|---|---|
redriven | false means the pause was cleared but nothing was queued to restart — a run paused before this endpoint could re-queue work. Replay it instead. |
reexecuting | How many steps will actually run again. 0 means this resume will produce exactly what it produced before — a budget pause invalidates nothing by design, and a degraded streak of void side-effect steps has nothing safe to re-run. |
Two kinds of counted step are deliberately not re-run: papayya.mark_* rows
(there is no function to call again) and steps that returned None (usually a
side effect, and re-running it would repeat it).
Clearing the streak matters too: without it a resumed run would re-pause on its very next imperfect step.
Resume continues the same run. To re-drive the work from the start as a new run, use replay above.
Set a run verdict
Records a reviewer's judgment of whether the run did the right thing. status: completed only means the runtime didn't crash — verdict is the human signal that turns traces into eval data.
Verdicts are recorded by a signed-in reviewer in the dashboard — they cannot be set via API key, since each verdict is attributed to the user that recorded it (verdict_set_by, verdict_set_at). A verdict is one of "good", "bad", "needs_review", or null (clears any existing verdict); notes is optional free text.
Cohorts
The item-grained recovery surface. A cohort is every item where predicate P held over window W — see Recovery. All three routes take the same predicate on the query string, parsed by one parser server-side, so a cohort you preview is the cohort you re-drive.
| Param | Meaning |
|---|---|
agent | Agent slug |
tenant (alias partition_key) | The item's partition_key |
run_id | One run's items — one optional term, not the addressing scheme |
outcome | not_ok (default), any, degraded, failed |
from / to | Window bounds, RFC3339 |
flagged | true / false — only items a person flagged |
include_triaged | Re-admit items already dispositioned (default false) |
limit | Cap on returned members (preview only) |
drift_episode | Select the items behind a detected change — see below |
probe | Select the items like one known-bad item — see Derive a probe |
drift_episode and probe replace the predicate rather than narrowing it.
The step, its window and the threshold it crossed are resolved server-side from
the change or the saved probe, so passing either alongside agent, tenant,
run_id or outcome is refused with a 400 rather than merged — two
selections in one request means one of them is about to be silently discarded,
and this is a verb that re-executes work. Passing both at once is also a 400.
With drift_episode | With probe |
|---|---|
limit, include_triaged apply | limit applies |
flagged admitted | flagged admitted |
from / to refused | from / to admitted, intersected with the frozen window — they can only narrow it |
| — | include_triaged is forced on: the item you pointed at may already have been dispositioned, and a cohort that excludes your own example is a wrong answer |
flagged is admitted beside both because it can only ever remove items from
a selection the server already resolved — ?probe=…&flagged=true is "everything
like this item that a person also complained about". outcome stays refused
on both doors: those predicates select at any outcome by design, because the
items they are about completed ok.
flagged implies an outcome, except on a re-drive
Pass flagged=true with no outcome and the preview and diff select at
outcome=any. That is not a convenience: the items people flag are
overwhelmingly the ones that came back ok, so the not_ok default returns
almost none of them and reads as good news.
POST /v1/durable/cohorts/replay does not apply that implication. A
hand-written flagged=true with no outcome is refused:
{ "error": { "message": "flagged selects records that completed ok, so a re-drive would act on records the default predicate excludes. Pass outcome=any to re-drive them, or outcome=not_ok for the flagged records that also failed." } }Say which population you mean. A read may widen what it shows you; a verb that
re-executes work may not widen what it acts on. (The probe and
drift_episode doors are exempt — their outcome is already any on the
preview and the release, so there is nothing to widen.)
A change whose signal is volume selects no items and returns 400: there
is no such thing as a cohort of items that did not arrive.
Nothing in these paths denotes a noun. That is deliberate: hanging a cohort
verb off /v1/durable/runs/{runID}/ would make one path segment mean two
different things.
Derive a probe (search by example)
POST /v1/durable/cohorts/like?item=<run_id>Derives every predicate that fits one known-bad item, saves each, and returns
it with the size of the cohort it selects. Optional from / to bound the
window (default: the last 60 days).
{
"record": "9c21e8b4-…",
"agent": "summarizer",
"partition_key": "acme",
"from": "2026-06-14T18:50:59Z",
"to": "2026-08-13T18:50:59Z",
"proposals": [
{
"probe": "9645e945-3de9-4ce9-a612-4f8b7b8a865e",
"label": "summarize",
"condition": "step_reason",
"reason_token": "conservation:field:summary",
"count": 126,
"why": "every item whose \"summarize\" step was graded \"conservation:field:summary\""
}
],
"refusals": [
{
"label": "summarize",
"condition": "below_size_floor",
"reason": "no size_floor baseline exists for this step yet, so there is nothing to compare records against"
}
],
"window_note": "the window is a default, not a retention guarantee — how far back records actually reach is not currently enforced"
}A POST because it writes. Each proposal is frozen into a saved predicate
so that a preview today and a release tomorrow resolve the same items, even
as the population floors it borrowed move underneath them. It re-executes
nothing and mutates no run — the write is a saved question, not an action.
partition_key is the scope every count is measured against. Absent means
agent-wide, across every tenant — a materially different incident from a cohort
scoped to one, which is why it is on the wire rather than left to be inferred.
condition is one of step_reason, field_blank, missing_field,
below_size_floor, below_cardinality_floor, truncated. It is there for
grouping and iconography; why is the sentence meant for a human.
refusals are returned, not dropped. A silently absent proposal is
indistinguishable from a condition the item did not satisfy, and the
difference matters when the reason is "your baseline is still forming (4
reference / 2 recent items)" rather than "this one looks fine on that
axis". Only one of those means come back later.
An empty proposals array is a real answer with a 200: nothing about the
item's recorded output is expressible in the vocabulary this platform will
commit to. 404 is an unknown item; 422 is an item that exists but
recorded no steps, since every condition reads a step.
Then pass ?probe=<id> to any of the three verbs below.
Preview a cohort
GET /v1/durable/cohorts?agent=enrich&tenant=acme&from=2026-08-01T00:00:00Z
GET /v1/durable/cohorts?probe=9645e945-3de9-4ce9-a612-4f8b7b8a865e{
"members": [ { "id": "…", "item_id": "co_007", "worst_outcome_status": "degraded", "cost_usd": 0.0135, "…": "…" } ],
"total": 812,
"truncated": true,
"cost_note": "cost_usd is estimated from token counts x your project rate card — not a billing figure"
}total is the full cohort size ignoring limit, and truncated says
plainly whether members is the whole of it. Read both: acting on a page
while believing it is the set is what truncated exists to prevent.
Release a cohort
POST /v1/durable/cohorts/replay?agent=enrich&tenant=acme&latest=trueRe-drives every releasable item, each on its own captured version unless
latest=true. Returns the manifest — one {source_id, new_run_id, item_id, agent, agent_version, source_outcome, source_cost_usd} per item, plus
released, cohort_total, skipped_not_terminal and
skipped_agent_missing.
On the probe path a release re-drives fewer items than the preview
showed, by design. The preview admits items that are themselves already
re-drives — you asked what else looks like this, and a recurring incident is
exactly where the earlier re-drives matter — while a release excludes them so
nobody is handed a re-drive of a re-drive. The gap can only ever remove
items from what was previewed, never add, so you cannot release something you
did not see. Read released against cohort_total for what actually went.
Quota is reserved for the whole cohort before any run is submitted. On a
shortfall the response is 429 and nothing is released:
{ "error": { "message": "cohort is 500 releasable item(s); only 120 trigger reservation(s) remain. Nothing was released." } }Diff a released cohort
GET /v1/durable/cohorts/diff?agent=enrich&tenant=acme&from=2026-08-01T00:00:00Z{
"records": [ { "source_id": "…", "new_run_id": "…", "before_status": "degraded", "after_status": "ok", "verdict": "recovered", "…": "…" } ],
"counts": { "recovered": 38, "still_not_ok": 1, "newly_broken": 1 },
"before_cost_usd": 0.51,
"after_cost_usd": 0.53,
"cost_note": "…"
}verdict is recovered / still_not_ok / newly_broken / still_ok /
pending. An item whose re-drive has not reached a terminal state is
pending and reports no after_status — a queued run's outcome is its
initial ok, and rendering that would read as a recovery that has not
happened.
This route forces include_triaged: a release marks every item it re-drives
as replayed, so the default predicate would exclude the entire population
and the diff would read as "nothing recovered".
Change detection
What has changed in an agent's outputs, and how far along each baseline is. See Change detection.
GET /v1/durable/drift?agent=enrich| Param | Meaning |
|---|---|
agent | Agent slug |
label | One step label |
metric | One signal (size_floor, volume, field_missing:<key>, …) |
state | Baselines in one state: forming, observing, armed |
include_resolved | Include changes that have already cleared (default false) |
limit | Cap on rows (default 200) |
{
"episodes": [
{
"id": "…",
"status": "open",
"agent": "enrich", "label": "extract", "metric": "size_floor",
"attributed_to": "unattributed",
"opened_at": "2026-08-08T04:00:00Z",
"last_seen_at": "2026-08-08T09:15:00Z",
"reference_rate": 0.05, "opening_rate": 0.31, "peak_rate": 0.42,
"window_from": "2026-08-07T04:00:00Z", "window_to": "2026-08-08T04:00:00Z",
"scope_state": "armed",
"notified_at": null,
"cohort": { "available": true, "query": "drift_episode=…" }
}
],
"scopes": [
{
"agent": "enrich", "label": "summarize", "metric": "size_floor",
"state": "forming",
"records": { "reference": 40, "reference_required": 200, "recent": 12, "recent_required": 30 },
"waiting_on": "both",
"quiet_records": 0, "arms_after_quiet_records": 60
}
]
}Read both lists. episodes is what changed; scopes is what is being
watched. An empty episodes with a populated scopes means we are watching
and nothing has moved — which is a different answer from an empty response,
and the reason the second list is on the wire at all.
attributed_to is deploy, unattributed or indeterminate; the three are
explained in Change detection.
peak_rate is the worst the change reached, which is usually what you want to
read rather than opening_rate.
cohort.query is the exact query string to append to any cohort verb. When
available is false — volume changes select no items — the object
carries a reason instead, and there is no link to follow.
On a forming baseline, records carries both window sizes with the floor
each must clear, and waiting_on (reference, recent or both) names which
one is short. A baseline can sit at forming with 5,000 items of history
because its recent traffic dried up, and the counts alone cannot tell you
that.
notified_at is null until an alert has actually been claimed for the change,
which is what distinguishes "we never sent one" from "one was sent."
Replay
Preview replay cost
There is no cost-preview REST endpoint. The projection is surfaced in the dashboard's bulk-replay confirmation gate, so an operator doesn't accidentally re-spend $4k on a 500-item run before confirming. The gate projects the total cost of replaying every not-ok item in the run — the items awaiting triage (failed or degraded):
{
"item_count": 47,
"estimated_sum_cents": 4321,
"estimated_p50_cents": 82,
"estimated_p95_cents": 197,
"methodology": "Each not-ok item's projected re-spend equals its original total_cost_cents..."
}Each not-ok item's predicted re-spend equals its original total_cost_cents — replay restarts the item from scratch on its original input, so the most accurate predictor is what the item cost before it stopped working. A run with nothing to replay projects item_count: 0 and estimated_sum_cents: 0. The papayya release CLI does the re-drive itself and reports what it actually cost afterwards; this gate only prices it beforehand.
Schedules
Create schedule
POST /v1/agents/{agentId}/schedules{
"cron_expression": "0 9 * * 1-5",
"timezone": "America/New_York",
"input": "Daily report",
"budget_cents": 200
}timezone is an IANA zone name and is honoured: the cron is evaluated as wall-clock time in that zone. "Local", and a TZ=/CRON_TZ= prefix inside the expression, are both rejected. The agent must already be deployed.
There is no max_steps — the step ceiling is read from the deployed bundle, so it belongs on @agent(max_steps=N). Sending the field returns a 400 that says so. (It was previously accepted and stored without ever being applied.)
List schedules
GET /v1/schedules
GET /v1/agents/{agentId}/schedulesEach schedule carries its most recent occurrence inline as last_event, so a list view can show the outcome without a call per row.
{
"id": "…",
"cron_expression": "0 9 * * 1-5",
"timezone": "America/New_York",
"enabled": true,
"next_run_at": "2026-08-07T13:00:00Z",
"occurrence_at": "2026-08-07T13:00:00Z",
"last_run_at": "2026-08-06T13:00:01Z",
"last_run_id": "…",
"disabled_reason": null,
"last_event": {
"scheduled_for": "2026-08-06T13:00:00Z",
"occurred_at": "2026-08-06T13:00:01Z",
"outcome": "fired",
"reason": null,
"run_id": "…"
}
}next_run_atis when we next attempt;occurrence_atis which occurrence that attempt serves. They are equal except while a transient failure is retrying inside an occurrence.last_run_atmoves only when a run was actually submitted — never on a tick that skipped or errored.disabled_reasonis"operator"when a human disabled the schedule, and a reason token (invalid_cron,invalid_timezone) when the scheduler disabled it itself.
Get / Update / Delete schedule
GET /v1/schedules/{scheduleId}
PATCH /v1/schedules/{scheduleId}
DELETE /v1/schedules/{scheduleId}PATCH with cron_expression and/or timezone recomputes the next occurrence immediately. PATCH {"enabled": true} always recomputes it too, and returns 400 if the stored cron will not parse — an enabled schedule with no computable next occurrence is invisible forever.
Occurrence history
GET /v1/schedules/{scheduleId}/events?limit=50One item per occurrence, newest first. limit defaults to 50; anything outside 1–200 falls back to 50. This is what answers "did yesterday's 09:00 fire?" — last_run_at describes the most recent tick, not a given occurrence.
[
{
"id": "…",
"schedule_id": "…",
"scheduled_for": "2026-08-06T13:00:00Z",
"occurred_at": "2026-08-06T13:00:02Z",
"outcome": "skipped",
"reason": "no_deployed_version",
"run_id": null,
"alerted_at": "2026-08-06T13:00:02Z"
}
]outcome is one of fired, skipped, error, missed. See Schedules for the reason tokens and which of them alert.
Trigger a schedule by hand
POST /v1/schedules/{scheduleId}/triggerFires the schedule now, using its own input, budget and deployed version. Returns 202 with the created run. Allowed on a disabled schedule, so a broken cron expression does not also block running the thing by hand. Records a fired event with reason: "manual" and moves last_run_at, without perturbing the cron cadence.
Triggers
A trigger is an inbound invocation hook: an authenticated HTTP call fires one run of the agent. (The HTTP call itself is a webhook — that is the transport; the product noun is the trigger.)
Create trigger
POST /v1/agents/{agentId}/webhooks(The wire path and id prefix are frozen at webhooks / whk_; the product noun is the trigger.)
{
"name": "GitHub Push",
"description": "Fires a run on GitHub push events"
}The response includes the trigger's signing secret. Capture it on creation — it is not re-shown on list.
List triggers
GET /v1/agents/{agentId}/webhooksFire a trigger
POST /v1/webhooks/{webhookId}/trigger
X-Webhook-Secret: whk_...
Content-Type: application/jsonX-Webhook-Secret is the trigger's signing secret (the transport-level auth). The request body becomes the run's input. Optionally include an X-Callback-URL header to receive the run result when it completes:
X-Callback-URL: https://your-api.com/run-completeDelete trigger
DELETE /v1/webhooks/{webhookId}Deployments
Deploy agent code
POST /v1/agents/{agentId}/deployMultipart upload of bundled agent code.
Get deployment status
GET /v1/deployments/{deploymentId}List deployments
GET /v1/agents/{agentId}/deploymentsRuntime Dispatcher (Worker API)
Internal protocol. This is the internal lease/heartbeat/complete protocol Papayya's worker pool uses to pull work off the runtime queue. It is not a surface for writing your own worker — the worker pool that installs with Papayya is the only execution path. Documented here for completeness and for local development against the in-process dispatcher.
Four endpoints hosted workers use to lease items off the runtime queue, heartbeat while running them, and either report completion or hand the item back. Wire-compatible with the in-process LocalDispatcher used during local development (papayya.runtime.dispatcher), so the same worker code path works against either side.
All four are project-scoped via API key. JWT auth has no project scope and is rejected with 401. Authenticate with the project's API key:
Authorization: Bearer cpk_your_api_keyLease an item
GET /v1/runtime/lease?worker_id=worker-abc123&wait=20Pops the next pending item from the project's queue under a fresh lease. Returns 204 No Content when the queue is empty.
| Query param | Required | Description |
|---|---|---|
worker_id | Yes | Stable identifier for the calling worker. |
wait | No | Seconds to hold an empty poll open rather than answering 204 immediately. Clamped to a maximum of 25; absent or 0 answers immediately. A held request returns as soon as work is enqueued — the server is woken by the database, not by a timer — so a long wait costs nothing in dispatch latency. |
wait is what keeps an idle pool cheap. Without it a worker polling every 50ms runs one queue transaction per poll, so idleness costs ~18 write-path transactions a second per worker. With wait=20 the same idle worker issues three requests a minute and still picks up new work in single-digit milliseconds.
200 OK:
{
"lease_id": "9c3e4b...",
"agent": "research-agent",
"item_id": "item_42",
"payload": { "topic": "vector databases" },
"agent_version": "v3",
"max_duration_seconds": 600
}| Field | Description |
|---|---|
lease_id | UUID. Stable through pending → leased → completed. The reaper re-queues a stale lease with a fresh lease_id so a zombie worker's late /complete cannot collide with the next worker's lease. |
agent | Agent name to dispatch to. |
item_id | Caller-supplied item identifier (e.g. the submitted JSONL row ID). |
payload | Opaque JSON handed to the agent. Omitted when null. |
agent_version | Agent version pinned at enqueue time, if any. |
max_duration_seconds | Per-item soft timeout. Worker terminates the run when exceeded. |
The default lease TTL is 30 seconds. Workers must heartbeat or complete within that window or the reaper releases the lease and another worker can pick the item up.
Complete a lease
POST /v1/runtime/complete{
"lease_id": "9c3e4b...",
"worker_id": "worker-abc123",
"status": "completed",
"error": null,
"error_category": null
}Always returns 200 OK. The dispatcher accepts duplicate completions safely — three internal outcomes all map to 200:
| Outcome | When |
|---|---|
| Fresh | First-time completion. Lease moved from runtime_leased to runtime_completed. |
| Duplicate | Worker retried a successful POST. Idempotent on lease_id; no double-write. |
| Stale | Lease was released by the reaper before this POST landed (zombie worker). Logged and dropped quietly so the worker's bounded retry doesn't spin. |
| Field | Required | Description |
|---|---|---|
lease_id | Yes | UUID returned by GET /v1/runtime/lease. |
worker_id | Yes | Same worker_id used to acquire the lease. |
status | Yes | "completed" or "failed". |
error | No | Free-text error message when status == "failed". |
error_category | No | Coarse category for failure clustering (e.g. provider_credit_exhausted, rate_limited). |
The 200-on-everything contract is what makes the SDK's bounded retry safe — combined with the lease TTL, partition recovery never loses work and never double-counts it.
Release a lease
POST /v1/runtime/release{
"lease_id": "9c3e4b...",
"worker_id": "worker-abc123",
"reason": "paused"
}The counterpart of /complete, and the distinction is the point: complete is terminal, release is not. A worker that stops without finishing — because a fence paused the run, or the LLM provider reported exhausted credits — hands the item back to the queue parked, so an operator resume can re-drive it. A completed lease lands in runtime_completed, which is terminal by construction; nothing can re-queue it.
A parked item is not leasable. GET /v1/runtime/lease will not return it to any worker until the run is resumed.
| Field | Required | Description |
|---|---|---|
lease_id | Yes | UUID returned by GET /v1/runtime/lease. |
worker_id | Yes | Same worker_id used to acquire the lease. |
reason | No | "paused" (default) — a fence stopped the run, and the run's status is already paused server-side. "credit" — the provider reported credit exhaustion, which is classified client-side, so this call is what marks the run paused with pause_reason="credit". |
Always returns 200 OK with the outcome in the body, on the same contract as /complete:
outcome | When |
|---|---|
released | The lease was held; the item is back in the queue, parked. |
duplicate | The lease already has a completion. Re-queueing would resurrect finished work, so it didn't. |
stale | The lease is in neither table — the reaper got there first, or this is the worker's own retry landing after the first release re-minted the lease_id. |
Heartbeat a lease
POST /v1/runtime/heartbeat{
"lease_id": "9c3e4b...",
"worker_id": "worker-abc123"
}200 OK on success — the lease's last_heartbeat and expires_at are pushed forward by one TTL window.
410 Gone when the lease no longer exists or is held by a different worker. The worker should treat 410 as authoritative and stop tracking the in-flight item; a different worker has taken it over under a fresh lease.
Heartbeat at TTL/3 or faster (≤ 10s in production) to absorb a missed tick without losing the lease.
Secrets
Set secret
POST /v1/projects/{projectId}/secrets{
"name": "MY_API_KEY",
"value": "sk-abc123"
}List secrets
GET /v1/projects/{projectId}/secretsReturns secret names only — values are never exposed.
Delete secret
DELETE /v1/projects/{projectId}/secrets/{name}Projects & API Keys
Create / List / Get / Update / Delete projects
POST /v1/projects
GET /v1/projects
GET /v1/projects/{projectId}
PATCH /v1/projects/{projectId}
DELETE /v1/projects/{projectId}Create API key
POST /v1/projects/{projectId}/api-keysList API keys
GET /v1/projects/{projectId}/api-keysRevoke API key
DELETE /v1/projects/{projectId}/api-keys/{keyId}Accounts & Members
Create / Get / Update account
POST /v1/accounts
GET /v1/accounts/{accountId}
PATCH /v1/accounts/{accountId}List / Invite / Update / Remove members
GET /v1/accounts/{accountId}/members
POST /v1/accounts/{accountId}/members
PATCH /v1/accounts/{accountId}/members/{userId}
DELETE /v1/accounts/{accountId}/members/{userId}Usage
Usage summary
GET /v1/usageUsage breakdown by project
GET /v1/usage/breakdownBilling
Get subscription
GET /v1/billing/subscriptionCreate checkout session
POST /v1/billing/subscriptionCancel subscription
POST /v1/billing/subscription/cancelList invoices
GET /v1/billing/invoicesBilling portal
POST /v1/billing/portal-sessionAuthentication
Register
POST /v1/auth/registerLogin
POST /v1/auth/loginRefresh token
POST /v1/auth/refresh