Skip to content

Agent runner

Status: implemented. How to use it is in agents.md and launching-agents.md. The code is runner.py.

Goal

AgentRunner runs agent definitions: it validates, calls the model, checks what came back, retries, limits concurrency, lets an agent launch other agents, and records every attempt (jobs). It is not a workflow engine. Order, loops, branching and when to stop are the caller's code. A runner is not tied to one agent: the agent is chosen on each call, and one runner can run any number of different agents.

Running

result = await runner.run(AgentClass, agent_input, job_id=job_id)
results = await runner.run_many(AgentClass, inputs, job_id=job_id)
  • run takes the class and an input that is an instance of its input_model.
  • run_many runs one agent over many inputs at the same time and returns the results in input order. It has no limit of its own: the concurrency limit bounds it.
  • job_id is optional. Runs of one pipeline share a job. Without one, the runs have no job.
  • identity= is who the run is for. Whether it is optional or required depends on the type the runner declares (AgentRunner(db, identity_type=...)): a declared type makes it required, a union with None allows none, and with nothing declared passing one is an error. run, run_many and stream take it. See identity.
  • Runtime failures are values. run returns a FAILED result. It does not raise.
  • Programming errors raise: an input of the wrong type (TypeError), a job_id that does not exist, an identity that is missing, of the wrong type, or given when no type is declared (TypeError), and an identity that is not the one of the job: a job is for one identity (ValueError, identity). run_many checks the identity once, at the call, also for no inputs; stream checks the job's identity when the loop starts.
  • A streaming agent is not run with run: it raises TypeError and names stream. stream(StreamingAgent, ChatInput, job_id=...) returns a StreamingRun at once, whose events come as the model writes (streaming agents). It takes a concurrency slot like any run, holds it for the whole stream, and is never retried. cancel(run_id) stops a streaming run of this runner by its id and says whether there was one (stopping a response).

The result

AgentResult[OutT]: status (SUCCESS or FAILED only), output (the validated output model, on success), error (the last error, on failure), attempt_id (the last attempt), input_tokens, output_tokens (thinking included), attempts, latency_ms (across attempts), model_name (as the API reported it, which can differ from the one requested) and reused (see resuming). Tokens are summed over the model calls of the successful attempt. The tool results the model read are in its input tokens. A failed result has no tokens.

Resuming

A takeover of a job (several workers) uses the same rules, with one difference: the source is the same job, and only runs of earlier executions (job_execution below the current one) are looked up, so a run never reuses its own execution's rows. The result is read under this job's own key, so nothing is copied forward, and only a resumable job is looked up. A job that resumes another and was taken over looks in itself first, then in the old job. The execution that asks is the one that the task running the job has (not the job row's: a worker that lost the job and has not noticed is still the execution it was).

A job created with resume_from (see jobs) makes the runner look up a run before it runs it. This is replay with memoised agent calls: the caller's code runs again, and only runs are answered from the log.

  • Where. At the start of a run, once per run call, before the attempt loop, and only when depth is 1 and there is a job_id. A sub-agent (depth above 1) is never looked up.
  • The match. In the old job: status = SUCCESS, the same agent_hash, the same input_hash, the same identity_hash (NULL, no identity, matches only NULL: identity), depth = 1. Any matching row will do. A row with no agent_hash or input_hash never matches. The log is the metadata question.
  • The result. The output comes from the runner's ResultStore (get(ResultKey(old job, agent hash, input hash))). No store (results=None) is a SetupError; no result for a step that the log says succeeded logs result_missing and the runs.
  • The check. The kept output is validated against the current output model, then check_output(agent_input, output) runs again. If either fails, run_reuse_rejected reason=... is logged and the agent runs normally.
  • What is kept. The output of a depth-1 run that succeeds inside a resumable job, put in the store after the row is finished. A store that fails does not fail the run (result_not_kept is logged). A reused run copies its result to the new job.
  • The reused run. It writes one SUCCESS row in the new job, with a new attempt_id, zero tokens, the stored output and reused_from_attempt_id. It logs run_reused run_id=... attempt_id=... reused_from_attempt_id=..., calls no model, builds no MCP connection and takes no slot. The result has reused=True, zero tokens and attempts=1.
  • run_many resumes per input, since each input is one run call.
  • Not covered. The determinism of the caller's code between agents (the caller's responsibility, not checked), state that a run kept in memory (a reused run does not run, so it is not rebuilt), side effects of tools, reuse of sub-agent runs, rows from before agent_hash.

Attempts and retries

Each attempt is one row in the run log, and goes through these steps:

  1. The tools of the attempt are collected, and MCP servers are started if needed (below). The row is created as INIT.
  2. The attempt waits for a concurrency slot. Then the row becomes RUNNING.
  3. The chat model is built (a failure here is a setup error), the agent is run through langgraph, the structured reply is validated, and check_output runs.
  4. The row is finished as SUCCESS with the output, or FAILED with the error.

