artifactr.core¶
Pure rules for collaborating on artifacts: no I/O, no async (ADR-0001).
Hosts call needs to learn what to load, then commit or record to decide
a change, and persist the returned CommitResult. change_notes and
resume are pure projections over the log.
Artifacts¶
Artifact types, stored versions and the type registry. See Defining artifact types.
Artifact
pydantic-model
¶
Bases: BaseModel
Base class for artifact types.
Subclass it with ordinary Pydantic fields. Override render_for_agent to control
what the agent sees, and describe_change to summarize changes in your own words.
Config:
extra:forbidvalidate_assignment:True
kind
class-attribute
¶
kind: str
The registered type name, derived from the class name unless given as name=.
write_policy
class-attribute
¶
write_policy: WritePolicy = 'direct'
Whether agents change this type directly or through proposals.
render_for_agent
¶
render_for_agent() -> str
Return the text the agent sees for this artifact. Defaults to indented JSON.
render_for_tool
¶
render_for_tool() -> str
Return the text the read_artifact tool gives the agent for this artifact.
A tool's result is read by the gateway's prompt-injection guardrail, and stays in the
thread's history, which every later request carries; the agent's instructions, where
render_for_agent shows the artifacts it follows, are not. A type whose data holds
text an agent wrote that the guardrail's word lists can mistake for an attack, such as a
mini app's HTML, leaves that text out here. Defaults to render_for_agent.
describe_change
¶
Summarize the change from before to this state, or return None.
before is always an instance of the same type. Annotate it as Self when you
override this method; the base annotation is Any only so that overrides type-check.
When this returns None, the summary is generated from the patch.
MarkdownArtifact
pydantic-model
¶
Versioned
pydantic-model
¶
Bases: BaseModel
A stored artifact: its data plus identity, version and last author.
Config:
frozen:True
Fields:
-
id(ArtifactId) -
version(int) -
data(SerializeAsAny[A]) -
updated_by(Actor) -
archived(bool)
kind
property
¶
kind: str
The artifact's registered type name. Serialized, so readers can tell types apart.
edit
¶
edit(
change: Callable[[A], object],
*,
summary: str | None = None,
thread_id: ThreadId | None = None,
) -> EditArtifact
Build an edit command by mutating a copy of the data.
change receives a deep copy of the data and mutates it in place; its return value
is ignored. The difference becomes a JSON Patch based on this version.
edit_text
¶
edit_text(
old: str,
new: str,
*,
field: str = "text",
summary: str | None = None,
thread_id: ThreadId | None = None,
) -> EditArtifact
Build an edit command that replaces the unique occurrence of old with new.
archive
¶
archive(
*, thread_id: ThreadId | None = None
) -> ArchiveArtifact
Build a command that archives this artifact at this version.
WritePolicy
module-attribute
¶
WritePolicy = Literal['direct', 'propose']
How an artifact type accepts agents' changes: applied directly, or as proposals.
create_artifact
¶
create_artifact(
artifact: Artifact,
*,
artifact_id: ArtifactId | None = None,
thread_id: ThreadId | None = None,
) -> CreateArtifact
Build a command that creates artifact.
artifact_types
¶
Return a read-only view of every registered artifact type, by name.
get_artifact_type
¶
Return the artifact type registered under kind.
Raises:
| Type | Description |
|---|---|
NotFound
|
If no type is registered under that name. |
load_artifact
¶
Validate JSON data as an instance of the artifact type registered under kind.
Raises:
| Type | Description |
|---|---|
NotFound
|
If no type is registered under that name. |
ValidationFailed
|
If the data does not validate. |
load_versioned
¶
load_versioned(
*,
id: ArtifactId,
kind: str,
version: int,
data: Mapping[str, Any],
updated_by: Actor,
archived: bool = False,
) -> Versioned[Artifact]
Rebuild a stored artifact from its parts, validating the data against its type.
Actors¶
Who did something. See Opening a workspace.
Actor
module-attribute
¶
Actor = Annotated[
UserActor
| AgentActor
| ExternalAgentActor
| SystemActor
| EvaluatorActor,
Field(discriminator="kind"),
]
Any actor, discriminated by kind.
UserActor
pydantic-model
¶
Bases: BaseModel
A person, identified by the host application's user id.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
AgentActor
pydantic-model
¶
Bases: BaseModel
The built-in agent of one thread, acting within one run.
A run acts for whoever's message or answer started it: its on_behalf_of, which every
check sees. A run started by the system, or by another agent, acts for no one.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
-
kind(Literal['agent']) -
thread_id(ThreadId) -
run_id(RunId | None) -
name(str) -
on_behalf_of(UserActor | ExternalAgentActor | None)
on_behalf_of
pydantic-field
¶
on_behalf_of: UserActor | ExternalAgentActor | None = None
The person, or the person's client, the run acts for, if it acts for one.
ExternalAgentActor
pydantic-model
¶
Bases: BaseModel
An agent outside artifactr, connected over MCP.
A person who connects a client with their own credentials acts through it: their actor is
its on_behalf_of, and it is checked as them. A client with credentials of its own acts
for no one.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
-
kind(Literal['external_agent']) -
client_id(str) -
name(str | None) -
on_behalf_of(UserActor | None)
SystemActor
pydantic-model
¶
Bases: BaseModel
The application itself, for automated changes.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
EvaluatorActor
pydantic-model
¶
Bases: BaseModel
An evaluator: a judge or decision model whose verdicts are recorded as feedback.
Evaluators only give feedback; every other command from one is forbidden.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
is_agent
¶
Return whether the actor is an agent, built-in or external.
Agents are subject to artifact write policies; people and the system are not.
same_participant
¶
Return whether two actors are the same participant.
same_principal
¶
Return whether two actors act for the same person or client, or both for no one.
acting_for
¶
acting_for(
actor: Actor,
) -> UserActor | ExternalAgentActor | None
Return whom an actor's work is done for: a person, or a person's client.
A person and an MCP client act for themselves, an agent's run for its on_behalf_of,
and the system and evaluators for no one.
acts_as
¶
Return whether an actor is the same participant as other, or acts for it.
It looks through on_behalf_of: an agent's run for a person, and that person's own
client, both act as the person.
Commands¶
Intents to change a workspace. See Commands and outcomes.
Command
module-attribute
¶
Command = Annotated[
CreateArtifact
| EditArtifact
| ArchiveArtifact
| ProposeChange
| RespondToProposal
| CreateThread
| PostMessage
| SetFocus
| SetThreadMode
| AnswerDeferred
| GiveFeedback,
Field(discriminator="type"),
]
Any command, discriminated by type.
CreateArtifact
pydantic-model
¶
Bases: _Command
Create an artifact.
If the artifact type's write policy (or the thread's mode) requires an agent to propose,
the command is recorded as a proposal with proposal_id instead.
Fields:
-
type(Literal['create_artifact']) -
artifact_id(ArtifactId) -
kind(str) -
data(dict[str, JsonValue]) -
thread_id(ThreadId | None) -
proposal_id(ProposalId)
EditArtifact
pydantic-model
¶
Bases: _Command
Apply a patch to an artifact, based on a specific version.
If the artifact type's write policy (or the thread's mode) requires an agent to propose,
the command is recorded as a proposal with proposal_id instead.
Fields:
-
type(Literal['edit_artifact']) -
artifact_id(ArtifactId) -
base_version(int) -
patch(Patch) -
summary(str | None) -
thread_id(ThreadId | None) -
proposal_id(ProposalId)
ArchiveArtifact
pydantic-model
¶
Bases: _Command
Archive an artifact. Archived artifacts can be read but not changed.
Fields:
-
type(Literal['archive_artifact']) -
artifact_id(ArtifactId) -
base_version(int) -
thread_id(ThreadId | None) -
proposal_id(ProposalId)
ProposeChange
pydantic-model
¶
Bases: _Command
Propose a change for someone else to accept, whatever the write policy.
Fields:
-
type(Literal['propose_change']) -
proposal_id(ProposalId) -
change(ProposedChange) -
rationale(str | None)
ProposedChange
module-attribute
¶
ProposedChange = Annotated[
CreateArtifact | EditArtifact | ArchiveArtifact,
Field(discriminator="type"),
]
A change that a proposal would make when accepted.
RespondToProposal
pydantic-model
¶
Bases: _Command
Accept or reject a pending proposal.
changes is an optional patch applied on top of the proposed result when accepting, so a
person can accept a proposal with their own edits.
Fields:
-
type(Literal['respond_to_proposal']) -
proposal_id(ProposalId) -
decision(Literal['accept', 'reject']) -
changes(Patch | None) -
reason(str | None)
CreateThread
pydantic-model
¶
PostMessage
pydantic-model
¶
Bases: _Command
Post a message, or a notice, in a thread, attributed to the actor who commits it.
Fields:
-
type(Literal['post_message']) -
thread_id(ThreadId) -
message_id(MessageId) -
content(str) -
kind(MessageKind) -
model(str | None)
Validators:
-
_no_model_on_notice
model
pydantic-field
¶
model: str | None = None
The model to answer with, by the name the host's model_for knows (ADR-0097), or the
thread's default when None. It applies when this message starts a new turn: one that
joins a running turn, through its watcher, is answered by the turn's model. A notice
starts no turn, so it names none. A name is up to 128 letters, digits and ._:/@+-,
starting with a letter or digit, as gateways name models; the events that record it read
any string, as logs written before hold.
MessageKind
module-attribute
¶
MessageKind = Literal['message', 'notice']
What a message is for: the thread's agent acts on a message, while a notice informs
people and starts or steers no turn (ADR-0051).
SetFocus
pydantic-model
¶
Bases: _Command
Set the artifacts a thread is focused on.
Fields:
-
type(Literal['set_focus']) -
thread_id(ThreadId) -
artifact_ids(tuple[ArtifactId, ...])
SetThreadMode
pydantic-model
¶
Bases: _Command
Switch a thread between edit and suggest mode.
Fields:
-
type(Literal['set_thread_mode']) -
thread_id(ThreadId) -
mode(ThreadMode)
ThreadMode
module-attribute
¶
ThreadMode = Literal['edit', 'suggest']
How agents change artifacts in a thread: directly, or always through proposals.
AnswerDeferred
pydantic-model
¶
GiveFeedback
pydantic-model
¶
Bases: _Command
Give feedback of a registered type on an artifact version, a thread, a turn or a message.
value holds the feedback type's fields; core validates it against the type, checks the
type can be given on the target, and checks the target exists.
Fields:
-
type(Literal['give_feedback']) -
feedback_type(str) -
target(FeedbackTarget) -
value(dict[str, JsonValue])
Feedback¶
Typed feedback on artifacts, threads, turns and messages. See Evaluation.
Feedback
pydantic-model
¶
Bases: BaseModel
Base class for feedback types.
Subclass it with ordinary Pydantic fields, and declare the targets it applies to with
targets=. Field types decide how each field is scored in evaluation backends: bounded
numbers are numeric, bool is yes or no, Literal and Enum are categories, and
str is free text.
Config:
frozen:Trueextra:forbid
feedback_type
class-attribute
¶
feedback_type: str
The registered type name, derived from the class name unless given as name=.
targets
class-attribute
¶
targets: frozenset[TargetKind]
The kinds of target this type of feedback can be given on.
FeedbackTarget
¶
FeedbackTarget = Annotated[
ArtifactTarget
| ThreadTarget
| TurnTarget
| MessageTarget,
Field(discriminator=kind),
]
What a piece of feedback is about, discriminated by kind.
ArtifactTarget
pydantic-model
¶
Bases: BaseModel
Feedback on one version of an artifact.
Config:
frozen:Trueextra:forbidjson_schema_extra:tag_required
Fields:
-
kind(Literal['artifact']) -
artifact_id(ArtifactId) -
version(int)
ThreadTarget
pydantic-model
¶
TurnTarget
pydantic-model
¶
MessageTarget
pydantic-model
¶
Bases: BaseModel
Feedback on one message in a thread.
Messages live only in the log, so the target names the thread they were posted in, and,
for the agent's messages, the run that posted them (the run_id of its
message_posted), which links the feedback to the run's trace.
Config:
frozen:Trueextra:forbidjson_schema_extra:tag_required
Fields:
TargetKind
¶
TargetKind = Literal[
"artifact", "thread", "turn", "message"
]
What feedback can be about: an artifact version, a thread, a turn (a run) or a message.
TARGET_KINDS
module-attribute
¶
TARGET_KINDS: frozenset[TargetKind] = frozenset(
{"artifact", "thread", "turn", "message"}
)
Every kind of target.
feedback_types
¶
Return a read-only view of every registered feedback type, by name.
get_feedback_type
¶
Return the feedback type registered under a name.
Raises:
| Type | Description |
|---|---|
NotFound
|
If no feedback type is registered under that name. |
load_feedback
¶
load_feedback(
feedback_type: str,
target: ArtifactTarget
| ThreadTarget
| TurnTarget
| MessageTarget,
value: Mapping[str, Any],
) -> Feedback
Validate feedback of a registered type, given on a target.
Raises:
| Type | Description |
|---|---|
NotFound
|
If no feedback type is registered under that name. |
ValidationFailed
|
If the type cannot be given on that kind of target, or the value does not validate. |
Outcomes¶
What a command did.
Outcome
module-attribute
¶
What a command did, discriminated by type.
Applied
pydantic-model
¶
Bases: _Outcome
The change was applied: the artifact is now at version.
Fields:
-
seq(int | None) -
type(Literal['applied']) -
artifact_id(ArtifactId) -
version(int)
Proposed
pydantic-model
¶
Bases: _Outcome
The change was recorded as a proposal instead of being applied.
Fields:
-
seq(int | None) -
type(Literal['proposed']) -
proposal_id(ProposalId)
Resolved
pydantic-model
¶
Bases: _Outcome
A proposal was accepted (the artifact is now at version) or rejected.
Fields:
-
seq(int | None) -
type(Literal['resolved']) -
proposal_id(ProposalId) -
decision(Literal['accept', 'reject']) -
version(int | None)
Recorded
pydantic-model
¶
Bases: _Outcome
The command was recorded; it changed no artifact.
Fields:
Rejections¶
The ways a command can fail. See Rejections.
VersionConflict
¶
ValidationFailed
¶
NotFound
¶
AlreadyExists
¶
Bases: InvalidState
What a create names is there already: an id is used once.
Its type is invalid_state, as before, and it says why in reason, with what was there,
so a client tells a create sent again after a lost answer from any other refusal by its fields,
not its words.
Patches¶
The two ways artifact data changes. See How changes are expressed.
Patch
module-attribute
¶
Any patch, discriminated by kind.
JsonPatch
pydantic-model
¶
TextEdits
pydantic-model
¶
Bases: BaseModel
A sequence of anchored replacements in one text field.
Each old must occur exactly once in the field at the moment it is applied. An empty
old is allowed only when the field is empty, to write its first content.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
TextEdit
pydantic-model
¶
apply_patch
¶
Apply a patch to JSON data, returning new data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, JsonValue]
|
The artifact's current JSON data. It is not modified. |
required |
patch
|
Patch
|
The patch to apply. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, JsonValue]
|
The patched data. |
Raises:
| Type | Description |
|---|---|
PatchFailed
|
If the patch does not apply. |
diff
¶
Return the JSON Patch that turns old into new.
describe_patch
¶
Return a short, human-readable description of a patch.
Used as the change summary when neither the command nor the artifact type provides one.
Entities¶
Threads, proposals, revisions and runs, as stored.
Thread
pydantic-model
¶
Bases: BaseModel
A chat, with its mode and the artifacts it is focused on.
Config:
frozen:True
Fields:
-
id(ThreadId) -
title(str) -
mode(ThreadMode) -
focus(tuple[ArtifactId, ...])
Proposal
pydantic-model
¶
Bases: BaseModel
A change proposed by one participant for another to accept or reject.
Config:
frozen:True
Fields:
-
id(ProposalId) -
change(ProposedChange) -
proposed_by(Actor) -
rationale(str | None) -
status(Literal['pending', 'accepted', 'rejected']) -
thread_id(ThreadId | None)
artifact_id
property
¶
artifact_id: ArtifactId
The artifact the proposal creates, changes or archives.
A revision's at is when it was committed, its events' ts; one saved before revisions were dated has none.
Revision
pydantic-model
¶
Bases: BaseModel
One immutable version of an artifact (ADR-0004).
Config:
frozen:True
Fields:
Run
pydantic-model
¶
Bases: BaseModel
An agent run, which may pause for deferred requests and resume.
Config:
frozen:True
Fields:
-
id(RunId) -
thread_id(ThreadId) -
status(RunStatus) -
pending(tuple[DeferredRequest, ...]) -
answers(dict[str, DeferredAnswer]) -
trace_ids(tuple[TraceId, ...]) -
model(str | None)
trace_ids
pydantic-field
¶
The OpenTelemetry trace of each traced attempt, oldest first: a run that pauses and resumes runs once per attempt, each in its own trace.
RunStatus
module-attribute
¶
RunStatus = Literal[
"running", "paused", "completed", "stopped", "failed"
]
DeferredAnswer
pydantic-model
¶
Events¶
Facts on a workspace's log, and the envelope each travels in. See The log.
Envelope
pydantic-model
¶
Bases: BaseModel
A stored event with its position and attribution. Its shape is also the wire shape.
Fields:
Event
module-attribute
¶
Event = Annotated[
Annotated[ThreadCreated, Tag("thread_created")]
| Annotated[
ThreadModeChanged, Tag("thread_mode_changed")
]
| Annotated[FocusChanged, Tag("focus_changed")]
| Annotated[MessagePosted, Tag("message_posted")]
| Annotated[ArtifactCreated, Tag("artifact_created")]
| Annotated[ArtifactChanged, Tag("artifact_changed")]
| Annotated[ArtifactArchived, Tag("artifact_archived")]
| Annotated[ProposalCreated, Tag("proposal_created")]
| Annotated[ProposalResolved, Tag("proposal_resolved")]
| Annotated[RunStarted, Tag("run_started")]
| Annotated[ToolCalled, Tag("tool_called")]
| Annotated[ToolReturned, Tag("tool_returned")]
| Annotated[RunPaused, Tag("run_paused")]
| Annotated[DeferredAnswered, Tag("deferred_answered")]
| Annotated[RunEnded, Tag("run_ended")]
| Annotated[FeedbackGiven, Tag("feedback_given")]
| Annotated[AppEvent, Tag("app_event")]
| Annotated[UnknownEvent, Tag("unknown")],
Discriminator(_event_tag),
]
Any event, discriminated by type; unknown types validate as UnknownEvent.
KnownEvent
module-attribute
¶
KnownEvent = (
ThreadCreated
| ThreadModeChanged
| FocusChanged
| MessagePosted
| ArtifactCreated
| ArtifactChanged
| ArtifactArchived
| ProposalCreated
| ProposalResolved
| RunStarted
| ToolCalled
| ToolReturned
| RunPaused
| DeferredAnswered
| RunEnded
| FeedbackGiven
| AppEvent
)
Every event type this version defines.
UnknownEvent
pydantic-model
¶
ThreadCreated
pydantic-model
¶
ThreadModeChanged
pydantic-model
¶
Bases: _Event
A thread switched between edit and suggest mode.
Fields:
-
type(Literal['thread_mode_changed']) -
thread_id(ThreadId) -
mode(ThreadMode)
FocusChanged
pydantic-model
¶
Bases: _Event
The set of artifacts a thread is focused on changed.
Fields:
-
type(Literal['focus_changed']) -
thread_id(ThreadId) -
artifact_ids(tuple[ArtifactId, ...])
MessagePosted
pydantic-model
¶
Bases: _Event
A message, or a notice, was posted in a thread. Its author is the envelope's actor.
Fields:
ArtifactCreated
pydantic-model
¶
Bases: _Event
An artifact was created at version 1.
Fields:
-
type(Literal['artifact_created']) -
thread_id(ThreadId | None) -
run_id(RunId | None) -
artifact_id(ArtifactId) -
kind(str) -
version(int) -
data(dict[str, JsonValue]) -
proposal_id(ProposalId | None)
ArtifactChanged
pydantic-model
¶
Bases: _Event
An artifact was changed by a patch.
Fields:
-
type(Literal['artifact_changed']) -
thread_id(ThreadId | None) -
run_id(RunId | None) -
artifact_id(ArtifactId) -
kind(str) -
version(int) -
patch(Patch) -
summary(str) -
proposal_id(ProposalId | None)
ArtifactArchived
pydantic-model
¶
Bases: _Event
An artifact was archived.
Fields:
-
type(Literal['artifact_archived']) -
thread_id(ThreadId | None) -
run_id(RunId | None) -
artifact_id(ArtifactId) -
kind(str) -
version(int) -
proposal_id(ProposalId | None)
ProposalCreated
pydantic-model
¶
Bases: _Event
A change was proposed.
Fields:
-
type(Literal['proposal_created']) -
thread_id(ThreadId | None) -
run_id(RunId | None) -
proposal_id(ProposalId) -
change(ProposedChange) -
rationale(str | None)
ProposalResolved
pydantic-model
¶
Bases: _Event
A proposal was accepted or rejected.
Fields:
-
type(Literal['proposal_resolved']) -
thread_id(ThreadId | None) -
run_id(RunId | None) -
proposal_id(ProposalId) -
decision(Literal['accept', 'reject']) -
proposed_by(Actor) -
artifact_id(ArtifactId) -
changes(Patch | None) -
reason(str | None) -
version(int | None)
RunEvent
module-attribute
¶
RunEvent = (
RunStarted
| ToolCalled
| ToolReturned
| RunPaused
| RunEnded
)
Facts about agent runs, recorded by the agent layer rather than commanded.
RunStarted
pydantic-model
¶
Bases: _Event
An agent run started, or resumed after a pause.
Fields:
-
type(Literal['run_started']) -
run_id(RunId) -
thread_id(ThreadId) -
trigger(Literal['message', 'resume', 'api']) -
trace_id(TraceId | None) -
message_ids(tuple[MessageId, ...]) -
model(str | None)
trace_id
pydantic-field
¶
trace_id: TraceId | None = None
The OpenTelemetry trace this attempt runs in, when it is traced.
message_ids
pydantic-field
¶
The messages this start carries out, oldest first (ADR-0065): the one that starts the run, or the reply and the messages a resumed run takes as its prompt. Messages that reach the run later, through its watcher, are not named.
model
pydantic-field
¶
model: str | None = None
The model this attempt asked for, by the name the host's model_for knows (ADR-0097),
or None for the agent's own. A model its sender asked for and may not use is not named:
the run asks for the default, and a notice says so. Which model answered each request, as
when a gateway falls back to another, is each step's StepUsage.model.
ToolCalled
pydantic-model
¶
Bases: _Event
The agent called a tool.
Fields:
-
type(Literal['tool_called']) -
run_id(RunId) -
thread_id(ThreadId) -
tool_call_id(str) -
tool_name(str) -
args_summary(str) -
args_truncated(bool) -
artifact_id(ArtifactId | None)
args_truncated
pydantic-field
¶
args_truncated: bool = False
Whether args_summary was cut short, at the capability's limit.
artifact_id
pydantic-field
¶
artifact_id: ArtifactId | None = None
The artifact the call names, if its arguments name one: a reader who may not see it doesn't see the call.
ToolReturned
pydantic-model
¶
Bases: _Event
A tool call finished.
Fields:
-
type(Literal['tool_returned']) -
run_id(RunId) -
thread_id(ThreadId) -
tool_call_id(str) -
status(Literal['ok', 'error', 'retry']) -
summary(str) -
truncated(bool) -
tool_name(str) -
artifact_id(ArtifactId | None)
truncated
pydantic-field
¶
truncated: bool = False
Whether summary was cut short, at the capability's limit.
tool_name
pydantic-field
¶
tool_name: str = ''
The tool's name, as in its tool_called; empty in events from earlier versions.
artifact_id
pydantic-field
¶
artifact_id: ArtifactId | None = None
The artifact the call names, as in its tool_called: what it returned is as hidden.
RunPaused
pydantic-model
¶
DeferredRequest
pydantic-model
¶
Bases: BaseModel
A tool call a paused run is waiting on: a question to answer or a call to approve.
Config:
frozen:True
Fields:
-
tool_call_id(str) -
tool_name(str) -
kind(Literal['question', 'approval']) -
args(dict[str, JsonValue]) -
review(dict[str, JsonValue]) -
approval(str | None)
review
pydantic-field
¶
What the tool tells the person who answers, beside the call's arguments: for a connected app's code, the app, what running it means, and what a scan found in it (ADR-0085).
approval
pydantic-field
¶
approval: str | None = None
The id of the approval an approval waits on, in the application's store of approvals,
when lattice's enforcer asked it (lattice RFC-0011): it is answered there, and given back to
the call as the run resumes (ADR-0101). None for one artifactr's own tools asked.
DeferredAnswered
pydantic-model
¶
Bases: _Event
A paused run's request was answered.
Fields:
RunEnded
pydantic-model
¶
Bases: _Event
An agent run ended.
Fields:
RunUsage
pydantic-model
¶
Bases: BaseModel
Token and request counts for a run (ADR-0096).
Every field has a default, so an event recorded before a field was counted reads as 0,
None, or no steps.
Config:
frozen:True
Fields:
-
requests(int) -
input_tokens(int) -
output_tokens(int) -
cache_read_tokens(int) -
cache_write_tokens(int) -
reasoning_tokens(int) -
model(str | None) -
steps(tuple[StepUsage, ...])
cache_read_tokens
pydantic-field
¶
cache_read_tokens: int = 0
Of the input tokens, those read from the provider's prompt cache; 0 where the provider doesn't say, as in events recorded before it was counted.
cache_write_tokens
pydantic-field
¶
cache_write_tokens: int = 0
Of the input tokens, those written to the provider's prompt cache; 0 where it doesn't say.
reasoning_tokens
pydantic-field
¶
reasoning_tokens: int = 0
Of the output tokens, those the model spent reasoning; 0 where the provider doesn't say.
model
pydantic-field
¶
model: str | None = None
The model that answered the run's last request, as its response names it.
steps
pydantic-field
¶
steps: tuple[StepUsage, ...] = ()
Each model request of the run segment whose response ended, oldest first, the token sums
being theirs; for a run stopped or failed mid-request, then a last step without a model or a
duration for what pydantic-ai counted that no ended response did, which is no request of
its own, so there may be one more step than requests. A resumed run is a new segment:
its steps, and its run_ended's usage, count from its resumption. Empty in events from
earlier versions, and in a live usage frame's total, whose step comes beside it.
FeedbackGiven
pydantic-model
¶
Bases: _Event
A person or an evaluator gave feedback. Who gave it is the envelope's actor.
It is thread-scoped when its target belongs to a thread (a thread, a turn or a message), and workspace-scoped for an artifact version.
Fields:
AppEvent
pydantic-model
¶
scope_of
¶
scope_of(
event: KnownEvent,
) -> tuple[ThreadId | None, RunId | None]
Return the thread and run an event belongs to, for its envelope.
delivered_to
¶
delivered_to(
envelope: Envelope, threads: Collection[ThreadId] | None
) -> bool
Return whether a subscriber following threads receives envelope.
Workspace-scoped events (artifacts and proposals, whose types are in
WORKSPACE_SCOPED) reach every subscriber, whichever thread they originated in.
Thread-scoped events reach subscribers that follow their thread. None follows every
thread. Storage applies the same rule when it reads the log for some threads.
WORKSPACE_SCOPED
module-attribute
¶
WORKSPACE_SCOPED: Final = frozenset(
{
"artifact_created",
"artifact_changed",
"artifact_archived",
"proposal_created",
"proposal_resolved",
}
)
The types of the events every subscriber receives, whichever thread they originated in.
Rules¶
The host contract: what to load, and how a command or a fact is decided (ADR-0018). Workspace.commit and Workspace.record use these; call them directly only when you write a host of your own.
needs
¶
commit
¶
commit(
command: Command,
state: State,
*,
actor: Actor,
direct: frozenset[str] | None = None,
) -> CommitResult
Decide a command against the loaded state.
An agent's write is a proposal in a thread in Ask (suggest), and in Auto (edit)
unless its kind is in direct: the kinds whose agents' writes apply directly, which the
host resolves (ADR-0009). Without direct, they are the kinds whose write_policy is
"direct".
Returns:
| Type | Description |
|---|---|
CommitResult
|
What to persist, and the outcome to report. |
Raises:
| Type | Description |
|---|---|
Rejection
|
If the command cannot be applied; see |
NotLoaded
|
If |
record
¶
record(
fact: Fact, state: State, *, actor: Actor
) -> CommitResult
Decide a fact about an agent run, or an application event, against the loaded state.
Only the thread's own agent, or the system, may record facts about the thread's runs.
Raises:
| Type | Description |
|---|---|
Rejection
|
If the fact contradicts the run's state, such as a tool call after the run ended, or the actor may not record it. |
NotLoaded
|
If |
Fact
module-attribute
¶
A fact recorded by the agent layer rather than commanded.
NotLoaded
¶
Bases: LookupError
The host called a rule without loading an entity that needs asked for.
This is a bug in the host, not a rejection of the command.
State
dataclass
¶
State(
artifacts: Mapping[
ArtifactId, Versioned[Artifact] | None
] = _EMPTY,
proposals: Mapping[
ProposalId, Proposal | None
] = _EMPTY,
threads: Mapping[ThreadId, Thread | None] = _EMPTY,
runs: Mapping[RunId, Run | None] = _EMPTY,
messages: Mapping[MessageId, bool] = _EMPTY,
)
The slice of a workspace that core needs to decide one command.
Each mapping holds what the host loaded, keyed by id. A key whose value is None was
looked up and does not exist; a missing key was not loaded (see needs).
Needs
dataclass
¶
Needs(
artifacts: frozenset[ArtifactId] = frozenset(),
proposals: frozenset[ProposalId] = frozenset(),
threads: frozenset[ThreadId] = frozenset(),
runs: frozenset[RunId] = frozenset(),
messages: frozenset[MessageId] = frozenset(),
)
Ids a host must load into State before core can decide a command.
CommitResult
dataclass
¶
CommitResult(
outcome: Applied | Proposed | Resolved | Recorded,
events: tuple[KnownEvent, ...] = (),
artifacts: tuple[Versioned[Artifact], ...] = (),
revisions: tuple[Revision, ...] = (),
proposals: tuple[Proposal, ...] = (),
threads: tuple[Thread, ...] = (),
runs: tuple[Run, ...] = (),
messages: tuple[MessageId, ...] = (),
)
Everything a host persists after a command, in one transaction.
artifacts, proposals, threads and runs are entities to insert or replace;
revisions are appended; messages are message ids to record as used; events are
appended to the log in order.
Change notes¶
What others did, told to one viewer. See Change notes.
change_notes
¶
change_notes(
envelopes: Iterable[Envelope],
*,
viewer: Actor,
focus: Collection[ArtifactId] | None = None,
notices: bool = False,
) -> list[Note]
Return notes about what others did, in the order it happened.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
envelopes
|
Iterable[Envelope]
|
A slice of the log, in |
required |
viewer
|
Actor
|
Who the notes are for; their own actions are left out. |
required |
focus
|
Collection[ArtifactId] | None
|
The artifacts the viewer follows. |
None
|
notices
|
bool
|
Include the notices others posted in the viewer's thread, when the viewer is a thread's agent. |
False
|
Returns:
| Type | Description |
|---|---|
list[Note]
|
One |
list[Note]
|
relevant proposal event, and, with |
render_notes
¶
Render notes as a bulleted list, one line each.
ChangeNote
pydantic-model
¶
ProposalNote
pydantic-model
¶
Bases: BaseModel
A proposal made by someone else, or a decision on the viewer's own proposal.
Config:
frozen:True
Fields:
-
type(Literal['proposal']) -
proposal_id(ProposalId) -
artifact_id(ArtifactId) -
actor(str) -
action(Literal['proposed', 'accepted', 'rejected']) -
detail(str | None) -
version(int | None)
NoticeNote
pydantic-model
¶
Live events¶
A run's token-level output. See Live output.
LiveFrame
pydantic-model
¶
LiveEvent
module-attribute
¶
LiveEvent = Annotated[
PartStarted
| TextDelta
| ThinkingDelta
| ToolArgsDelta
| PartEnded
| Draft
| AppLive
| UsageUpdate,
Field(discriminator="type"),
]
Any live event, discriminated by type.
PartStarted
pydantic-model
¶
TextDelta
pydantic-model
¶
Bases: _LiveEvent
More text for a text part.
Fields:
offset
pydantic-field
¶
offset: int | None = None
Where delta starts in the part, in UTF-16 code units from the part's start, as
JavaScript indexes a string, when the sender counts: a client that is sent a delta again,
as a run's frames are replayed on reconnect, writes it where it belongs rather than
appending it twice; one past the end of what it has is appended. None from a sender
that doesn't count, as earlier versions didn't.
ThinkingDelta
pydantic-model
¶
ToolArgsDelta
pydantic-model
¶
PartEnded
pydantic-model
¶
Draft
pydantic-model
¶
Bases: _LiveEvent
A full snapshot of an artifact being generated, not yet committed.
Fields:
-
type(Literal['draft']) -
kind(str) -
data(dict[str, JsonValue]) -
artifact_id(ArtifactId | None)
AppLive
pydantic-model
¶
Protocol frames¶
The thread protocol's frames and its resume rule. See the thread protocol.
PROTOCOL
module-attribute
¶
PROTOCOL: Final = 'artifactr.v1'
The protocol version this library speaks.
Hello
pydantic-model
¶
Bases: BaseModel
The first frame a client sends on a connection.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
-
type(Literal['hello']) -
protocol(str) -
resume_after_seq(int) -
from_head(bool) -
threads(tuple[ThreadId, ...] | None) -
events(bool)
resume_after_seq
pydantic-field
¶
resume_after_seq: int = 0
The last seq the client has: everything after it is replayed.
from_head
pydantic-field
¶
from_head: bool = False
Start at the head of the log instead, replaying nothing. resume_after_seq must then
be 0; a client that reconnects resumes from welcome.head_seq with it.
threads
pydantic-field
¶
Thread-scoped events to receive; None means every thread.
Welcome
pydantic-model
¶
ActiveRun
pydantic-model
¶
Bases: BaseModel
A run in progress, as listed in welcome.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
-
run_id(RunId) -
thread_id(ThreadId) -
started_at(datetime | None)
EventFrame
pydantic-model
¶
Bases: Envelope
A durable event, delivered in its envelope.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
-
seq(int) -
id(str) -
ts(datetime) -
workspace_id(WorkspaceId) -
thread_id(ThreadId | None) -
run_id(RunId | None) -
actor(Actor) -
traceparent(str | None) -
event(Event) -
type(Literal['event'])
ReplayComplete
pydantic-model
¶
CommandFrame
pydantic-model
¶
Bases: BaseModel
A client's command, with an id that correlates it with its result.
command_id is also an idempotency key: the server deduplicates repeated ids.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
-
type(Literal['command']) -
command_id(str) -
command(FrameCommand)
FrameCommand
module-attribute
¶
FrameCommand = Annotated[
Command
| StopRun
| WatchRun
| WatchArtifact
| UnwatchArtifact,
Field(discriminator="type"),
]
Anything a client can ask for in a command frame.
StopRun
pydantic-model
¶
WatchRun
pydantic-model
¶
CommandResult
pydantic-model
¶
ErrorFrame
pydantic-model
¶
ClientFrame
module-attribute
¶
ClientFrame = Annotated[
Hello | CommandFrame | Presence,
Field(discriminator="type"),
]
Any frame a client sends.
ServerFrame
module-attribute
¶
ServerFrame = Annotated[
Welcome
| EventFrame
| ReplayComplete
| LiveFrame
| CommandResult
| ErrorFrame
| PeerPresence
| PeerLeft,
Field(discriminator="type"),
]
Any frame the server sends.
resume
¶
resume(
hello: Hello,
*,
head_seq: int,
first_retained_seq: int = 1,
) -> ResumePlan
Decide where replay starts for a connecting client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hello
|
Hello
|
The client's hello frame. |
required |
head_seq
|
int
|
The workspace log's latest |
required |
first_retained_seq
|
int
|
The oldest |
1
|
Raises:
| Type | Description |
|---|---|
UnsupportedProtocol
|
If the client speaks another protocol version. |
ValidationFailed
|
If the client asks to start at the head and to resume. |
ResumePlan
pydantic-model
¶
Bases: BaseModel
Where a connection's replay starts.
Config:
frozen:Truejson_schema_extra:tag_required
Fields:
-
replay_after(int) -
reset(bool)
Identifiers¶
Identifiers are plain strings. These aliases say what a string identifies, and the factories generate ids with a short type prefix.
TraceId
¶
TraceId = Annotated[
str, StringConstraints(pattern="^[0-9a-f]{32}$")
]
An OpenTelemetry trace id, as 32 lowercase hexadecimal digits.