Skip to content

artifactr.agent

artifactr's integration with pydantic-ai.

Give an agent the ArtifactWorkspace capability and deps_type=Session[...], then run it in threads with a Runner::

agent = Agent(
    "anthropic:claude-sonnet-5-5",
    deps_type=Session[None],
    capabilities=[ArtifactWorkspace(types=[Doc, Plan])],
)
runner = Runner(agent, app=None)
await runner.send(workspace, thread_id, "Draft a launch plan")

The capability

See The agent.

ArtifactWorkspace dataclass

ArtifactWorkspace(
    types: Sequence[type[Artifact]],
    *,
    ask: bool = False,
    max_render_chars: int = 4000,
    max_summary_chars: int = 2000,
    notices: bool = False,
)

Bases: AbstractCapability[Session[Any]]

Make an agent a participant in a workspace.

Parameters:

Name Type Description Default
types Sequence[type[Artifact]]

The artifact types the agent may create.

required
ask bool

Include the ask_user tool, which pauses the run until someone answers. The agent's output_type must then include DeferredToolRequests.

False
max_render_chars int

How much of each followed artifact's rendering to include in the instructions.

4000
max_summary_chars int

How much of each tool call's arguments and result to record, which is what people see of the call.

2000
notices bool

Tell the agent about the notices others post in its thread, as change notes, when a run starts and while it runs, so they are kept in its history. They are left out by default.

False

get_toolset

get_toolset() -> FunctionToolset[Session[Any]]

Return the generic artifact tools.

get_instructions

get_instructions() -> Any

Return the instructions, rendered fresh for every model request.

wrap_run async

wrap_run(
    ctx: Context, *, handler: WrapRunHandler
) -> AgentRunResult[Any]

Record the run, brief the agent, and watch the workspace while it runs.

wrap_model_request async

wrap_model_request(
    ctx: Context,
    *,
    request_context: ModelRequestContext,
    handler: WrapModelRequestHandler,
) -> ModelResponse

Count what the request used, as its provider says, and tell the run's live channel.

The total sent is the run segment's requests summed: pydantic-ai's own count takes a streamed response in parts, its tokens before its request, so mid-step it is neither (ADR-0096). The run's end sums the same steps.

before_tool_execute async

before_tool_execute(
    ctx: Context,
    *,
    call: ToolCallPart,
    tool_def: ToolDefinition,
    args: ValidatedToolArgs,
) -> ValidatedToolArgs

Record the tool call.

on_tool_validate_error async

on_tool_validate_error(
    ctx: Context,
    *,
    call: ToolCallPart,
    tool_def: ToolDefinition,
    args: RawToolArgs,
    error: ValidationError | ModelRetry,
) -> ValidatedToolArgs

Record a call whose arguments were refused, and why: the model is told, and retries.

wrap_tool_execute async

wrap_tool_execute(
    ctx: Context,
    *,
    call: ToolCallPart,
    tool_def: ToolDefinition,
    args: ValidatedToolArgs,
    handler: WrapToolExecuteHandler,
) -> Any

Record a tool's own ModelRetry or ToolFailed, which skip the error hook.

A call lattice's enforcer deferred is noted in the session by its approval's id, which the Runner withdraws if the run segment ends before it pauses on it (ADR-0102).

after_tool_execute async

after_tool_execute(
    ctx: Context,
    *,
    call: ToolCallPart,
    tool_def: ToolDefinition,
    args: ValidatedToolArgs,
    result: Any,
) -> Any

Record the tool's result.

on_tool_execute_error async

on_tool_execute_error(
    ctx: Context,
    *,
    call: ToolCallPart,
    tool_def: ToolDefinition,
    args: ValidatedToolArgs,
    error: Exception,
) -> Any

Turn rejections into retries the model can act on; record every failure.

Session dataclass

Session(
    workspace: Workspace,
    thread_id: ThreadId,
    run_id: RunId,
    app: AppDepsT,
    trigger: Trigger = "api",
    watch_after: int | None = None,
    message_ids: tuple[MessageId, ...] = (),
    model: str | None = None,
)

