The agent¶
artifactr plugs into pydantic-ai as one capability, ArtifactWorkspace (ADR-0006). An agent with it is a participant in a workspace: it reads and edits artifacts through tools, sees the artifacts it follows in its instructions, is told what others changed, and has everything it does recorded on the log. A Runner runs such an agent in threads, so a message behaves the same from every surface (ADR-0020).
Setting up the agent¶
from dataclasses import dataclass
from pydantic_ai import Agent
from artifactr import ArtifactWorkspace, Runner, Session
@dataclass
class AppDeps:
search: SearchClient # whatever your tools need
agent = Agent(
"anthropic:claude-sonnet-5-5",
deps_type=Session[AppDeps],
toolsets=[plan_tools], # your own tools
capabilities=[ArtifactWorkspace(types=[Plan, Brief])],
)
runner = Runner(agent, app=AppDeps(search=SearchClient()))
deps_type=Session[AppDeps]. The run's dependencies are aSession:workspace(a handle acting as this thread's agent),thread_id,run_id, andapp, your own dependencies. UseSession[None]if you have none.ArtifactWorkspace(types=...)lists the artifact types the agent may create.ask=Trueadds theask_usertool (see Pausing);max_render_chars(4,000) limits how much of each followed artifact goes into the instructions;max_summary_chars(2,000) limits how much of each tool call's arguments and result is recorded, which is what everyone who may read the thread sees of the call (0records none: a tool that reads what some readers may not see names it byartifact_id, so the call is hidden with it, and keeps secrets out of what it returns and raises, ADR-0084);notices=Truetells the agent about notices (see Notices).Runner(agent, app=...)passesappto every run asctx.deps.app. Its other options areagent_name(how the agent is named in the workspace,"assistant"by default),claim_ttl(how long a thread claim survives a dead process, 30 seconds),live(where live output goes; see Live output),liveness(how long a turn waits for a model, or a tool, that sends nothing before it fails the run; see A model that sends nothing),results(where commands' results are remembered, so a retried command is carried out once; see Serving) andmodel_for(the models a message may choose; see A model per message).
The capability composes with any other capabilities, toolsets, output types and model settings the agent has. A turn is an ordinary pydantic-ai run.
The generic tools¶
Every agent with the capability gets tools that work for any artifact type. Their definitions never change between requests, so the provider's prompt cache stays warm.
| Tool | What it does |
|---|---|
list_artifacts(kind=None) |
Lists the workspace's artifacts, with their kinds and versions |
read_artifact(artifact_id) |
Returns an artifact's current render_for_tool() text, which is its render_for_agent() text unless the type says otherwise (a mini app's leaves out its HTML), and follows it |
create_artifact(kind, data) |
Creates an artifact of one of the capability's types; the description includes each type's JSON Schema |
edit_text(artifact_id, old, new, field="text", summary=None, propose=False, rationale=None) |
Replaces one exact passage of a text field, or proposes the replacement |
archive_artifact(artifact_id) |
Archives an artifact |
ask_user(questions) |
Asks the people in the thread one to four questions with options, and pauses the run; only with ask=True |
Reading, creating or editing an artifact through these tools adds it to the thread's focus, so the agent hears about later changes to it.
Application tools¶
Structured edits belong in your own tools: add_task, set_status, move_section. They are plain pydantic-ai tools over RunContext[Session[AppDeps]], registered on the agent, not on the capability (ADR-0017):
from pydantic_ai import FunctionToolset, RunContext
from artifactr import Applied, Proposed, Session
plan_tools = FunctionToolset[Session[AppDeps]]()
@plan_tools.tool
async def add_task(ctx: RunContext[Session[AppDeps]], plan_id: str, title: str) -> str:
"""Add a task to a plan."""
plan = await ctx.deps.workspace.get(Plan, plan_id)
match await ctx.deps.workspace.commit(plan.edit(lambda p: p.add_task(title))):
case Applied(version=version):
return f"Added. The plan is now at version {version}."
case Proposed(proposal_id=proposal_id):
return f"Proposed adding the task ({proposal_id}); the user will review it."
- Commit through
ctx.deps.workspace. It acts as the agent (anAgentActorfor this thread and run), so every change is attributed to it, and write policies apply. - Do not catch rejections. The capability turns any
Rejectiona tool raises into a retry carrying the rejection's message, and for aVersionConflictadds "Read the artifact again, then retry." A tool may also raise pydantic-ai'sModelRetryitself, to ask the model to try again with better arguments. Other exceptions are recorded and fail the run. - Annotate the context literally as
RunContext[...]. pydantic-ai recognizes a tool that takes its context by that annotation, so a type alias would hide it. artifactr.agent.describe_outcome(outcome)gives the model a standard sentence for any outcome, andartifactr.agent.submit(workspace, change, propose=..., rationale=...)commits a change or proposes it, as the generic tools do.
Every tool call, yours included, is recorded as tool_called and tool_returned events, with clipped summaries of the arguments and result.
What the agent sees¶
The capability's instructions are rendered fresh from storage for every model request, so they are never stale, even within one run. They contain:
- a short introduction to working with shared artifacts
- a note that the thread is in suggest mode, when it is
- the kinds of artifact the agent can create
- every artifact the thread follows, as its
render_for_agent()text inside an<artifact id="..." kind="..." version="...">element - the agent's own proposals awaiting review
Change notes and steering¶
The agent is told what other participants did, as short notes in their own words (ADR-0008):
<workspace-changes>
- Alice changed plan_1 (plan, v7 → v8): completed Ship v1
- Alice rejected your proposal prp_3f9c2a1b7d4e5f60 for plan_1: not before the beta
</workspace-changes>
- When a run starts, the agent receives the notes it missed since the thread's history was last saved. Nothing is reported twice and nothing is skipped.
- While a run is in progress, a watcher follows the log. Others' changes to followed artifacts arrive as notes, and a new message in the thread arrives as-is. Both reach the model at its next request, so a person can steer a long run without stopping it. The watcher delivers messages only from the author the run acts for: it stops at the first from anyone else, which starts the next turn (One author per turn).
Notes cover the artifacts the thread follows, plus artifacts created in the thread. They leave out the agent's own changes, including those of its earlier runs: every run of one thread's agent is the same participant. They arrive as user-prompt parts, so they are stored in the model history with the rest of the conversation.
Notices¶
A notice is a message for the people in a thread rather than its agent, such as a rule saying it has gone live: a PostMessage of kind notice (ADR-0051). Whoever may post a message may post a notice.
from artifactr.core import ExternalAgentActor
rule = ws.as_actor(ExternalAgentActor(client_id="reflexr:timeline-entry", name="timeline-entry"))
await rule.post_message(thread.id, "The rule is live.", kind="notice")
- It starts no run, steers none and answers no paused run, from every surface:
Runner.executecommits it as it is, andrunner.sendposts messages only. - Clients can show it apart: its
message_postedhaskind: "notice". - Its
message_idis used once, as a message's is. - The agent is not told, so a notice stays out of the model history, unless the application asks with
ArtifactWorkspace(types=..., notices=True). The agent is then told of the notices others post in its thread as notes, when a run starts and while it runs:
Running the agent¶
runner.send(workspace, thread_id, content) posts a message as the handle's actor and acts on it. A message means one thing wherever it comes from:
| The thread is | The message |
|---|---|
| Idle | starts a run |
| Running | steers the running agent, which is told at its next request, if the run acts for its author; otherwise it is taken by the next turn |
| Ending, or pausing: its run no longer takes messages but still holds the thread | is taken by the next turn, which the run starts as it releases the thread |
| Paused on questions or approvals | is the reply: it answers the questions, declines the approvals with the message as the reason, and resumes the run |
| Paused on forms alone | waits: a form is answered only by its own answer, and the message reaches the run as the form's answer resumes it |
A message whose author may not start the thread's turn, as authorize says of the agent acting for them, is passed over rather than wedging the thread (ADR-0057), and people are told: the runner posts a notice in the thread, as the runner: "The last message got no reply: whoever sent it isn't allowed to start the assistant in this thread. Ask someone who can start the assistant to send it again." It says why in people's words, and logs the refusal at warning level with the action refused (ADR-0095). The notice is a notice, so it starts no turn and the agent is not told unless the capability asks for notices.
Behind the table is one rule: the log decides (ADR-0055). A thread's messages are taken in the log's order, each by one turn: as a run's prompt, as a paused run's reply, or through the watcher of the run that holds the thread. A message or an answer sent with the runner asks for a turn. Whoever holds the thread next, in any process, starts the turn with the oldest message no turn has taken, and its watcher delivers the rest. So a message sent the moment a client sees run_ended is answered, and each message is consumed once: in the same transaction as the run's start it prompts, the answer it replies with, or the end of the run it was delivered to. The one exception is a claim that lapses while its holder lives, as when a process stalls past claim_ttl. A message the stalled run was delivered, and could not record, may then be consumed again by the thread's next holder.
A message is a message, however it was committed. One committed without the runner, with ws.post_message, asks for nothing, so it starts no turn, but the thread's next turn takes it: as its prompt, or, in a paused thread, as its reply, if it is the oldest. Post anything that should not answer the agent or steer it as a notice, which is never a reply and starts nothing.
A thread from before this behaviour starts from where its workspace's log stood at the upgrade, which migrate records. The agent never suddenly answers messages from before it.
sent = await runner.send(ws, thread.id, "Break the launch into tasks.")
if sent.run is not None: # None when the thread's run takes the message, or will hand it over
result = await sent.run.wait()
send returns a Sent: the recorded message (outcome, whose run_id names the run) and the RunHandle it started or resumed, if any. RunHandle.wait() returns pydantic-ai's result when the run finishes or pauses. The run's reply is posted to the thread as a message_posted event by the agent.
sent.run is None when the message or answer started no run, which is not a failure:
- the thread's run is already active, in this process or another, so the message steers it; if that run is ending or pausing, 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, or the turn after it does, if this one is from another author
- an answer leaves some of the paused run's requests unanswered, so the run waits for them
- the paused run waits on a form, which a message doesn't answer, so the message waits too
The run send started may take an older message first: the thread's oldest message that no turn has taken.
A message in an idle thread, such as one just created, starts a run unless another starts one first. Code that owns its thread, such as a test or an evaluation, can assert that sent.run is set.
send takes a message_id. Sending a used one again raises InvalidState before anything else happens, so a retry never starts or steers a second turn (ADR-0045). send commits the message, then asks for the thread's turn; a process that stops between the two leaves the message waiting for the next turn. A retry that finds its id used asks with runner.ask(workspace, thread_id) instead, and the turn takes the message (ADR-0064).
| Runner method | What it does |
|---|---|
send(workspace, thread_id, content, message_id=None) |
Posts a message and starts, steers or resumes a run |
answer(workspace, AnswerDeferred(...)) |
Answers one request of a paused run, resuming it once all are answered |
ask(workspace, thread_id) |
Asks for the thread's next turn, for whatever its log has that no turn has taken, as send asks after its message; it does nothing when there is nothing to take |
resume(workspace, run_id) |
Asks for the thread's next turn, which resumes a paused run whose requests are answered; the oldest message not yet taken answers any left open |
stop(run_id) |
Cancels a run in this process; it ends with status stopped |
recover(workspace) |
Takes each turn the workspace's threads were asked for and no run has taken, as the application starts, and returns the runs it started |
drain() |
Waits until no run that has ended is still handing its thread over; aclose() cancels them instead |
aclose() |
Stops every run in this process, as the application shuts down; see Serving |
watch(run_id) |
Yields the run's live output; see Live output |
running(thread_id) |
This process's run in a thread, if any |
execute(workspace, command, command_id=...) |
Carries out any command the way every surface does, the first time its id is seen, and returns its command_result; a repeated id returns the first result |
One run is active per thread. The runner claims the thread with a lease in storage, renewed every third of claim_ttl while the run lasts, so the rule holds across processes. A renewal that fails is logged and retried, so a run survives one failed renewal, or storage that stalls for about two thirds of claim_ttl; keep it above the clock skew between replicas. A message sent while another process holds the claim steers that run instead of starting a second, or is taken by the turn that run hands the thread over to. Each claim has a holder of its own, so a run resuming cannot renew the claim its pausing segment still holds. Runs are asyncio tasks in the process that started them, so stop and watch reach only local runs.
A process that dies mid-run cannot record how its run ended, so the run stays running. Its claim lapses after claim_ttl, and the next run to claim the thread first records the one left behind as failed, with the error "the run was abandoned: its claim lapsed" and the reason abandoned, attributed to SystemActor(name="runner"). A run the runner starts holds its claim until it has recorded its end, so holding the claim means the other run's process is gone, or its claim lapsed. The abandoned turn is not resumed.
What the dead process was asked is not lost (ADR-0070). A runner the dead process's claim refused looks at the thread again a claim_ttl later, and again while the thread is claimed, until what was asked is taken. A process that died alone leaves no runner refused, so call runner.recover(workspace) for each of your workspaces as the application starts: it takes what each thread was asked for and not taken, looks again at a thread whose dead claim has not lapsed yet, and records each run the dead process left running as abandoned, once its thread can be claimed, looking again once a look_again_after later if the dead claim still held it, so no client is told it is active until someone posts in its thread (ADR-0095); stackr's template calls it the first time each workspace opens in a process. A message the dead run's watcher had given its model was not recorded as taken, so the thread's next turn gives it to the model again: steering is delivered at least once (ADR-0055's amendment of 2026-10-17).
A run whose process lives on loses its claim if no renewal succeeds for a whole claim_ttl, even while a renewal hangs, and the runner then cancels it, before another run can claim the thread. If the thread's next run records it as abandoned first, as when its process cannot reach storage to record that it stopped, a tool call it makes is refused, and fails it; the end of a tool already running, and the run's own end, are dropped and logged, so its abandonment is the only end it has.
A runner's evaluators judge each turn as it ends, in the background, and record their verdicts as feedback; see Online evaluation.
One author per turn¶
A run acts for the person, or the person's MCP client, whose message or answer started it: its agent's AgentActor.on_behalf_of, which Session.on_behalf_of reads and every authorize check sees (ADR-0057). The log records it on every write of the run, starting with run_started. A run started by the system, or by another agent, acts for no one.
So a turn takes messages only up to the first from another author, whose messages start the next turn. A paused run resumed by answers acts for whoever answered it last, and the messages waiting for it join it only up to the first from someone else. One person's message never rides on another's rights, and a person cannot accept their own proposal through a run acting for them.
The runner's own work, claiming the thread and keeping its place in the log, acts as SystemActor(name="runner"), so authorize hears it apart from the person.
Starting a turn asks artifactr:record as the agent acting for its author. send asks it before posting, and raises Forbidden if the sender may not start a turn. A message that reached the thread otherwise, or a reply its author may not give, is passed over: the runner takes the log past it, records nothing for it, and runs the next turn, so it never wedges the thread; a paused run whose resume is refused ends as failed, with the reason forbidden.
A model per message¶
A message may name the model that answers it: PostMessage.model, or runner.send(..., model="fast"). The runner asks the application for it by name, through model_for, a function from a name to a pydantic-ai Model that raises LookupError for a name it doesn't know (ADR-0097):
from pydantic_ai.models.openai import OpenAIChatModel
models = {name: OpenAIChatModel(name, provider=gateway) for name in ("default", "fast", "local")}
runner = Runner(agent, app=deps, model_for=models.__getitem__)
The runner calls model_for as each turn starts, so build each model once and keep it, as the dict does. Keep it a closed list of the models you offer: a function that builds a model from whatever name it is given lets anyone who may choose use any model your gateway serves. A name is up to 128 letters, digits and ._:/@+-, starting with a letter or digit. Without model_for, every turn answers with the agent's own model, as before.
- A turn answers with the model its first message names, or with the agent's own when it names none. A message that joins a running turn, through its watcher, is answered by the turn's model, with no notice: the model applies when the message starts a new turn. A client shows this beside its picker, or disables the picker while a run is active.
- A resumed run answers with the model its reply names, or else the one the run last asked for (
Run.model). - Who may choose. The turn asks
artifactr:use_modelas its agent acting for its author, with the model's name inAccess.model. grantr'seditorholds it for every model. - Never silent. A model its author may not use, one
model_fordoesn't know or fails to set up (the failure is logged), or any model where there is nomodel_for, is not refused: the turn answers with the agent's own, and the runner posts a notice that says which model was asked for, that the default is answering instead, and what to do. - Which model answered.
run_started.modelis the model the turn asked for,Nonefor the agent's own; each step of the run's usage names the model that answered, which a gateway that falls back to another reports (Token counts).
Running without a runner¶
The capability works in any pydantic-ai run. Build the session with Session.start and pass the thread's history yourself:
from artifactr.agent import load_history
result = await agent.run(
"Summarize the plan's open tasks.",
deps=Session.start(ws, thread.id, app=deps),
message_history=await load_history(ws, thread.id),
)
Pass Session.start(..., on_behalf_of=user) for a run that acts for a person; without it, the run acts for no one, and its watcher stops at the first message a person posts. The run is recorded the same way (with trigger api) and its history is saved. The prompt itself is not posted to the thread; post it with ws.post_message first if people should see it. A direct run takes no claim: nothing stops two in one thread at once, and a runner that claims the thread meanwhile records the direct run as abandoned. A direct run a runner has recorded as abandoned returns normally if it ends without calling another tool, but its end and history are dropped. If a runner also serves the thread, hold the claim around the run: async with ws.claim_thread(thread_id, holder=...) as lost:, and stop the run if the event lost is set, as the runner does.
What is recorded¶
A run's record is on the log, attributed to the agent:
run_started trigger: message, resume or api; the trace id when the run is traced;
the ids of the messages its start carries out
tool_called for every tool call, the application's included
artifact_changed (or proposal_created, artifact_created, ...) for each change a tool commits
tool_returned the tool's name, and status: ok, retry (a rejection or the tool's own
ModelRetry) or error
message_posted the agent's reply
run_ended status: completed, stopped or failed, with the token usage so far, and for
a failure the error, and a reason when a RunFailure said why
A run that pauses ends its segment with run_paused instead, listing the requests it waits on, with the usage so far. A tool or capability that fails the run for a known reason raises RunFailure(message, reason="..."): the run is recorded as failed with that reason, which clients and dashboards can count on (ADR-0042). The LLM gateway uses it for guardrail blocks, and the runner for a model or a tool that sends nothing for its wait, model_stalled and tool_stalled (Live output). The runner itself records the reason abandoned, as the system, for a run whose claim lapsed before it ended (see Running the agent). A stopped or failed run's usage is what it used so far; an abandoned run's went with its process, so it has none. The run's new model messages are stored in the same transaction as run_ended or run_paused, so the history and the log never disagree.
Proposals¶
An agent proposes instead of applying a change when:
- the artifact type's
write_policyis"propose", or, withWorkspaces(direct_writes=...), the workspace'sagent-writes:directsetting doesn't name its kind - the thread is in suggest mode (
SetThreadMode(thread_id=..., mode="suggest")) - it asks to, with
edit_text(..., propose=True, rationale=...)or, in your tools,submit(workspace, change, propose=True)
Proposals do not block the run (ADR-0009). The agent is told its change was proposed and carries on. A person accepts, edits or rejects the proposal from any surface, whenever they like, and the decision reaches the agent as a change note. When a proposal is accepted with edits, the note describes the person's changes. The agent's proposals awaiting review are listed in its instructions.
Pausing for people¶
Some points need a person before the agent can continue: a question only they can answer, or an action that needs approval. These use pydantic-ai's deferred tools (ADR-0010):
ask_user, added byArtifactWorkspace(..., ask=True), asks one to four questions, each with a shortheaderand two to four options (alabel, adescription, andrecommendedon the one the agent would choose), one choice ormultiple, and, where it setsother, an answer in the person's own words (ADR-0083). Any tool that raisesCallDeferredpauses the same way.- A tool declared with
requires_approval=Trueneeds approval before it runs.
The agent's output_type must include DeferredToolRequests:
from pydantic_ai import Agent, DeferredToolRequests, FunctionToolset, RunContext
release_tools = FunctionToolset[Session[None]]()
@release_tools.tool(requires_approval=True)
async def publish(ctx: RunContext[Session[None]], channel: str) -> str:
"""Publish the release notes to a channel."""
return f"Published to {channel}."
agent = Agent(
"anthropic:claude-sonnet-5-5",
deps_type=Session[None],
output_type=[str, DeferredToolRequests],
toolsets=[release_tools],
capabilities=[ArtifactWorkspace(types=[ReleaseNotes], ask=True)],
)
When the model asks a question or calls publish, the run ends with a run_paused event listing each request (tool_call_id, tool_name, kind of question or approval, and args). Nothing waits in memory, so a pause survives restarts. Answers arrive as AnswerDeferred commands, from any surface:
from artifactr.core import AnswerDeferred
run = await ws.run(run_id)
for request in run.pending:
if request.kind == "question": # ask_user's: one answer per question it asked
answer = {"answers": [{"selected": ["Monday"]}]}
command = AnswerDeferred(run_id=run.id, tool_call_id=request.tool_call_id, answer=answer)
else:
command = AnswerDeferred(run_id=run.id, tool_call_id=request.tool_call_id, approved=True)
answered = await runner.answer(ws, command) # resumes the run after the last answer
An answer to ask_user is {"answers": [...]}, one {"selected": [labels], "other": words} per question, in order, or {"reply": words}, which answers them all in words; core refuses one that doesn't fit the questions as validation_failed, at ["answers", n]. The agent reads each question beside its answer: [{"question": ..., "selected": [...], "other": ...}], or the reply.
Once every request is answered, the run resumes under the same run_id, with the answers passed to pydantic-ai as deferred tool results; an approved call runs then. A chat message sent to a paused thread is the reply, ask_user's as {"reply": text}, as described above, so the model history never ends in an unanswered tool call. A form, the ask_form tool of artifactr's forms, is the exception: only its own answer answers it, so a reply leaves it open and the run paused, and a message posted while only forms are open is not taken until the form's answer resumes the run, which it joins (ADR-0055's amendment).
Each deferred_answered names the tool whose call it answers, tool_name, so whatever reads the log tells a form's answer from a question's or an approval's. An application may refuse an answer before it is recorded, with a check of answer_deferred (Checks); the request stays open, and the run paused.