Agent runs API
Create, inspect, list, cancel, and advance governed agent runs from machine credentials or a trusted console write. Console pages only read runs.
Governed runs are created by owning workflows, external hosts, and admins. Console pages only read runs, and opening any Agents page never starts one. The agent_run_routes module exposes HTTP endpoints for run lifecycle, provenance-backed listings, operational metrics, and spend analytics.
What this API area is for
A run record describes work started by an owning execution surface; reading the record does not start that work. The routes distinguish lifecycle operations from inspection.
The module docstring describes governed runs: creation by owning workflows, hosts, and admins; inspection; cancel; and handoff. Console pages only read runs. A run is created by an owning workflow or external host with its own credential, or by an admin through a trusted console write. Opening any Agents page never starts one.
Machine callers authenticate with a bearer token; console operators authenticate through the normal signed-in session plus, on mutating routes, console write trust. Hosts and workflows may only start or control runs for their own agent_id; operators bypass that ownership check.
Routes
| Method | Path | Permission | Handler | What it does |
|---|---|---|---|---|
| POST | /api/runs | agents.manage | create_run | Creates a run for body.agent_id, with optional idempotency via request_id. Returns run identity, state, config binding, budget, and a self link. |
| GET | /api/runs/facets | agents.read | facets | Lists facet values for run filters (mode facets) using query filters. |
| GET | /api/runs/failure-reasons | agents.read | failure_reasons | Lists failure-reason facet values for run filters (mode reasons). |
| GET | /api/runs | agents.read | runs | Lists runs with optional filters, pagination (limit, cursor), and scope. |
| GET | /api/agents/{agent_id}/runs | agents.read | agent_runs | Same listing as runs, scoped to the path agent_id (console role only; no bearer header on this handler). |
| GET | /api/runs/{run_id} | agents.read | run | Returns one run’s detail via provenance read; bearer callers must own the run. |
| GET | /api/runs/{run_id}/steps | agents.read | run_steps | Returns orchestrator steps for the run; bearer callers must own the run. |
| GET | /api/runs/{run_id}/trace | agents.manage | run_trace | Looks up a Phoenix trace for Recobot (operator-agent) runs. The handler calls require_role("agents.manage"), which is the route permission, not one of the named roles. |
| POST | /api/runs/{run_id}/cancel | agents.manage | cancel | Requests cancellation for ledger-owned runs; operators use draft roles for console cancel. |
| POST | /api/runs/{run_id}/handoff | agents.manage | handoff | Hands work to another agent with reason and state reference; creates a child run. |
| POST | /api/runs/{run_id}/start | agents.manage | start | After the ownership check, start calls agent_orchestrator.start for that run. |
| POST | /api/runs/{run_id}/complete | agents.manage | finish | Completes or fails a run from machine or trusted console caller. |
| GET | /api/metrics/agents | agents.read | metrics | Operational agent metrics for a time window and optional filters. |
| GET | /api/metrics/agents/analytics | agents.read | analytics | analytics calls analyze with the rolling flag, dimension, and JSON-decoded filters, and a viewer whose name_policy is spend. |
Request and response models
RunCreate (POST /api/runs body)
| Field | Type | Constraints |
|---|---|---|
agent_id | str | min_length=1, max_length=80 |
trigger | dict[str, object] | required |
budget | dict[str, float] | default empty dict |
fallback | dict[str, object] | None | optional |
request_id | str | None | optional, max_length=128 |
trigger_kind | "human" | "scheduled" | "event" | "agent" | None | optional |
is_evaluation | bool | default False |
Extra fields are forbidden (extra="forbid").
Success response (201) from the handler’s perform closure:
| Field | Type |
|---|---|
run_id | object (from orchestrator) |
state | object |
config_binding | object |
budget | object |
links | { "self": "/api/runs/{run_id}" } |
create_run always returns the result of idempotent, including when request_id is absent.
Handoff (POST /api/runs/{run_id}/handoff body)
| Field | Type | Constraints |
|---|---|---|
to_agent_id | str | min_length=1, max_length=80 |
reason | str | min_length=3, max_length=300 |
state_ref | str | min_length=1, max_length=200 |
Success response:
| Field | Type |
|---|---|
parent_run_id | str (path run_id) |
child_run_id | from child run |
state | child run state |
Finish (POST /api/runs/{run_id}/complete body)
| Field | Type | Constraints |
|---|---|---|
output_ref | str | None | optional, max_length=200 |
outcome | str | default "completed" |
error_class | str | None | optional, max_length=60 |
Behaviour: If outcome is "failed", the handler calls orchestrator fail with error_class or "reported_failure". If outcome is "completed", it completes with output_ref. Any other outcome raises invalid with message outcome must be completed or failed.
run_steps response
{
"run_id": "<run_id>",
"steps": "<orchestrator steps list>"
}Query parameters on list and facet routes
Shared optional query parameters on facets, failure_reasons, runs, and agent_runs:
| Parameter | Type | Notes |
|---|---|---|
agent_id | str or str | None | On agent_runs, agent_id is a required path str; on facets, failure_reasons, and runs it is an optional query str. |
state | str | None | filter |
since | str | None | filter |
until | str | None | filter |
scope | str | default "all" |
person_subject | str | None | filter |
channel_key | str | None | filter |
failure_reason | str | None | filter |
runs and agent_runs also accept limit (int \| None, passed through bounded_limit) and cursor (str \| None).
facets, failure_reasons, and runs accept optional Authorization header for machine reads. agent_runs does not declare that header.
metrics query parameters
| Parameter | Type | Default |
|---|---|---|
window_hours | int | 24 |
principal | str | None | — |
agent_id | str | None | — |
scope | str | "all" |
since | str | None | — |
until | str | None | — |
analytics query parameters
| Parameter | Type | Default |
|---|---|---|
from_date | str | None | — |
to_date | str | None | — |
rolling | bool | False |
scope | str | "all" |
metric | str | "tokens" |
component | str | "total" |
split | str | "none" |
interval | str | "day" |
dimension | str | "model" |
filters | str | "{}" (filters is a string defaulting to "{}", decoded with json.loads, and turned into ValueError when its length is greater than 16000) |
bucket | str | None | — |
group | str | None | — |
offset | int | 0 |
limit | int | 50 |
snapshot | str | None | — |
snapshot_key | str | None | — |
detail | bool | False |
run_id | str | None | — |
receipt_id | str | None | — |
The handler documents that analytics uses the same agent-read capability and tenant database as the operational directory.
Behaviour and errors
Caller resolution
- Writes (
create_run,cancel,handoff,start,finish): IfAuthorizationis present, the bearer is authenticated as a machine principal (external_host,workflow, ornative_component) with optionaldelegated_user_hashon claims. Otherwise the route requires console write trust, thenrequire_admin()orrequire_role(console_roles). Cancel passesDRAFT_ROLESso operators in draft roles may cancel. - Reads (most GET handlers): If
Authorizationis present, the bearer is authenticated and never falls back to the console identity. IfAuthorizationis absent,_readercallsrequire_role()and returns no machine principal. run_trace: Callsrequire_role("agents.manage")only; no bearer branch.
Ownership: _owns is true when the caller type is operator or caller["id"] equals the agent_id argument. Violations on create raise fail(403, "denied", "A host or workflow may only start its own runs"). Violations on run-scoped actions raise fail(403, "denied", "This principal does not own that run").
Validation and refusals
body.is_evaluationon create raisesfail(403, "denied", "Evaluation admission is internal only").- Pydantic validates
RunCreate,Handoff, andFinishfield lengths and forbids unknown keys. create_run:RunNotFound→not_found;RunRefusedorAccessStopped→fail(403, "denied", ...).cancel: If runsourceis notshared_run_ledger,fail(409, "conflict", "This run is controlled by its owning workflow").RunStopped→_stopped(409conflictor 409stale_configwhen code isnot_queued).handoff:RunStopped→_stopped;RunNotFound→not_found;RunRefused→invalid.start:RunStopped→_stopped.finish: invalid outcome string →invalid._run_read:PermissionError→fail(403, "denied", "Person selection is not available");ValueError→invalid.run:RunNotFound→not_found.run_steps:RunNotFound→not_found.run_trace:RunNotFound→not_found; ifagent_idis notoperator-agent,not_found("Phoenix trace lookup is available for Recobot runs").metricsmapsValueErrortoinvalid;analyticsmapsValueErrorandTypeErrortoinvalid; analyticsPermissionError→ person-selection denial as above.
Explicit HTTP status codes set in this module via fail are 403 (denied) and 409 (conflict or stale_config). Other helpers (not_found, invalid) are raised from shared HTTP utilities without their status codes defined in this module’s files.
Provenance and orchestration
List, facet, and detail reads go through agent_provenance.list_reads and agent_provenance.detail_read with a viewer from agent_provenance.read_viewer. Orchestrator mutations here are create_run, request_cancel, handoff, start, complete, and fail; get_run, steps, and metrics are reads. Operator-created runs wrap creation in agent_provenance.ingress with origin console_run_api. run_trace calls agent_tracing.lookup_run_trace.
How the permission model applies
The route permission table maps each handler to a permission name. For agent_run_routes, GET handlers use agents.read except run_trace, which is mapped to agents.manage and calls require_role("agents.manage"); POST handlers use agents.manage.
At application startup, require_complete refuses to start when a route has no permission, the table names no route, or a permission name is unknown. For signed-in console users, gate loads the permission for the endpoint key agent_run_routes.<handler_name> and denies with HTTP 403 when the user’s role does not hold that permission. That ceiling does not replace route-level checks: bearer grants, ownership, provenance viewer policy, and console write trust can narrow access further.
With sign-in off, the caller is Recohut's OS admin on this computer, and a bearer-authenticated machine call carries its own grants. Public permissions do not apply to these routes.
Machine principal raw ids use prefixes host:, workflow:, and component: depending on principal type.
How is this page?
Last updated on