Tasks
Model runs and standalone work share the task lifecycle: TaskStarted, optional TaskProgress, and one terminal event — TaskCompleted, TaskFailed, TaskExpired, or TaskCancelled. Observers, network mirrors, and UIs consume the same events in each case.
Model Runs#
Pass capability or ttl_seconds to enable lifecycle events for an agent invocation:
capability tags the work for network observations. The task title (TaskStarted.objective) is the agent's name, never the prompt, because task events are mirrored to the network hub; a delegation uses its objective. ttl_seconds carries an absolute expiry deadline on TaskStarted; an external observer owns expiry. It does not set a local execution timeout. Omitting both options leaves ordinary runs without task lifecycle events.
The observable form accepts the same options:
Entering run opens the scope. TaskStarted is emitted when start() or result() drives it; leaving an undriven run emits no task events. Repeated result() calls share one invocation and one lifecycle. The terminal is emitted after middleware and observer cleanup when the run scope closes. ask() completes that cleanup before it returns. Subscribe directly to the stream to observe the terminal after run-scoped observers have been released.
A model or tool exception produces TaskFailed and propagates to the caller. Cancelling the turn or leaving a running scope produces TaskCancelled after running tools and descendants have settled. Setup errors produce a start/failure pair even if the model never runs. Cleanup errors, including a storage failure while usage is recorded, produce a failure terminal and propagate to the caller; cleanup cancellation produces TaskCancelled. Before publishing its terminal, an opted-in run waits for delegations it left running in the background, so ask() returns once they have settled.
Waiting for a shared stream's turn lock happens before the run scope opens. Cancelling an ordinary invocation during that wait emits no task events. A delegation also reports a rejected attempt to its parent as a start/cancellation pair, using the same lifecycle transitions without entering the busy stream.
AgentReply.ask(), AgentReply.run(), and Agent.resume() accept the same options. Each continuation gets a fresh task identity when opted in; capability and TTL are supplied per invocation. Recovery of model work uses the recorded trajectory and resume().
Delegations through Agent.as_tool() use this lifecycle automatically, with the delegation's task ID and parent tool-call ID. Ancestors receive the same events with their source path, without duplicate starts or terminals. See Subagents.
Standalone Work#
Construct Task directly for arbitrary coroutines outside the model loop. Tasks are owner-driven; the framework does not assign or schedule them.
When to Use a Standalone Task#
Use a Task whenever a unit of work has a beginning, an end, and observable progress that you want to surface beyond your own function's return value:
- Long-running pipelines where downstream consumers want progress checkpoints.
- HITL approvals where a UI needs to know the task is waiting on a human.
- Test harnesses that assert a sequence of lifecycle events.
Standalone Example#
The async with block opens the lifecycle. On clean exit the task auto-completes with result=None if you didn't call complete() or fail() yourself.
Lifecycle States#
CREATED -> RUNNING -> COMPLETED (terminal, success)
-> FAILED (terminal, exception or explicit fail)
-> EXPIRED (terminal, externally observed expiry)
-> CANCELLED (terminal, explicit or coroutine cancellation)
| State | Meaning |
|---|---|
CREATED | The Task object exists but __aenter__ has not run. task.task_id and task.metadata raise. |
RUNNING | Inside the async with block. Progress events allowed. |
COMPLETED | Reached complete() or clean block exit. |
FAILED | Reached fail() or block exited via exception. |
EXPIRED | An external observer marked the task expired. |
CANCELLED | Reached cancel() or the coroutine exited with asyncio.CancelledError. |
The terminal states are immutable — once set, further complete() / fail() / progress() calls are silent no-ops. The set is exported as ag2.task.TERMINAL_TASK_STATES.
API Reference#
Task(...)#
from ag2.task import CheckpointStore, Task, TaskSpec
Task(
owner_id=agent.name,
spec=TaskSpec(
title="index documents",
description="",
payload={},
capability=None,
),
context=None,
ttl_seconds=None,
checkpoint_store=None,
resume_from=None,
)
| Parameter | Type | Description |
|---|---|---|
owner_id | str | Owner identity included in lifecycle events; use agent.name for agent-owned work. |
spec | TaskSpec | Title, description, payload and optional capability tag. |
context | ConversationContext \| None | Events flow on context.stream; TaskInject resolves to this Task for the duration of the block. If omitted, the Task creates a private MemoryStream on entry. |
ttl_seconds | int \| None | Sets metadata.expires_at; an external observer owns expiry. |
checkpoint_store | CheckpointStore \| None | Store for owner-defined checkpoint state. |
resume_from | str \| None | Prior task ID whose checkpoint is loaded into task.resumed_state on entry. |
Returns an unentered Task. Construction does not start work or emit events.
TaskSpec describes the work:
| Field | Type | Default | Description |
|---|---|---|---|
title | str | Required | Short objective shown on every event. |
description | str | "" | Longer description. |
payload | dict[str, Any] | Fresh {} | Owner-defined task data. |
capability | str \| None | None | Capability name used by network mirrors. |
Task instance methods#
| Method | Description |
|---|---|
await task.progress(payload) | Emits TaskProgress; merges payload into metadata.progress and stamps last_progress_at. No-op if already terminal. |
await task.complete(result=None) | Terminal. Emits TaskCompleted; sets metadata.result and state = COMPLETED. |
await task.fail(error) | Terminal. Accepts a string (wrapped in RuntimeError) or any BaseException. Emits TaskFailed; sets state = FAILED. |
await task.cancel(reason="") | Terminal. Emits TaskCancelled; sets state = CANCELLED. |
await task.checkpoint(state) | Persists owner-defined recovery state through the configured store. |
await task.expire() | Terminal. Emits TaskExpired; sets state = EXPIRED. Called by external TTL observers. |
Properties#
| Property | Available before __aenter__? |
|---|---|
task.state | Yes — returns TaskState.CREATED. |
task.task_id | No — raises RuntimeError. |
task.metadata | No — raises RuntimeError. |
task.context | No — raises RuntimeError. |
Bound Context vs. Standalone#
Passing a ConversationContext shares the stream with the rest of your agent's run, so observers and middleware already attached to that stream see the lifecycle events.
Without a context, the Task creates a private stream on entry. Events still fire — but only observers attached to that private stream see them. Useful for one-off background work that doesn't need to surface anywhere.
Auto-Complete and Auto-Fail#
The async with block has these guarantees:
- Clean exit, no terminal call -> auto
complete(result=None). - Exception inside the block -> auto
fail(exc), then the exception propagates. - Coroutine cancellation -> auto
cancel("cancelled"), then cancellation propagates. - Already terminal at exit time -> nothing further happens.
Observing the Lifecycle#
Subscribe directly on the bound stream to capture every lifecycle event in order.
Note
TaskProgress is marked transient — it is delivered live to subscribers but not persisted to the stream's storage. Subscribe before the events fire to capture them. TaskStarted, TaskCompleted, TaskFailed, and TaskExpired are persisted normally.
Reading the Active Task with TaskInject#
Model runs do not inject a standalone Task or replace one supplied by an enclosing block. Use context variables for model-run state.
Code running inside an async with Task(...) block can reach the task without having it passed around: annotate a parameter with TaskInject and the framework injects the task whose block encloses the call.
TaskInject annotation#
TaskInject is a fast_depends-resolvable annotation that injects the enclosing task into any function the dependency-injection machinery resolves — most usefully a @tool body.
TaskInject resolves to None when no task encloses the call, so always null-check before use.
Which task a tool sees#
Open the block on the stream the agent's turn runs on, and the turn's tools report to that task:
- Parallel tool calls. When several calls in one model response each open their own task — for example from tool middleware that wraps every call in
Task(...)— each call resolves its own task, whatever the others do. - Nested blocks. A nested block resolves to the innermost enclosing task; once it exits, the outer task again.
- Other conversations. A turn on a different stream started inside the block does not see the task. That includes subagents (
as_tool): a delegation runs on its own stream and is its own task scope. - Outside the block. Code the block does not enclose — after it exits, or a handler or background task started before it — resolves
None, not some other task.
Outside any block, a task you pass yourself as the "ag2.task" dependency is injected — handy for testing a tool on its own:
Direct access#
For direct readers of the dict, context.dependencies["ag2.task"] also holds a task for the duration of the block:
The slot is best-effort when tasks overlap: with parallel tool calls each opening a task on one conversation, it can only name the most recently entered task still running. Prefer TaskInject, which does not read the slot a block stamped.
TTL and Expiry#
Setting ttl_seconds=N populates metadata.expires_at but does not start a timer. The Task primitive itself never self-expires — that's by design, so a standalone Task with no observer doesn't spawn a background task. Instead, an external observer (e.g. a network hub's TTL sweeper, a periodic watch) checks expires_at and calls task.expire() when due.
For self-contained TTL behaviour, wire up a sweeper in your application:
Checkpoint and Recovery#
Pass a checkpoint_store to persist owner-defined state with await task.checkpoint(state). To continue that work, construct a new Task with the same store and resume_from set to the prior task ID. On entry, task.resumed_state contains the saved state, or None if no checkpoint is available. The application decides how to continue from that state.
from ag2.task import Task, TaskSpec
async with Task(
owner_id=agent.name,
spec=TaskSpec(title="index documents", capability="indexing"),
context=ctx,
checkpoint_store=store,
resume_from=prior_task_id,
) as task:
next_document = (task.resumed_state or {}).get("next_document", 0)
await task.progress({"next_document": next_document})
# Process the next batch, then save where to continue.
await task.checkpoint({"next_document": next_document + 12})
Without a checkpoint store, checkpoint() is a no-op and resumed_state is None.
TaskSpec and TaskMetadata#
Two small dataclasses surface around a Task:
TaskSpec— what the task is doing:title,description,payload, optionalcapability. Passed toTask(spec=...).TaskMetadata— mutable lifecycle record updated on each transition:task_id,owner_id,spec,state, ISO-8601 timestamps,progress,result,error, optionalchannel_id.