tasks Package

Task subsystem for crash-resilient long-running agents.

Provides the <xref:task> and <xref:multi_turn_task> decorators plus supporting types for building Azure AI Hosted Agents that survive container crashes, OOM kills, and redeployments.

Key features:

  • Two decorators — @task (one-shot, single run, ephemeral) and @multi_turn_task (chain — every return X is one turn; chain stays alive in suspended between turns).
  • Lifecycle automation — .run() and .start() automatically start, resume, or recover tasks based on their current state.
  • Entry mode — ctx.entry_mode tells the handler whether it was entered fresh, resumed from suspension, or recovered from a crash.
  • RetryPolicy — configurable retry with exponential, fixed, or linear backoff (see <xref:RetryPolicy> presets).
  • Streaming lives in streaming; handlers call stream = await streams.get_or_create(invocation_id) to obtain a stream handle; TaskRun itself is NOT iterable.

Public API::

from azure.ai.agentserver.core.tasks import (
    task,
    multi_turn_task,
    Task,
    MultiTurnTask,
    RetryPolicy,
    TaskContext,
    TaskRun,
    TaskFailed,
    TaskCancelled,
    TaskDeferred,
    TaskConflictError,
    LastInputIdPreconditionFailed,
    SteeringQueueFull,
    InputTooLarge,
    JSONValue,
    TaskErrorDict,
    TaskExhaustedRetriesErrorDict,
    EntryMode,
)

Classes

InputTooLarge

Raised when an input's serialized size exceeds the per-input cap (: bare).

LastInputIdPreconditionFailed

Raised when Task.start's if_last_input_id precondition is not met.

: only actual_last_input_id is carried.

MultiTurnTask

A decorated multi-turn resilient task chain.

Distinct public class:class:Task — NOT a subclass. The type checker enforces "no .delete() on one-shot" and "multi-turn get_active_run takes both task_id AND input_id" statically.

Returned by the multi_turn_task decorator.

This class wraps an internal Task (same execution model) but exposes a strictly-typed multi-turn surface. The wrapped Task carries ephemeral=False so the framework knows the chain semantics.

RetryPolicy

Retry configuration for resilient tasks.

New in version 2.1.0.

SteeringQueueFull

Raised when the steering pending-input queue is at capacity (: bare).

Task

A decorated resilient task function. Not callable directly.

Use run (invoke-and-wait), start (fire-and-forget), or <xref:azure.ai.agentserver.core.tasks.Task.options> (per-call overrides).

TaskCancelled

Raised when a resilient task is cancelled (: bare).

TaskConflictError

Raised when a task lifecycle conflict cannot be resolved.

: only current_status is carried.

keyword current_status: The task's current status.

paramtype current_status: str

TaskContext

The single parameter to a resilient task function.

Provides access to the task's identity, typed input, cancellation signals (with cause booleans), and the ability to suspend or exit-for-recovery.

TaskDeferred

Raised when handler called ctx.exit_for_recovery.

Semantically DISTINCT from TaskCancelled — the task stays in_progress and recovery re-invokes the handler in a future lifetime. Bare exception.

TaskErrorDict

Shape of:attr:TaskFailed.error for a normal handler-raise failure.

TaskExhaustedRetriesErrorDict

Shape of:attr:TaskFailed.error when the retry budget was exhausted.

TaskFailed

Raised when a resilient task function raises an unhandled exception.

: only error is carried. task_id is no longer on the exception (caller has it from the run handle).

keyword error: Structured error details (matches one of TaskErrorDict or TaskExhaustedRetriesErrorDict).

paramtype error: dict[str, Any]

TaskManagerNotInitialized

Raised when a resilient-task operation is attempted with no installed manager.

Signals that the resilient-task subsystem is not available in the current process — for example an in-process test harness that never ran the server lifespan, or a deployment where the manager failed to initialize at boot. Subclasses RuntimeError for backward compatibility with callers that catch the broader type.

TaskRun

Handle to a running or completed resilient task.

Returned by start. Provides external observation and control of the task lifecycle.

Functions

multi_turn_task

Decorator producing a multi-turn resilient chain.