The pydantic-ai deps of one agent run.

Tools receive it as ctx.deps. Its workspace handle acts as the thread's agent, for whoever started the run segment, so everything a tool commits is attributed to the agent and this run, and checked as done for them.

Create it with start rather than directly.

app instance-attribute

app: AppDepsT

The application's own dependencies.

watch_after class-attribute instance-attribute

watch_after: int | None = None

Watch the log for others' changes after this seq; None means from the run's start.

message_ids class-attribute instance-attribute

message_ids: tuple[MessageId, ...] = ()

The messages the run segment's start carries out, which its run_started names.

model class-attribute instance-attribute

model: str | None = None

The model the run segment asked for, by the host's name for it, which its run_started names; None for the agent's own (ADR-0097).

delivered class-attribute instance-attribute

delivered: Delivered = field(
    default_factory=Delivered,
    init=False,
    repr=False,
    compare=False,
)

How far the run has taken the log: to watch_after once it has started, then as far as its watcher delivers. The capability records it with the run's start and its end.

steps class-attribute instance-attribute

steps: list[StepUsage] = field(
    default_factory=list[StepUsage],
    init=False,
    repr=False,
    compare=False,
)

What each of the run segment's model requests used, oldest first, as the capability counts them: recorded with the segment's end, however it ends (ADR-0096).

made class-attribute instance-attribute

made: set[ArtifactId] = field(
    default_factory=set[ArtifactId],
    init=False,
    repr=False,
    compare=False,
)

The artifacts the run segment's tools made as the person it acts for, which its watcher doesn't tell it of as the person's: a tool adds an id before it commits.

asked class-attribute instance-attribute

asked: set[str] = field(
    default_factory=set[str],
    init=False,
    repr=False,
    compare=False,
)

The approvals lattice's enforcer asked for the run segment's calls, by id, as its bridge deferred them: a segment stopped or failed before it paused on them withdraws them (ADR-0102).

on_behalf_of property

on_behalf_of: UserActor | ExternalAgentActor | None

Whom the run segment acts for: its agent's on_behalf_of.

Spans record a person here as the user.

start classmethod

start(
    workspace: Workspace,
    thread_id: ThreadId,
    *,
    app: AppDepsT,
    run_id: RunId | None = None,
    agent_name: str = "assistant",
    trigger: Trigger = "api",
    watch_after: int | None = None,
    on_behalf_of: UserActor
    | ExternalAgentActor
    | None = None,
    message_ids: tuple[MessageId, ...] = (),
    model: str | None = None,
) -> Session[AppDepsT]

Return a session for a new (or resuming) run of the thread's agent.

Parameters:

Name Type Description Default
workspace Workspace

A handle on the workspace; the session derives the agent's handle.

required
thread_id ThreadId

The thread the agent runs in.

required
app AppDepsT

The application's own dependencies, available to tools as ctx.deps.app.

required
run_id RunId | None

The run's id; a new one is generated when omitted.

None
agent_name str

How the agent is named in change notes and messages.

'assistant'
trigger Trigger

What started the run.

'api'
watch_after int | None

The seq after which others' changes are delivered into the run.

None
on_behalf_of UserActor | ExternalAgentActor | None

Whom the run segment acts for: the person, or the person's client, whose message or answer started it.

None
message_ids tuple[MessageId, ...]

The messages its start carries out.

()
model str | None

The model it asks for, by the host's name for it; None for the agent's.

None

RunFailure

RunFailure(message: str, *, reason: str)

Bases: Exception

An exception that fails a run for a known reason, recorded in its run_ended.

Raise a subclass from a tool or a capability to give a failure a typed reason instead of an opaque error: the run ends as failed, with reason and the exception's message.

Parameters:

Name Type Description Default
message str

What happened, for people.

required
reason str

A short, stable code, such as guardrail_blocked.

required

Trigger module-attribute

Trigger = Literal['message', 'resume', 'api']

What started a run: a posted message, answers to a pause, or a direct call.

load_history async

load_history(
    workspace: Workspace, thread_id: ThreadId
) -> list[ModelMessage]

