Skip to Content
Recodocs

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.

8 min read

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

MethodPathPermissionHandlerWhat it does
POST/api/runsagents.managecreate_runCreates 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/facetsagents.readfacetsLists facet values for run filters (mode facets) using query filters.
GET/api/runs/failure-reasonsagents.readfailure_reasonsLists failure-reason facet values for run filters (mode reasons).
GET/api/runsagents.readrunsLists runs with optional filters, pagination (limit, cursor), and scope.
GET/api/agents/{agent_id}/runsagents.readagent_runsSame listing as runs, scoped to the path agent_id (console role only; no bearer header on this handler).
GET/api/runs/{run_id}agents.readrunReturns one run’s detail via provenance read; bearer callers must own the run.
GET/api/runs/{run_id}/stepsagents.readrun_stepsReturns orchestrator steps for the run; bearer callers must own the run.
GET/api/runs/{run_id}/traceagents.managerun_traceLooks 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}/cancelagents.managecancelRequests cancellation for ledger-owned runs; operators use draft roles for console cancel.
POST/api/runs/{run_id}/handoffagents.managehandoffHands work to another agent with reason and state reference; creates a child run.
POST/api/runs/{run_id}/startagents.managestartAfter the ownership check, start calls agent_orchestrator.start for that run.
POST/api/runs/{run_id}/completeagents.managefinishCompletes or fails a run from machine or trusted console caller.
GET/api/metrics/agentsagents.readmetricsOperational agent metrics for a time window and optional filters.
GET/api/metrics/agents/analyticsagents.readanalyticsanalytics 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)

FieldTypeConstraints
agent_idstrmin_length=1, max_length=80
triggerdict[str, object]required
budgetdict[str, float]default empty dict
fallbackdict[str, object] | Noneoptional
request_idstr | Noneoptional, max_length=128
trigger_kind"human" | "scheduled" | "event" | "agent" | Noneoptional
is_evaluationbooldefault False

Extra fields are forbidden (extra="forbid").

Success response (201) from the handler’s perform closure:

FieldType
run_idobject (from orchestrator)
stateobject
config_bindingobject
budgetobject
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)

FieldTypeConstraints
to_agent_idstrmin_length=1, max_length=80
reasonstrmin_length=3, max_length=300
state_refstrmin_length=1, max_length=200

Success response:

FieldType
parent_run_idstr (path run_id)
child_run_idfrom child run
statechild run state

Finish (POST /api/runs/{run_id}/complete body)

FieldTypeConstraints
output_refstr | Noneoptional, max_length=200
outcomestrdefault "completed"
error_classstr | Noneoptional, 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:

ParameterTypeNotes
agent_idstr or str | NoneOn agent_runs, agent_id is a required path str; on facets, failure_reasons, and runs it is an optional query str.
statestr | Nonefilter
sincestr | Nonefilter
untilstr | Nonefilter
scopestrdefault "all"
person_subjectstr | Nonefilter
channel_keystr | Nonefilter
failure_reasonstr | Nonefilter

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

ParameterTypeDefault
window_hoursint24
principalstr | None—
agent_idstr | None—
scopestr"all"
sincestr | None—
untilstr | None—

analytics query parameters

ParameterTypeDefault
from_datestr | None—
to_datestr | None—
rollingboolFalse
scopestr"all"
metricstr"tokens"
componentstr"total"
splitstr"none"
intervalstr"day"
dimensionstr"model"
filtersstr"{}" (filters is a string defaulting to "{}", decoded with json.loads, and turned into ValueError when its length is greater than 16000)
bucketstr | None—
groupstr | None—
offsetint0
limitint50
snapshotstr | None—
snapshot_keystr | None—
detailboolFalse
run_idstr | None—
receipt_idstr | 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): If Authorization is present, the bearer is authenticated as a machine principal (external_host, workflow, or native_component) with optional delegated_user_hash on claims. Otherwise the route requires console write trust, then require_admin() or require_role(console_roles). Cancel passes DRAFT_ROLES so operators in draft roles may cancel.
  • Reads (most GET handlers): If Authorization is present, the bearer is authenticated and never falls back to the console identity. If Authorization is absent, _reader calls require_role() and returns no machine principal.
  • run_trace: Calls require_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_evaluation on create raises fail(403, "denied", "Evaluation admission is internal only").
  • Pydantic validates RunCreate, Handoff, and Finish field lengths and forbids unknown keys.
  • create_run: RunNotFound → not_found; RunRefused or AccessStopped → fail(403, "denied", ...).
  • cancel: If run source is not shared_run_ledger, fail(409, "conflict", "This run is controlled by its owning workflow"). RunStopped → _stopped (409 conflict or 409 stale_config when code is not_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; if agent_id is not operator-agent, not_found("Phoenix trace lookup is available for Recobot runs").
  • metrics maps ValueError to invalid; analytics maps ValueError and TypeError to invalid; analytics PermissionError → 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