Multi-turn chains accept inputs across many turns against the same task_id. The handler's return X is the implicit-suspend signal — there is no ctx.suspend. The chain stays alive across handler raises.

multi_turn_task(fn: Callable[[...], Any] | None = None, *, name: str | None = None, title: str | None = None, timeout: timedelta | None = None, retry: RetryPolicy | None = None, steerable: bool = False, **_extra_kwargs: Any) -> Any

Parameters

Name Description
fn
Callable[..., Any] | None

The handler to decorate (parameterized form only; the bare @multi_turn_task form is rejected because it cannot supply a name).

Default value: None

Keyword-Only Parameters

Name Description
name

Required stable chain-identity anchor (no function-derived default; omitting it raises ValueError).

Default value: None
title

Static human-readable string. Callable-factory form is not supported.

Default value: None
timeout

Per-turn cooperative timeout. Defaults to 1 day when unset; 7 days is a hard ceiling (larger/negative rejected at decoration). This is a per-turn cap, not a chain-lifetime bound.

Default value: None
retry

Default retry policy.

Default value: None
steerable

When True, start() against an in-flight chain queues the new input instead of raising TaskConflictError.

Default value: False

Returns

Type Description
Any

A MultiTurnTask instance (distinct public class from Task).

resilient_tasks_enabled

Return the Invocations task-runtime opt-in setting.

This does not report whether a Responses host has enabled its own runtime.

resilient_tasks_enabled() -> bool

Returns

Type Description

True if set_resilient_tasks_enabled turned it on.

set_resilient_tasks_enabled

Enable or disable task execution for Invocations hosts.

Enabled hosts initialize a persistent task manager, perform startup recovery and run the periodic recovery loop. Set this before lifespan startup. Responses hosts use their own feature options independently, including on cooperative multi-protocol hosts. This setting remains process-global for Invocations configuration and defaults to enabling when called without an argument.

set_resilient_tasks_enabled(value: bool = True) -> None

Parameters

Name Description
value

True to enable the resilient task subsystem, False to clear.

Default value: True

task

Turn an async function into a crash-resilient one-shot resilient task.

One-shot tasks are always ephemeral — the persisted record is deleted on terminal exit. task_id is optional on the resulting handle's .start / .run calls; the framework auto-generates a GUID and defaults input_id to task_id (1:1 invariant).

name is required — always use the parameterized form:


   @task(name="my-task")
   async def my_task(ctx: TaskContext[MyInput]) -> MyOutput: ...

Note

Use @multi_turn_task for steerable chains. Passing

ephemeral= or steerable= to @task raises

TypeError at decoration time.

task(fn: Callable[[...], Any] | None = None, *, name: str | None = None, title: str | None = None, timeout: timedelta | None = None, retry: RetryPolicy | None = None, **_extra_kwargs: Any) -> Any

Parameters

Name Description
fn
Callable[..., Any] | None

The async function to decorate (parameterized form only; the bare @task form is rejected because it cannot supply a name).

Default value: None

Keyword-Only Parameters

Name Description
name

Required stable identity anchor. Used for recovery routing and source stamping. There is no function-derived default: deriving it from fn.__qualname__ would silently rebind task identity whenever the function is renamed or moved, orphaning in-flight tasks on the next deploy. Omitting it (or passing whitespace) raises ValueError at decoration.

Default value: None
title

Static human-readable string.

Default value: None
timeout

Per-turn, wall-clock, resilient, cooperative-only execution budget. Defaults to 1 day when unset; a supplied value may raise the budget up to 7 days, which is a hard ceiling (a larger or negative value raises ValueError at decoration). This caps a single handler invocation only — it is NOT a task-lifetime bound. When the budget elapses for the current turn, ctx.timeout_exceeded is set then ctx.cancel is set; the handler decides whether to wind down. The watchdog does NOT force-stop the handler. See the developer guide §4 Timeout for the full mechanic (including the crash-mid-turn budget-preserving recovery semantics).

Default value: None
retry

Default retry policy for this task. Recovery-safe: applied by the framework on every entry, including crash recovery.

Default value: None

Returns

Type Description
Any

A Task[Input, Output] wrapper.