Return a thread's model history, to pass as message_history.

last_seen async

last_seen(workspace: Workspace, thread_id: ThreadId) -> int

Return the seq up to which the thread's agent has been told what happened.

Running agents in threads

See Running the agent.

Runner

Runner(
    agent: Agent[Session[AppDepsT], Any],
    *,
    app: AppDepsT,
    live: FanoutChannel | None = None,
    agent_name: str = "assistant",
    claim_ttl: timedelta = timedelta(seconds=30),
    look_again_after: timedelta | None = None,
    tracer_provider: TracerProvider | None = None,
    meter_provider: MeterProvider | None = None,
    turn_context: TurnContext | None = None,
    evaluators: Sequence[TurnEvaluator] = (),
    results: CommandResults | None = None,
    liveness: Liveness | None = None,
    model_for: ModelFor | None = None,
    approvals: Approvals | None = None,
    surface: str = "portalr",
)

Runs an agent in workspace threads.

Parameters:

Name Type Description Default
agent Agent[Session[AppDepsT], Any]

The agent, whose deps_type is Session[AppDepsT] and which has the ArtifactWorkspace capability.

required
app AppDepsT

The application's dependencies, passed to every run as ctx.deps.app.

required
live FanoutChannel | None

Where runs' live frames go. Defaults to an in-process fan-out.

None
agent_name str

How the agent is named in the workspace.

'assistant'
claim_ttl timedelta

How long a thread claim lasts without renewal, should this process die. Once it lapses, the thread's next run records the run left behind as abandoned, and a run of this process whose claim is lost is cancelled. A claim is lost as storage says, not as this process's loop does: one renewed late, after a stall, is kept if no one else had it meanwhile. A claim is renewed every third of it, so a run survives one failed renewal, or storage that stalls for about two thirds of it. It must exceed the clock skew between replicas.

timedelta(seconds=30)
look_again_after timedelta | None

How long a claimant that finds its thread claimed waits before it looks again, in case the claim's holder died. Defaults to claim_ttl, the soonest the claim could have lapsed; a look before then is refused, and waits again.

None
tracer_provider TracerProvider | None

Where turn spans go. Defaults to the global tracer provider.

None
meter_provider MeterProvider | None

Where turn metrics go. Defaults to the global meter provider.

None
turn_context TurnContext | None

Entered around each turn, inside its span.

None
evaluators Sequence[TurnEvaluator]

Given each turn as it ends, to judge it in the background, such as artifactr.evals.OnlineEvaluators.

()
results CommandResults | None

Where execute remembers commands' results. Defaults to the 10,000 most recent, in this process.

None
liveness Liveness | None

How long a turn waits for a model, or a tool, that sends nothing before it fails the run, model_stalled or tool_stalled. Defaults to Liveness's: two minutes for a hosted model, five for a local one, ten for a tool.

None
model_for ModelFor | None

The host's models by name, for messages that name one (ADR-0097). A turn answers with the model its first message names, if its author may use it (artifactr:use_model) and the host knows it; otherwise with the agent's own, and a notice says why. Without it, every turn answers with the agent's own model, and a message that names one is told so.

None
approvals Approvals | None

The application's store of approvals, the one its enforcer asks (lattice RFC-0011). An approval a call waits on is answered there, and the Runner follows each one a paused run waits on, so an answer given anywhere resumes the run (ADR-0101). Without it, an answer to one is refused.

None
surface str

The surface the store records an answer sent with the Runner as given on: portalr, whose thread shows the request, by default.

'portalr'

execute async

execute(
    workspace: Workspace,
    command: Command | StopRun,
    *,
    command_id: str,
) -> CommandResult

Carry out a command the way every surface should, once per command_id.

Messages and answers go through send and answer, so they start, steer and resume runs; stop_run stops a run of this workspace that runs in this process; everything else, notices included, is committed as-is. A rejection is the result, not raised.