Retries. A failed attempt is retried, up to max_attempts (3). The wait between attempts is retry_delay_s (1s), and it does not hold a concurrency slot.

  • A retry resamples with the same input. The error is recorded in the log but is not sent back to the model. If a retry should know what went wrong, the pipeline does that: it builds a new input.
  • Failed attempts: an API error, a reply that does not validate, no structured reply, a rejection by check_output, an early answer, the recursion limit, and any other exception.
  • Not retried (the run fails at once): a SetupError (no API key, an unknown model, an MCP server that cannot start, two tools with one name), and any 4xx response except 408, 409 and 429, found on the exception or its causes.
  • A FAILED result carries the last attempt's error, with its type, at most 2,000 characters.

An early answer

Where the output is asked for as a tool call (LangChain's ToolStrategy: Claude Haiku 5.5 today), the model is given the output as one more tool, and it can call it in the same reply as other tools. LangChain then takes the answer, runs the other tools and ends: the model never sees what they returned, and the answer is empty or made up.

The runner refuses a run whose last reply holds the output's call and other calls, with EarlyAnswerError (a ValueError), before check_output. The attempt fails and is retried like any other. By then the other tools have run, and a retry runs them again, which is the rule for every failed attempt: a tool must be safe to run twice. A streaming agent has no typed output, and is not checked.

It is the runner's, and not the model settings' (decided 2026-11-26). It is about how a run ended, it is the same pattern whatever model made it, and no provider needs another rule. A hook on the settings would be a way to switch the check off that nothing needs; if a provider ever needs a rule of its own for a reply, the hook can come with it. Rejected: middleware that sends the answer back to the model (models). Seen once on the real API (Claude Haiku 5.5, thinking on): one model call, the tool ran, and every field was empty. The reply was not kept; the case was reproduced with a fake model.

Concurrency

A semaphore of max_concurrent slots (FTW_MAX_CONCURRENT_ATTEMPTS, default 10) bounds the attempts that run at once on one runner, across every agent. A queued attempt shows as INIT until it holds a slot. The slot is released between attempts.

Launching agents

An agent can hand part of its work to another agent: it launches it, waits, and reads the result.

The identity. A launched agent runs with the identity of its parent, and the model cannot set or change it (identity).

Declaration. subagents is an allow-list of agent classes: the agent can launch exactly those. There is no registry to maintain. The agent definition checks the list (agents).

What the model gets, for an agent with sub-agents and depth left (can_launch = bool(sub-agents) and depth < max_depth):

  • the prompt lists the agents it may launch, by name and description;
  • two tools built for each attempt: get_agent_schema(agent_name), which returns the agent's name, description and input and output JSON schemas, and launch_agent(agent_name, input_json), which validates input_json against the child's input model, runs the child to the end and returns the result.

input_json is a string, because Gemini can reject a function parameter that is an object with no declared properties (checked with the real model).

Both tools always return text and never raise into the parent's run, so that the model can read what happened:

Case What comes back
The child succeeds {"status": "SUCCESS", "agent": "...", "output": {...}}
The child fails after its own retries {"status": "FAILED", "agent": "...", "error": "..."}
A name that is not on the allow-list 'x' is not an agent you can launch. You can launch: ...
The input does not fit the child's input model The input for 'x' is not valid: ... Check get_agent_schema and try again.
The depth or the launch limit is reached A sentence saying which limit

The child is an ordinary run. It has its own retries, tools, skills, MCP servers and sub-agents, and its own rows in the log. It shares the parent's job. Its row records parent_attempt_id (the attempt that launched it) and depth (1 for a top-level run). The parent sees only the child's output, as a tool result, which counts in the parent's input tokens. A model may launch several agents in one turn, and they run at the same time. A retried parent attempt launches its children again, and the earlier children stay in the log under the failed attempt.

Limits.

  • Depth (max_depth, default 3): the most agents in one chain, the first included. A depth of 1 turns launching off. At the limit an agent gets no launch tools and no mention of them in its prompt, and the tool refuses a call made anyway.
  • Breadth (max_launches, default 10): the most launches one attempt of one agent may make. Launches that fail validation do not count. It is per attempt, not per job, so with the defaults a tree can reach 1 + 10 + 100 = 111 agents before retries. This is different from recursion_limit, which bounds the steps of one agent's own tool loop.

A launched child blocks its parent. One that does not is a background job, which is a job and has its own spec. The runner gives it start_background (and settings max_background_jobs and background=); the rules are there.

The slot hand-over. A parent that waits for its child holds a slot the child needs, and with enough waiting parents nothing could finish. So a parent gives up its slot while its launches run and takes one again when the last of them is done, also when it launched several at once. The limit on model calls at one time still holds, because a waiting parent is not calling the model.

Tools and connections

Each attempt builds a tool registry from the agent's tools, the tools of its MCP servers, and the tools the runner adds: launch_agent and get_agent_schema (with sub-agents and depth left) and get_skill (with skills) and search_tools and call_tool (with an MCP server that is found by search). A failure to build it is a setup error.

MCP connections are the runner's, shared by every agent it runs (MCP tools). A run holds a lease on its servers from its first attempt to its last, so a retry does not start a server again, and lets go when it is done. A server stops when its last lease is released. async with AgentRunner(...), or await runner.aclose(), is optional: it keeps servers up between runs and stops them at the end. A runner with no MCP agents needs neither.

Configuration

Argument Environment variable Default
max_attempts 3 At least 1
retry_delay_s 1.0
max_concurrent FTW_MAX_CONCURRENT_ATTEMPTS 10 At least 1
max_depth FTW_MAX_AGENT_DEPTH 3 At least 1
max_launches FTW_MAX_AGENT_LAUNCHES 10 At least 1
max_background_jobs FTW_MAX_BACKGROUND_JOBS 3 At least 1

An argument wins over the variable. A value below 1, or an environment variable that is not an integer, raises, and names the variable. The settings of the runner that have no argument, such as the timeout of an observer, and the rule for all of them, are in configuration. The key of the provider (GOOGLE_API_KEY, ANTHROPIC_API_KEY or OPENAI_API_KEY) is needed for the real model. A missing key is a setup error: the run fails at once, without retries.

Logging

run_started and run_finished (with attempts, tokens and latency), attempt_started, attempt_failed (with non_retryable), retry_waiting, waiting_for_slot and slot_acquired, fan_out_started and fan_out_finished, agent_launch (parent, child, depth and launch count), skill_read, and the mcp_* lines. All are plain key=value text through logging.

Observers

Built (#92 and #93). What an observer is, and what it receives, is in observers and OpenTelemetry. What the runner does:

  • Where they are set. AgentRunner(db, observers=[...]); the timeout is FTW_OBSERVER_TIMEOUT (1 second). A worker runs its jobs with its runner, so a job run by run_job and a job run by a worker call the same observers, and nothing is reported twice.
  • When it calls them. Around each attempt (from the moment it holds a slot and runs, until its row is finished; a streamed run: from its row to its end), when a step is reused (resuming: an event, not an attempt), and for each model call and tool call of an attempt. A streaming run is one attempt, with its model calls and tool calls, and none per token. Around the job: the one function that runs a job (execute_job, for run_job and for a worker) enters the observers' job scope before the pipeline and finishes it with the status and the error type, so an observer can make its span current while the pipeline runs (jobs); a worker hands it the message's trace context.
  • Model calls and tool calls. An attempt is one lc_agent.ainvoke(...), so they happen inside LangChain's agent loop. A callback handler added to the config of each attempt (and of a streamed run) turns LangChain's callbacks into the observers' events, with real timings. It does nothing when there are no observers.
  • Inline, and harmless. Every call is awaited, with a timeout (a second by default); an observer that raises or is slow is logged and ignored, so it never changes or fails a run. That includes a hook that raises when it is called, before anything is awaited.
  • Content is built only when asked. The runner builds the content fields of a record only if an observer says it wants content, and passes each observer the record without them unless that observer asked.
  • A launched agent knows its tool call. The callback sets the id of the tool call that is running (CURRENT_TOOL_CALL_ID, a context variable that LangChain copies into the tool's task), and launch_agent passes it as the child attempt's parent_tool_call_id. Without observers it is None.

Decisions

  • The runner does not choose the model. The agent's model settings are the only way to pick one, and the runner calls agent.model.build(). A test replaces the settings with fake ones, so tests take the production path (models).
  • Failures are values. A pipeline decides what a failed run means: skip a document, stop the job, ask again.
  • A retry resamples, and does not feed the error back. Feeding it back is a different feature, and the pipeline can do it by building a new input.
  • Allow-lists of classes, so that there is nothing to register and a rename is a normal refactor.
  • The child's result is text for the parent, not an exception, so that the parent's model can recover.
  • Depth and breadth, not cost. They are simple to explain and to set. A budget is not built.
  • Slots are held by attempts that call the model, which keeps the limit on model calls honest.
  • The runner owns no workflow. It is not a graph engine. Resuming is replay: the caller's code runs again, and the runner answers the runs that already succeeded.
  • AgentResult.reused. A plain flag, so that a pipeline or a test can tell a reused result from a run without reading the log.

Not supported

  • Finding agents. An agent knows only its own allow-list. There is no tool to search for agents.
  • Launching in the background. launch_agent waits for the child. An agent that does not wait is a background job.
  • Resuming inside a run. An attempt that failed halfway runs whole. Reusing the result of a sub-agent when its parent is run again is not built: a parent that failed reruns with its children.
  • A limit on launches per job, or on cost or tokens.
  • Streaming from run(). A streaming agent has its own method, stream().
  • Cancelling one run from outside. Cancelling the task that awaits run() cancels the run, and its row is CANCELLED. A streaming run has run.cancel() and runner.cancel(run_id).
  • A runner shared between processes. The slots and the connections are per runner.

Tests

test_runner.py (results, retries, non-retryable errors, token sums), test_limits.py (the three limits: defaults, environment variables, arguments, and the slot limit with run_many), test_concurrency.py (many runs at once do not interfere), test_resume.py (resuming a job), test_subagents.py (the allow-list, the two tools, depth and breadth, the slot hand-over with deadlock tests, tracing), and test_mcp.py (leases). A real-model test of launching is in tests/e2e/test_subagents_e2e.py.