A command is known by its tenant, workspace, sender (the handle's actor, as a participant) and command_id. The first time, it is carried out and its result is remembered. A repeated id returns the remembered result and carries nothing out, whatever command it comes with, so a retry is safe on every surface.

send async

send(
    workspace: Workspace,
    thread_id: ThreadId,
    content: str,
    *,
    message_id: MessageId | None = None,
    model: str | None = None,
) -> Sent

Post a message as the workspace handle's actor, and ask for the thread's next turn.

A model is the one to answer with, if this message starts a turn (ADR-0097): one that joins a running turn is answered by the turn's model. A model the sender may not use, or the host doesn't know, is not refused here: the turn answers with the agent's own, and a notice says so.

Raises:

Type Description
InvalidState

If message_id is already used in the workspace; nothing is done.

Forbidden

If authorize refuses the message, or the turn it would start, as the agent acting for the sender (ADR-0057); nothing is done.

ask async

ask(
    workspace: Workspace, thread_id: ThreadId
) -> RunHandle | None

Ask for the thread's next turn, for whatever its log has that no turn has taken.

send asks once it has committed its message. A caller whose ask may have been lost, because its process stopped between the two, asks again here: a retried send finds its message id used (ADR-0064). It is asked as send is, as the agent acting for the handle's actor. With nothing untaken, it does nothing.

Raises:

Type Description
Forbidden

If authorize refuses the turn it would start.

answer async

answer(
    workspace: Workspace, command: AnswerDeferred
) -> Sent

Answer one of a paused run's requests, resuming the run once all are answered.

An approval the enforcer asked is answered in the store first, as the person the handle's actor is, bound to the arguments the request shows by their digest, with the answer, if it is text, as the reason (ADR-0101). The store's refusal is the answer's. One settled already, as on another surface, is refused with how it was settled, and the thread takes that.

Raises:

Type Description
Forbidden

If the actor isn't a person, or neither artifactr nor the store lets them answer it.

InvalidState

If the approval was settled already, or the Runner keeps no store.

NotFound

If the store has no such approval.

resume async

resume(
    workspace: Workspace, run_id: RunId
) -> RunHandle | None

Ask for the thread's next turn, which resumes a paused run whose requests are answered.

The turn is whatever the thread's log calls for, as for a message: the thread's oldest message that no turn has taken answers the run's open requests, if it has any, and otherwise goes to the resumed run with any later ones. With nothing asked of the thread that no turn has taken, it does nothing.

recover async

recover(workspace: Workspace) -> list[RunHandle]

Take the turns the workspace was asked for, and end the runs a dead process left.

Call it for each workspace as the application starts. A process that died holding a thread, or between an ask and its claim, left what was asked for no one to take (ADR-0070). A thread whose dead holder's claim has not lapsed yet is looked at again once it could have. It acts as the Runner, as a hand-over does, and asks nothing of the handle's actor; a thread hidden from the Runner is not swept. A thread whose turn fails to start is logged, and the others are still taken. A closed runner takes none. Returns the runs it started.

A run left running by a process that died is recorded as failed, abandoned, once its thread can be claimed, as the thread's next turn would record it (ADR-0095): until then every client is told the run is active. Its usage went with its process, so it has none. A thread claimed by another, as a dead process's thread still is until its claim lapses, is swept again once, look_again_after later; a live holder's is left to it, as it records its own run's end.

stop async

stop(run_id: RunId) -> bool

Cancel a run of this process. Returns whether there was one to stop.

It asks nothing: callers check. execute asks artifactr:stop_run before it stops a run for a client.

drain async

drain() -> None

Wait until no run of this process is handing its thread over.

A run that ends hands its thread over in the background (ADR-0055): it starts the thread's next turn if a message or an answer asked for one meanwhile. This waits until none is pending, not for the turns they start. aclose cancels them instead; a hand-over it cancels ends this wait, rather than raising here. It does not wait for a claimant that another holder's claim refused to look again, look_again_after on.

aclose async

aclose() -> None

Stop every run of this process, wait for them to end, and start no more.

watch

watch(run_id: RunId) -> AsyncIterator[LiveFrame]

Yield a run's live frames from now until it ends.

running

running(thread_id: ThreadId) -> RunHandle | None

Return this process's run in a thread, if there is one.

A run is forgotten as its task's done callbacks run, the loop's turn after the task is done, and before anything awaiting the task resumes.

RunHandle dataclass

RunHandle(
    run_id: RunId,
    thread_id: ThreadId,
    task: Task[AgentRunResult[Any]],
)

A run started by a Runner.

wait async

wait() -> AgentRunResult[Any]

Wait for the run to finish (or pause) and return its result.

Sent dataclass

Sent(outcome: Recorded, run: RunHandle | None)

What posting a message, or an answer, did.

outcome instance-attribute

outcome: Recorded

The recorded message or answer, with the run_id of run, if there is one.

run instance-attribute

run: RunHandle | None

The run it started or resumed, or None when it started none, which is not a failure:

  • The thread's run is active, in this process or another, so the message steers it. If that run is ending or pausing and takes no more messages, it hands the thread over as it releases it, and the next turn takes the message. If its process died, this runner looks again once the run's claim could have lapsed, and takes the message then.
  • Another message or answer took the thread first, and its turn takes this one too, if it acts for the same author; otherwise the turn after it does.
  • An answer leaves some of the paused run's requests unanswered, so the run waits for them.
  • The runner is closed (Runner.aclose), as the application shuts down. The thread's next claimant, in any process, carries the message or answer out.

The run it started may take an older message first: the thread's oldest message that no turn has taken, however it was committed. In a paused thread, that message is the reply. A message in an idle thread, such as one just created, starts a run unless another starts one first, so code that owns its thread can assert that run is set.

CommandResults

Bases: Protocol

Where a runner remembers the results of commands: a port (ADR-0034).

InMemoryCommandResults remembers them in the process. An implementation over shared storage would deduplicate across processes too.

get async

get(key: CommandKey) -> CommandResult | None

Return the result remembered for a command, if there is one.

put async

put(key: CommandKey, result: CommandResult) -> None

Remember a command's result.

InMemoryCommandResults

InMemoryCommandResults(capacity: int = 10000)

The most recent results, in this process: the default CommandResults.

Parameters:

Name Type Description Default
capacity int

How many results to remember. Beyond it, the oldest is forgotten first, and a command whose result was forgotten is carried out again if it is repeated.

10000

get async

get(key: CommandKey) -> CommandResult | None

Return the result remembered for a command, if it is still remembered.

put async

put(key: CommandKey, result: CommandResult) -> None

Remember a command's result, forgetting the oldest beyond the capacity.

CommandKey dataclass

CommandKey(
    tenant_id: TenantId,
    workspace_id: WorkspaceId,
    participant: str,
    command_id: str,
)

What makes two commands the same: who sent them, where, and with which id.

tenant_id instance-attribute

tenant_id: TenantId

The tenant of the workspace the command was sent to.

workspace_id instance-attribute

workspace_id: WorkspaceId

The workspace it was sent to.

participant instance-attribute

participant: str

The sender, as its actor's participant: every action of one person or client.

command_id instance-attribute

command_id: str

The id the client chose for the command.

TurnContext

A context entered around each turn, inside the turn's span, given the run's session.

It is a port (ADR-0034): a backend that attributes a turn in its own way, such as Langfuse's propagated trace attributes, implements it, and the Runner stays free of the backend.

TurnEvaluator

Bases: Protocol

Judges turns after they end: a port (ADR-0034, ADR-0044).

artifactr.evals.OnlineEvaluator adapts evalr's online evaluation to it; the Runner knows nothing of evalr.

submit

submit(turn: EndedTurn) -> object

Start judging a turn that ended, in the background, and return at once.

It must not wait for the evaluation: the Runner calls it as the turn ends. A failure it raises is recorded on the turn's span, never raised to the turn.

EndedTurn dataclass

EndedTurn(
    session: Session[Any],
    outcome: TurnOutcome,
    span: SpanContext,
)

A turn that has ended, as the Runner hands it to its evaluators.

session instance-attribute

session: Session[Any]

The turn's session: its workspace handle (acting as the agent), thread and run.

outcome instance-attribute

outcome: TurnOutcome

How the turn ended.

span instance-attribute

The turn's invoke_workflow turn span, on whose trace evaluations are recorded.

TurnOutcome

TurnOutcome = Literal[
    "completed", "paused", "failed", "stopped"
]

How a turn ended: the agent finished, paused on questions, raised, or was stopped.

A model, or a tool, that sends nothing

See A model that sends nothing.

Liveness dataclass

Liveness(
    first_output: float = 120.0,
    no_output: float = 120.0,
    local_first_output: float = 300.0,
    local_no_output: float = 300.0,
    tool: float | None = 600.0,
    local_models: frozenset[str] = frozenset(),
    hosted_models: frozenset[str] = frozenset(),
)

How long a turn waits for a model, or a tool, that sends nothing, in seconds.

Parameters:

Name Type Description Default
first_output float

The most a hosted model's request may take to its first event.

120.0
no_output float

The most a hosted model may go between events, once it has started.

120.0
local_first_output float

The same, for a model served locally.

300.0
local_no_output float

The same, for a model served locally.

300.0
tool float | None

The most a tool call may take to return; None lets a tool take as long as it needs.

600.0
local_models frozenset[str]

Names of models to treat as local whatever their shape.

frozenset()
hosted_models frozenset[str]

Names of models to treat as hosted whatever their shape.

frozenset()

limits

limits(model_name: str) -> tuple[float, float]

The limits for a model, by name: to its first event, and between events.

is_local_model

is_local_model(
    name: str,
    *,
    local: Collection[str] = (),
    hosted: Collection[str] = (),
) -> bool

Whether a model, by name, is served locally: slower to its first token than a host's.

local and hosted are the application's own say, by exact name, which wins over the name's shape; hosted wins over local where both name it. Otherwise a name with a local provider's prefix (ollama/, lm_studio/, omlx/, llamacpp/, vllm/) or a local alias (local, local-*, local/*) is local, and any other name, an unknown one among them, is hosted.

ModelStalled

ModelStalled(model: str, seconds: float, *, first: bool)

Bases: RunFailure

The model sent nothing for longer than the turn waits: the run fails, model_stalled.

ToolStalled

ToolStalled(tools: Collection[str], seconds: float)

Bases: RunFailure

A tool call didn't return within the turn's wait: the run fails, tool_stalled.

tools names the calls still running as the wait ran out: the wait starts again at each event, so which of them stalled isn't known. A name called twice is named once. A call deferred to a person (CallDeferred, ApprovalRequired) sends no result either, so beside a call that really hung it is named as still running too.

Scripted models

See Testing your application.

function_model

function_model(respond: Respond) -> FunctionModel

Return a pydantic-ai FunctionModel that answers every request with respond.

A plain request gets the response as it is. A streamed request, which is every request of a run the Runner starts, gets it streamed: each text part as one text delta, each thinking part as one thinking delta, and each tool call whole. Script a model for a test with it, rather than writing a stream function beside the function::

def respond(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
    return ModelResponse(parts=[TextPart("On it.")])


with agent.override(model=function_model(respond)):
    ...

Parameters:

Name Type Description Default
respond Respond

Answers each request from the messages so far, as FunctionModel's function does; it may be async.

required

Raises:

Type Description
ValueError

When a streamed response has a part other than text, thinking or a tool call, which the stream cannot carry.

Respond

Answers a model request: pydantic-ai's FunctionDef, sync or async.

Live output

See Live output.

ArtifactDraft dataclass

ArtifactDraft(
    *,
    kind: str,
    snapshot: dict[str, Any],
    artifact_id: ArtifactId | None = None,
)

Bases: CustomEvent

A snapshot of an artifact that a tool is still generating.

Emit it from an application tool with await ctx.emit(ArtifactDraft(...)); it reaches live channels as a draft frame and is never stored.

forward_live

forward_live(
    channel: LiveChannel, *, coalesce: float = COALESCE
) -> EventStreamHandler

Return a pydantic-ai event_stream_handler that sends live frames to channel.

The run id comes from the run's Session. Text and thinking deltas of a part are gathered for coalesce seconds and sent as one, with the offset of the first, so a model that streams a token at a time doesn't send a frame a token; 0 sends each as it comes. Any other event sends what is gathered first, so frames keep the stream's order, and the stream's end sends the rest.

A delta's offset is where it starts in its part, in UTF-16 code units, as JavaScript indexes a string: it counts from 0 at each part_started, and a model response's parts are numbered from 0 again, so the offsets of one response's part 0 say nothing of another's. A client keeps each part's text and writes a delta at its offset, text[:offset] + delta, so one it is sent twice, as a run's buffered frames are on reconnect, lands once; a delta past the end of what it has, after a frame it was never sent, is appended; one without an offset, from an earlier server, is appended too.

to_live

to_live(event: AgentStreamEvent) -> list[LiveEvent]

Translate one pydantic-ai stream event into live events (often none).

LiveChannel

Bases: Protocol

Where a run's live frames go.

send async

send(frame: LiveFrame) -> None

Deliver one frame. Delivery is best-effort.

FanoutChannel

FanoutChannel(
    *, buffer: int = 1024, remember_closed: int = 10000
)

An in-process channel that fans each run's frames out to its watchers.

It keeps the frames of runs in progress, so a watcher that attaches mid-run first receives what the run has produced so far. Watchers that fall behind lose their oldest frames rather than slowing the run. A run's latest usage frame is kept apart as well, so a watcher that attaches after it left the buffer still learns the run's count.

Parameters:

Name Type Description Default
buffer int

How many frames each run keeps, and each watcher may fall behind.

1024
remember_closed int

How many ended runs to remember, so late watchers end at once.

10000

send async

send(frame: LiveFrame) -> None

Keep a frame for the run, and deliver it to the run's current watchers.

watch async

watch(run_id: RunId) -> AsyncIterator[LiveFrame]

Yield the run's frames so far, then new ones until close is called for it.

Watching a run that has already ended stops at once.

open

open(run_id: RunId) -> None

Take a run's frames again: a run that paused, and was closed, resumes under its id.

close

close(run_id: RunId) -> None

End every watcher of a run, and any that start watching it later, until it opens.

NullChannel

A channel that drops every frame, for headless runs.

send async

send(frame: LiveFrame) -> None

Drop the frame.

Tool helpers

The generic tools, and helpers for writing your own.

artifact_tools

artifact_tools(
    types: Sequence[type[Artifact]], *, ask: bool = False
) -> FunctionToolset[Session[Any]]

Build the generic toolset for the given artifact types.

Parameters:

Name Type Description Default
types Sequence[type[Artifact]]

The artifact types the agent may create; their JSON Schemas are described to the model once, so tool definitions never change between requests.

required
ask bool

Whether to include ask_user, which asks questions and pauses the run until someone answers them (ADR-0083). The agent's output_type must then include DeferredToolRequests.

False

describe_outcome

describe_outcome(outcome: Outcome) -> str

Tell a model what its command did, whatever the outcome.

submit async

submit(
    workspace: Workspace,
    change: EditArtifact | ArchiveArtifact | CreateArtifact,
    *,
    propose: bool = False,
    rationale: str | None = None,
) -> Applied | Proposed

Commit a change, or propose it for review when propose is set.

artifact_text

artifact_text(
    artifact: Versioned[Artifact],
    *,
    as_tool_result: bool = False,
) -> str

Render an artifact for a model: a header line, then its text.

Parameters:

Name Type Description Default
artifact Versioned[Artifact]

The artifact.

required
as_tool_result bool

Whether the text is an agent's tool result, which the gateway's guardrails read: its render_for_tool text rather than its render_for_agent.

False

list_artifacts_text async

list_artifacts_text(
    workspace: Workspace,
    kind: str | None = None,
    *,
    include_archived: bool = False,
) -> str

List a workspace's artifacts as text, one per line.

Parameters:

Name Type Description Default
workspace Workspace

The workspace to list.

required
kind str | None

Only list artifacts of this kind.

None
include_archived bool

List archived artifacts too, marked as archived.

False