Skip to content

artifactr.workspace

Tenant-scoped workspaces over pluggable storage.

Open a Workspace with Workspaces.open; every read and write goes through it, each asks the application's authorize hook, every read leaves out what its hidden hook hides, every command passes the application's checks, and every write runs core's rules in one storage transaction.

Workspaces

Tenant-scoped handles. See Workspaces, commits and the log.

Workspaces

Workspaces(
    storage: Storage,
    *,
    types: Iterable[type[Artifact]] | None = None,
    checks: Mapping[str, Check] | None = None,
    authorize: Authorize | None = None,
    on_open: OnOpen | None = None,
    hidden: Hidden | None = None,
    gate: Gate | None = None,
    direct_writes: DirectWrites | None = None,
    hidden_refresh: timedelta = timedelta(seconds=30),
    tracer_provider: TracerProvider | None = None,
    meter_provider: MeterProvider | None = None,
)

Opens scoped Workspace handles over one storage.

Parameters:

Name Type Description Default
storage Storage

Where workspaces are kept.

required
types Iterable[type[Artifact]] | None

The artifact types this application accepts. Others are rejected even if they are registered, so clients cannot create arbitrary types. None accepts every registered type.

None
checks Mapping[str, Check] | None

The application's checks of commands, by command type, each called before a command of that type commits; none if omitted.

None
authorize Authorize | None

Whether an actor may take an action, asked by every handle in each of its methods; allows everything if omitted.

None
on_open OnOpen | None

Called each time a workspace is opened, once authorize allows it.

None
hidden Hidden | None

The threads and artifacts an actor may not see, which every read leaves out; hides nothing if omitted.

None
gate Gate | None

Refuses a command while an integration it needs is off, before authorize hears it; gates nothing if omitted.

None
direct_writes DirectWrites | None

The kinds whose agents' writes apply directly in a thread in Auto, in a workspace, asked on each agent's write (ADR-0009); without it, those whose write_policy is "direct". Give it direct_writes_from.

None
hidden_refresh timedelta

How often an open subscription asks hidden again.

timedelta(seconds=30)
tracer_provider TracerProvider | None

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

None
meter_provider MeterProvider | None

Where artifactr's metrics go. Defaults to the global meter provider.

None

open async

open(
    tenant_id: TenantId,
    workspace_id: WorkspaceId,
    *,
    actor: Actor,
) -> Workspace

Return a handle on a tenant's workspace, acting as actor.

This is the only place a tenant id enters; nothing on the handle can reach another tenant. Opening asks authorize for artifactr:open, then calls on_open.

Raises:

Type Description
Forbidden

If authorize refuses the actor this workspace.

list async

list(
    tenant_id: TenantId,
    *,
    actor: Actor,
    after: WorkspaceId | None = None,
    limit: int = 100,
) -> list[WorkspaceId]

Return a page of the tenant's workspaces that actor may open, ordered by id.

A workspace is listed once its log has an event. Listing spans the tenant, so it asks authorize for artifactr:read_workspaces with no workspace, then for artifactr:open in each workspace it finds, and leaves out those refused (ADR-0058). It opens none of them, so on_open is not called. A page is full unless the list has ended; pass its last id as after for the next.

Raises:

Type Description
Forbidden

If authorize refuses the actor the list.

ValidationFailed

If limit is below 1.

Workspace

Workspace(context: _Context, scope: Scope, actor: Actor)

A handle on one tenant's workspace, bound to the actor it acts as.

Create handles with Workspaces.open, and derive handles for other actors (such as the agent) with as_actor. Each method asks the authorize hook first, as the handle's actor, with the action it takes; a refusal raises Forbidden.

tenant_id property

tenant_id: TenantId

The id of the tenant the workspace belongs to.

workspace_id property

workspace_id: WorkspaceId

The workspace's id.

actor property

actor: Actor

Who this handle acts as.

as_actor

as_actor(actor: Actor) -> Workspace

Return a handle on the same workspace that acts as actor, checked as it.

check async

check(access: Access) -> None

Ask authorize whether this handle's actor may take an action here.

Every method asks it first. A surface asks it itself only for what it does beside the workspace, as the runner does to stop a run.

Raises:

Type Description
NotFound

If the access names a thread or artifact hidden from the actor, as if it were missing, so ids can't be probed.

Forbidden

If authorize refuses it.

hidden async

hidden() -> Hides

What this handle's actor may not see here: nothing without a hidden hook.

The handle asks the hook once every hidden_refresh at most, so a request asks it once; a handle from as_actor asks afresh.

commit async

commit(command: ProposeChange) -> Proposed
commit(command: RespondToProposal) -> Resolved
commit(
    command: CreateThread
    | PostMessage
    | SetFocus
    | SetThreadMode
    | AnswerDeferred
    | GiveFeedback,
    *,
    cursor: tuple[str, int] | None = None,
    claim: tuple[ThreadId, str] | None = None,
) -> Recorded
commit(
    command: Command,
    *,
    cursor: tuple[str, int] | None = None,
    claim: tuple[ThreadId, str] | None = None,
) -> Outcome

Submit a command.

Parameters:

Name Type Description Default
command Command

The command.

required
cursor tuple[str, int] | None

A named cursor, (name, seq), to save in the same transaction, as with save_cursor: it moves only if the command is applied.

None
claim tuple[ThreadId, str] | None

A thread's claim, (thread_id, holder), that fences the command: it is applied only while holder has the thread (claim_thread).

None

Returns:

Type Description
Outcome

What the command did, with the seq of the last event it appended.

Raises:

Type Description
Rejection

If the command cannot be applied; ThreadBusy, a rejection too, if claim is given and its holder no longer has the thread.

record async

record(
    fact: Fact,
    *,
    history: bytes | None = None,
    cursor: tuple[str, int] | None = None,
    claim: tuple[ThreadId, str] | None = None,
) -> Recorded

Record a fact about an agent run, or an application event.

Parameters:

Name Type Description Default
fact Fact

The fact to record.

required
history bytes | None

Serialized model messages to append to the fact's thread history in the same transaction, typically with RunPaused or RunEnded.

None
cursor tuple[str, int] | None

A named cursor, (name, seq), to save in the same transaction, as with save_cursor: it moves only if the fact is recorded.

None
claim tuple[ThreadId, str] | None

A thread's claim, (thread_id, holder), that fences the fact: it is recorded only while holder has the thread (claim_thread).

None

Raises:

Type Description
ThreadBusy

If claim is given and its holder no longer has the thread.

create async

create(
    artifact: Artifact,
    *,
    artifact_id: ArtifactId | None = None,
    thread_id: ThreadId | None = None,
) -> Applied | Proposed

Create an artifact from an instance of its type.

create_thread async

create_thread(title: str = '') -> Thread

Create a thread and return it.

post_message async

post_message(
    thread_id: ThreadId,
    content: str,
    *,
    message_id: MessageId | None = None,
    kind: MessageKind = "message",
) -> Recorded

Post a message, or a notice, in a thread as this handle's actor.

Parameters:

Name Type Description Default
thread_id ThreadId

The thread to post in.

required
content str

What the message says.

required
message_id MessageId | None

The message's id; a new one when omitted. An id already used in the workspace is refused with InvalidState.

None
kind MessageKind

notice for a notice, which is for people and starts no run (ADR-0051).

'message'

get async

get(
    artifact_type: type[A], artifact_id: ArtifactId
) -> Versioned[A]

Return an artifact's current version, checked to be of artifact_type.

Raises:

Type Description
NotFound

If there is no such artifact of that type.

watch async

watch(artifact_id: ArtifactId) -> Literal['view', 'edit']

Check that this handle's actor may watch an artifact live, and say what they may do.

A watch is a read: a hidden artifact is missing, as everywhere. While an integration that governs it is off, the gate refuses it as it would an edit that changes nothing, so presence ends with the integration (lattice RFC-0006, ADR-0093).

Raises:

Type Description
NotFound

If there is no such artifact, or it is hidden from the actor.

Forbidden

If the actor may not read artifacts.

NotEnabled

If an integration it needs is off.

artifact async

artifact(artifact_id: ArtifactId) -> Versioned[Artifact]

Return an artifact's current version, whatever its type.

Raises:

Type Description
NotFound

If there is no such artifact.

artifacts async

artifacts(
    artifact_type: type[A] = Artifact,
    *,
    kind: str | None = None,
    include_archived: bool = False,
) -> list[Versioned[A]]

Return current artifacts that are instances of artifact_type, oldest first.

Parameters:

Name Type Description Default
artifact_type type[A]

Only artifacts of this type, or a subclass of it.

Artifact
kind str | None

Only artifacts registered under this kind.

None
include_archived bool

Archived artifacts too.

False

revisions async

revisions(artifact_id: ArtifactId) -> list[Revision]

Return an artifact's revisions, oldest first.

Raises:

Type Description
NotFound

If there is no such artifact: every artifact has a revision.

thread async

thread(thread_id: ThreadId) -> Thread

Return a thread.

Raises:

Type Description
NotFound

If there is no such thread.

threads async

threads() -> list[Thread]

Return every thread, oldest first.

proposal async

proposal(proposal_id: ProposalId) -> Proposal

Return a proposal.

Raises:

Type Description
NotFound

If there is no such proposal.

proposals async

proposals(
    *,
    status: Literal["pending", "accepted", "rejected"]
    | None = "pending",
) -> list[Proposal]

Return proposals with a status (pending by default; None for all), oldest first.

run async

run(run_id: RunId) -> Run

Return a run.

Raises:

Type Description
NotFound

If there is no such run.

runs async

runs(
    *,
    thread_id: ThreadId | None = None,
    status: RunStatus | None = None,
) -> list[Run]

Return runs, optionally of one thread and with one status, oldest first.

A hidden thread has none, as one that doesn't exist has none.

history async

history(thread_id: ThreadId) -> Sequence[HistoryChunk]

Return a thread's history: serialized model messages, one chunk per run segment.

A hidden thread has none, as one that doesn't exist has none.

head_seq async

head_seq() -> int

Return the log's latest seq, or 0 if it is empty.

read async

read(
    *,
    after_seq: int = 0,
    before_seq: int | None = None,
    threads: Collection[ThreadId] | None = None,
    limit: int | None = None,
    last: int | None = None,
) -> list[Envelope]

Return logged envelopes in the window after_seq < seq < before_seq, in order.

Parameters:

Name Type Description Default
after_seq int

Only envelopes after this seq.

0
before_seq int | None

Only envelopes before this seq; None reads to the head.

None
threads Collection[ThreadId] | None

Only thread-scoped events from these threads; workspace-scoped events (artifacts, proposals) are always included. None includes every thread.

None
limit int | None

At most this many: the first ones in the window that match.

None
last int | None

At most this many: the last ones in the window that match, still in order. To page backwards, read last=n, then last=n before the oldest seq returned.

None

Raises:

Type Description
ValidationFailed

If both limit and last are given, or a number is negative or more than storage holds.

subscribe async

subscribe(
    *,
    after_seq: int = 0,
    threads: Collection[ThreadId] | None = None,
) -> AsyncIterator[Envelope]

Yield envelopes after after_seq: the stored ones, then new ones as they commit.

Replay and live delivery are the same stream, so nothing falls between them. Reading the log is untraced, so a subscription that polls storage makes no trace per poll (ADR-0046); what the subscriber does with each envelope is traced as usual.

It leaves out what hidden hides from the actor, asking it again every hidden_refresh, so an item restricted while it is open is left out from then on.

change_notes async

change_notes(
    *,
    after_seq: int,
    before_seq: int | None = None,
    focus: Collection[ArtifactId] | None = None,
    viewer: Actor | None = None,
    notices: bool = False,
) -> list[Note]

Return notes about what others did in the window after_seq < seq < before_seq.

Parameters:

Name Type Description Default
after_seq int

Only consider envelopes with a greater seq.

required
before_seq int | None

Only consider envelopes with a lesser seq; None reads to the head.

None
focus Collection[ArtifactId] | None

The artifacts the viewer follows; None means all.

None
viewer Actor | None

Who the notes are for; defaults to this handle's actor.

None
notices bool

Include the notices others posted in the viewer's thread, when the viewer is a thread's agent.

False

cursor async

cursor(name: str) -> int

Return how far a named consumer of the log has got: the seq it saved, or 0.

A consumer, such as a feedback mirror, saves its cursor with save_cursor and carries on after it when it starts again.

save_cursor async

save_cursor(name: str, seq: int) -> None

Save how far a named consumer of the log has got: it is done with seq.

A cursor only moves forward: saving a seq below the saved one leaves it, so a consumer that runs in several processes, each at its own pace, cannot move it back.

lease_artifact async

lease_artifact(
    artifact_id: ArtifactId, *, holder: str, ttl: timedelta
) -> ArtifactLease

Take or renew an artifact's lease, which one holder has at a time (ADR-0071).

The same holder taking it again renews it, for ttl from now. Another holder may take it once it has expired. Nothing renews it in the background. The lease is advisory: core doesn't know it, so no command is refused for it, and a holder's writes are guarded by their base version and a JSON Patch test, as anyone's are. It asks artifactr:edit_artifact about the artifact.

A call cut short may still have taken or renewed the lease, as with claim_thread; a holder that took it for the first time releases it.

Raises:

Type Description
NotFound

If there is no such artifact, or it is hidden from the actor.

ArtifactBusy

If another holder has it.

ValidationFailed

If ttl is not positive.

artifact_lease async

artifact_lease(
    artifact_id: ArtifactId,
) -> ArtifactLease | None

Return an artifact's lease, or None if no one holds it now.

It is a read, which asks artifactr:read_artifacts: viewers see who has the artifact.

Raises:

Type Description
NotFound

If there is no such artifact, or it is hidden from the actor.

release_artifact async

release_artifact(
    artifact_id: ArtifactId, *, holder: str
) -> None

Release an artifact's lease if holder has it. It asks artifactr:edit_artifact.

Raises:

Type Description
NotFound

If there is no such artifact, or it is hidden from the actor.

claim_thread async

claim_thread(
    thread_id: ThreadId,
    *,
    holder: str,
    ttl: timedelta = timedelta(seconds=30),
) -> AsyncGenerator[Event]

Hold a thread exclusively, renewing the claim until the block exits.

One run is active per thread. The claim is a lease in storage, so it holds across processes and lapses by itself if the holder dies. A call cancelled, or failing, as it claims releases the lease, which storage may have granted all the same.

Yields:

Type Description
AsyncGenerator[Event]

An event set once the claim is lost, as storage says: a renewal found that another

AsyncGenerator[Event]

holder has the thread, or no one has it, or a renewal still in flight a whole

AsyncGenerator[Event]

ttl after it began, or one that raised once the claim was due to lapse, left it

AsyncGenerator[Event]

unknown. A ttl after its last renewal began, with no renewal in flight, as when

AsyncGenerator[Event]

the event loop stalled, the claim is renewed at once, and only if no one else has

AsyncGenerator[Event]

had it meanwhile (renew_lease): so a holder

AsyncGenerator[Event]

whose loop stalled keeps its claim, and its run, unless storage gave it to another.

AsyncGenerator[Event]

The claim is never renewed once lost, even if storage would allow it. Its lease is

AsyncGenerator[Event]

released only when the block exits, so exit promptly once the event is set.

Raises:

Type Description
ThreadBusy

If another holder has the thread.

ThreadBusy

ThreadBusy(message: str)

Bases: InvalidState

Another run holds the thread.

ArtifactLease dataclass

ArtifactLease(
    artifact_id: ArtifactId,
    holder: str,
    expires_at: datetime,
)

A lease on an artifact: who holds it, and until when (ADR-0071).

ArtifactBusy

ArtifactBusy(
    artifact_id: ArtifactId, lease: ArtifactLease | None
)

Bases: InvalidState

Another holder has the artifact's lease (ADR-0071).

Attributes:

Name Type Description
lease

The lease that refused it, so a caller can say who has the artifact, or None if it ended between the refusal and the read: then the artifact may be free already.

Authorize module-attribute

Authorize = Callable[
    [TenantId, WorkspaceId | None, Actor, Access],
    Awaitable[bool],
]

Decides whether an actor may take an action in a workspace of its tenant.

Workspaces holds it, and every Workspace it opens asks it in each method, before anything is read or written: so every REST request, WebSocket command, MCP tool call and in-process call is checked alike. A refusal raises Forbidden. The workspace is None only for listing a tenant's workspaces, which spans the tenant.

Access pydantic-model

Bases: BaseModel

What an actor is about to do in a workspace, as authorize hears it.

Config:

  • frozen: True

Fields:

action pydantic-field

action: str

One of ACTIONS.

thread_id pydantic-field

thread_id: ThreadId | None = None

The thread it is about, when it names one.

artifact_id pydantic-field

artifact_id: ArtifactId | None = None

The artifact it is about, when it names one.

model pydantic-field

model: str | None = None

The model it is about: artifactr:use_model's, the name a message asked to answer with (ADR-0097). It is not a workspace item, so an authorize that scopes by item, as grantr's does, asks it of the thread; one that limits models reads it here.

ACTIONS module-attribute

ACTIONS: Final = frozenset(
    {
        "artifactr:open",
        "artifactr:read_workspaces",
        "artifactr:create_artifact",
        "artifactr:edit_artifact",
        "artifactr:archive_artifact",
        "artifactr:propose_change",
        "artifactr:respond_to_proposal",
        "artifactr:create_thread",
        "artifactr:post_message",
        "artifactr:set_focus",
        "artifactr:set_thread_mode",
        "artifactr:answer_deferred",
        "artifactr:give_feedback",
        "artifactr:stop_run",
        "artifactr:use_model",
        "artifactr:create_native_file",
        "artifactr:run_connected_code",
        "artifactr:record",
        "artifactr:claim_thread",
        "artifactr:save_cursor",
        "artifactr:read_artifacts",
        "artifactr:read_threads",
        "artifactr:read_proposals",
        "artifactr:read_runs",
        "artifactr:read_history",
        "artifactr:read_events",
        "artifactr:read_cursors",
    }
)

Every action a Workspace asks authorize about: the complete catalog.

An action is artifactr: and a name. A command's is its type, a read's is read_ and what it reads, and opening a workspace is artifactr:open. artifactr:read_workspaces, listing a tenant's workspaces, is the one asked with no workspace.

OnOpen module-attribute

OnOpen = Callable[[TenantId, WorkspaceId], Awaitable[None]]

Called each time Workspaces.open opens a workspace, after authorize allows it.

It starts a workspace's background work, such as a feedback mirror, so it must be idempotent: a permission check has no side effects.

Gate module-attribute

Gate = Callable[
    ["Workspace", Command, Changes], Awaitable[None]
]

Refuses a command while an integration it needs is off in the workspace (ADR-0081).

Workspaces holds it, and Workspace.commit calls it once the command's targets pass hidden and before authorize hears the command, so a refusal says nothing about the actor's grants, and nothing about a hidden artifact. It is given the committing handle, the command, and the Changes it makes, read without asking authorize. It refuses with NotEnabled; anything else it raises fails the command as an error. Reads and facts are never gated.

Changes module-attribute

Changes = Versioned[Artifact] | CreateArtifact | None

The data a command makes or changes, as a Gate hears it (ADR-0081).

It is the artifact an edit, or an accepted proposal, changes, as storage holds it; or the CreateArtifact that makes one, a proposal's among them. It is None for a command that changes no artifact's data, such as an archive or a rejected proposal, and for one on an artifact that doesn't exist.

integration_gate

integration_gate(
    integrations: Integrations, key_of: KeyOf
) -> Gate

Return a gate that refuses changes to what an integration governs while it is off.

While it is off, creating, editing and proposing to create or edit such an artifact are refused, and so is accepting a proposal about one, whatever it proposes, since accepting carries a change out. Archiving one, proposing to archive one, and rejecting a proposal pass, so people can still tidy up; a pending proposal stays, to be accepted once the integration is on again. A command on no artifact, or on one no integration governs, always passes, and so does a create whose data isn't its type's, which core refuses.

Parameters:

Name Type Description Default
integrations Integrations

Whether an integration is on in a tenant's workspace.

required
key_of KeyOf

The integration that governs an artifact, such as "excalidraw" for an excalidraw_diagram, or None for one none does. It reads the data as core stores it, with its type's defaults, whether the artifact is made or changed.

required

KeyOf module-attribute

KeyOf = Callable[[str, Mapping[str, JsonValue]], str | None]

The integration that governs an artifact, by its kind and its data as JSON, or None.

DIRECT_WRITES module-attribute

DIRECT_WRITES: Final = 'agent-writes:direct'

The setting that names the kinds whose agents' writes apply directly in Auto.

direct_writes

direct_writes(types: Iterable[type[Artifact]]) -> Setting

agent-writes:direct, for the settings registry, over the application's types.

Its default is the kinds whose write_policy is "direct"; each kind is labelled with what its type does by default.

direct_writes_from

direct_writes_from(settings: Settings) -> DirectWrites

The kinds a settings store holds in agent-writes:direct, read on each agent's write.

A store that can't be read answers the setting's floor, no kinds, as grantr's adapter does, so every agent's write is a proposal; a value that isn't names raises TypeError, which refuses the write.

DirectWrites module-attribute

The kinds whose agents' writes apply directly in a thread in Auto, in a tenant's workspace.

Storage

The storage protocol, and the in-memory implementation. See Storage.

Storage

Bases: Protocol

Persistence for workspaces. Every method is scoped to one tenant's workspace.

The exception is workspaces, which lists a tenant's.

A caller can be cancelled at any await, by a stopped run, a timeout or a closed connection, so every method is cancel-safe: a cancelled caller leaves no lock or connection behind; cancellation may be deferred until the current statement ends. So a cancelled call may still have taken effect: a transaction may have committed, or acquire_lease taken the lease. A wait for a pooled connection cannot be interrupted either, so a task that holds a transaction must not await a task it cancelled. The event loop's shutdown is not covered: it cancels the storage's own tasks too, so stop runs with Runner.aclose first.

transaction

transaction(
    scope: Scope,
) -> AbstractAsyncContextManager[Transaction]

Begin a transaction that commits when the block exits normally.

workspaces async

workspaces(
    tenant_id: TenantId,
    *,
    after: WorkspaceId | None = None,
    limit: int = 100,
) -> list[WorkspaceId]

Return a page of a tenant's workspaces, in the order of their ids.

A workspace is listed once its log has an event. Reading one, or keeping its cursors or leases, does not list it. Ids are ordered as the storage orders strings, so one page follows on from the last.

Parameters:

Name Type Description Default
tenant_id TenantId

The tenant whose workspaces to list.

required
after WorkspaceId | None

Only workspaces whose ids come after this one: the last of the previous page.

None
limit int

At most this many.

100

artifact async

artifact(
    scope: Scope, artifact_id: ArtifactId
) -> Versioned[Artifact] | None

Return an artifact's current version, or None.

artifacts async

artifacts(
    scope: Scope,
    *,
    kind: str | None = None,
    include_archived: bool = False,
) -> list[Versioned[Artifact]]

Return current artifacts, optionally of one kind, oldest first.

revisions async

revisions(
    scope: Scope, artifact_id: ArtifactId
) -> list[Revision]

Return an artifact's revisions, oldest first.

drop_revisions async

drop_revisions(
    scope: Scope,
    artifact_id: ArtifactId,
    versions: Collection[int],
) -> int

Forget some of an artifact's earlier revisions, as retention thins them; how many.

Its current version is never forgotten, whatever versions names: what is read of an artifact, its head, stays. The log's events, which say what each revision changed, stay too. A version it doesn't hold is passed over.

thread async

thread(scope: Scope, thread_id: ThreadId) -> Thread | None

Return a thread, or None.

threads async

threads(scope: Scope) -> list[Thread]

Return every thread, oldest first.

proposal async

proposal(
    scope: Scope, proposal_id: ProposalId
) -> Proposal | None

Return a proposal, or None.

proposals async

proposals(
    scope: Scope,
    *,
    status: Literal["pending", "accepted", "rejected"]
    | None = None,
) -> list[Proposal]

Return proposals, optionally with one status, oldest first.

run async

run(scope: Scope, run_id: RunId) -> Run | None

Return a run, or None.

runs async

runs(
    scope: Scope,
    *,
    thread_id: ThreadId | None = None,
    status: RunStatus | None = None,
) -> list[Run]

Return runs, optionally of one thread and with one status, oldest first.

head_seq async

head_seq(scope: Scope) -> int

Return the log's latest seq, or 0 if it is empty.

read async

read(
    scope: Scope,
    *,
    after_seq: int = 0,
    before_seq: int | None = None,
    threads: Collection[ThreadId] | None = None,
    limit: int | None = None,
    last: int | None = None,
) -> list[Envelope]

Return logged envelopes in the window after_seq < seq < before_seq, in order.

Parameters:

Name Type Description Default
scope Scope

The workspace whose log to read.

required
after_seq int

Only envelopes after this seq.

0
before_seq int | None

Only envelopes before this seq; None reads to the head.

None
threads Collection[ThreadId] | None

Only the envelopes a subscriber following these threads receives, by delivered_to's rule; None reads every thread.

None
limit int | None

At most this many: the first ones in the window that match.

None
last int | None

At most this many: the last ones in the window that match, still returned in order. This is the tail of the log.

None

Callers give at most one of limit and last, and no negative numbers; read checks.

subscribe

subscribe(
    scope: Scope, *, after_seq: int = 0
) -> AsyncGenerator[Envelope]

Yield envelopes with seq greater than after_seq.

First the stored ones, then each new one as it is committed. The iterator runs until it is closed.

history async

history(
    scope: Scope, thread_id: ThreadId
) -> Sequence[HistoryChunk]

Return a thread's history chunks, in the order they were appended.

acquire_lease async

acquire_lease(
    scope: Scope, key: str, holder: str, ttl: timedelta
) -> bool

Take or renew an exclusive lease. Return False if another holder has it.

renew_lease async

renew_lease(
    scope: Scope, key: str, holder: str, ttl: timedelta
) -> bool

Renew a lease only if holder still has it, expired or not; never take one.

Return False if the lease is another holder's, or no one's: a holder that took it after it expired may have released it since. It checks the holder and renews in one statement, and never takes a lease, so a claim renewed late is renewed only if no one else had it meanwhile. That needs holders unique to each claim attempt: a holder used again could pass for one that had the lease since.

release_lease async

release_lease(scope: Scope, key: str, holder: str) -> None

Release a lease if holder has it.

lease async

lease(
    scope: Scope, key: str
) -> tuple[str, datetime] | None

Return who holds a lease and when it expires, or None if no one holds it now.

A lease whose expiry has passed, by the storage's clock, is held by no one, as acquire_lease judges it (ADR-0071).

cursor async

cursor(scope: Scope, name: str) -> int

Return how far a named consumer of the log has got: the seq saved, or 0.

save_cursor async

save_cursor(scope: Scope, name: str, seq: int) -> None

Save how far a named consumer of the log has got, such as a feedback mirror.

A cursor only moves forward: saving a seq below the saved one leaves it, so a consumer running in several processes cannot move it back.

Transaction

Bases: Protocol

One atomic unit of work on a workspace.

A transaction must be serialized with respect to every other transaction on the same scope from the moment it begins, so what it loads cannot change before it saves. The in-memory storage holds a per-workspace lock; SQL storage locks the workspace row.

load async

load(needs: Needs) -> State

Load the requested entities, and whether the requested message ids are used.

Entity ids that do not exist map to None.

save async

save(
    result: CommitResult,
    *,
    actor: Actor,
    traceparent: str | None = None,
) -> list[Envelope]

Persist a result's entities, revisions and used message ids, and log its events.

Parameters:

Name Type Description Default
result CommitResult

What core decided.

required
actor Actor

Who the envelopes are attributed to.

required
traceparent str | None

The W3C trace context the envelopes record.

None

Returns:

Type Description
list[Envelope]

The appended envelopes, with their seq numbers assigned.

append_history async

append_history(
    thread_id: ThreadId, messages: bytes
) -> None

Append serialized model messages to a thread's history.

save_cursor async

save_cursor(name: str, seq: int) -> None

Save a named cursor with this transaction: it moves forward, if the transaction commits.

It is Storage.save_cursor, made atomic with the transaction's writes.

holds_lease async

holds_lease(key: str, holder: str) -> bool

Whether holder has the lease key, expired or not, until the transaction ends.

A write fenced by a claim asks it first: Storage.acquire_lease for another holder must not take the lease between the answer and the commit. SQL storage locks the lease's row; in-memory storage's acquire_lease waits for the workspace's lock, which the transaction holds.

Scope dataclass

Scope(tenant_id: TenantId, workspace_id: WorkspaceId)

A tenant's workspace: the unit of isolation, ordering and locking.

HistoryChunk dataclass

HistoryChunk(seq: int, messages: bytes)

Serialized model messages from one run segment, and the seq they were saved at.

seq instance-attribute

seq: int

The log's head when the chunk was saved: everything up to it happened before.

seal

seal(
    events: Sequence[KnownEvent],
    *,
    after_seq: int,
    scope: Scope,
    actor: Actor,
    ts: datetime,
    traceparent: str | None,
) -> list[Envelope]

Put a result's events in envelopes, numbered on from after_seq, to log them.

Implementations of Transaction.save call it, so every storage stamps, scopes and numbers envelopes alike.

InMemoryStorage

InMemoryStorage(*, clock: Clock = _utc_now)

Storage that keeps every workspace in process memory.

Use it from one event loop: its locks are asyncio's, so a caller waiting on one from another loop is never woken.

Parameters:

Name Type Description Default
clock Clock

Returns the current time. Defaults to the system clock in UTC.

_utc_now

transaction async

transaction(scope: Scope) -> AsyncGenerator[_Transaction]

Begin a transaction; it holds the workspace's lock until it ends.

workspaces async

workspaces(
    tenant_id: TenantId,
    *,
    after: WorkspaceId | None = None,
    limit: int = 100,
) -> list[WorkspaceId]

Return a page of a tenant's workspaces with an event in their logs, by id.

artifact async

artifact(
    scope: Scope, artifact_id: ArtifactId
) -> Versioned[Artifact] | None

Return an artifact's current version, or None.

artifacts async

artifacts(
    scope: Scope,
    *,
    kind: str | None = None,
    include_archived: bool = False,
) -> list[Versioned[Artifact]]

Return current artifacts, optionally of one kind, oldest first.

revisions async

revisions(
    scope: Scope, artifact_id: ArtifactId
) -> list[Revision]

Return an artifact's revisions, oldest first.

drop_revisions async

drop_revisions(
    scope: Scope,
    artifact_id: ArtifactId,
    versions: Collection[int],
) -> int

Forget some of an artifact's earlier revisions; never its current version.

thread async

thread(scope: Scope, thread_id: ThreadId) -> Thread | None

Return a thread, or None.

threads async

threads(scope: Scope) -> list[Thread]

Return every thread, oldest first.

proposal async

proposal(
    scope: Scope, proposal_id: ProposalId
) -> Proposal | None

Return a proposal, or None.

proposals async

proposals(
    scope: Scope,
    *,
    status: Literal["pending", "accepted", "rejected"]
    | None = None,
) -> list[Proposal]

Return proposals, optionally with one status, oldest first.

run async

run(scope: Scope, run_id: RunId) -> Run | None

Return a run, or None.

runs async

runs(
    scope: Scope,
    *,
    thread_id: ThreadId | None = None,
    status: RunStatus | None = None,
) -> list[Run]

Return runs, optionally of one thread and with one status, oldest first.

head_seq async

head_seq(scope: Scope) -> int

Return the log's latest seq, or 0 if it is empty.

read async

read(
    scope: Scope,
    *,
    after_seq: int = 0,
    before_seq: int | None = None,
    threads: Collection[ThreadId] | None = None,
    limit: int | None = None,
    last: int | None = None,
) -> list[Envelope]

Return logged envelopes in the window after_seq < seq < before_seq, in order.

Of those delivered to threads, if given: the first limit or the last last.

subscribe async

subscribe(
    scope: Scope, *, after_seq: int = 0
) -> AsyncGenerator[Envelope]

Yield stored envelopes after after_seq, then each new one as it commits.

history async

history(
    scope: Scope, thread_id: ThreadId
) -> Sequence[HistoryChunk]

Return a thread's history chunks, in the order they were appended.

acquire_lease async

acquire_lease(
    scope: Scope, key: str, holder: str, ttl: timedelta
) -> bool

Take or renew an exclusive lease. Return False if another holder has it.

It waits for the workspace's transaction, as SQL storage's waits for a lease's row that a transaction locked (holds_lease).

renew_lease async

renew_lease(
    scope: Scope, key: str, holder: str, ttl: timedelta
) -> bool

Renew a lease only if holder still has it, expired or not; never take one.

release_lease async

release_lease(scope: Scope, key: str, holder: str) -> None

Release a lease if holder has it.

lease async

lease(
    scope: Scope, key: str
) -> tuple[str, datetime] | None

Return who holds a lease and when it expires, or None if no one holds it now.

cursor async

cursor(scope: Scope, name: str) -> int

Return how far a named consumer of the log has got: the seq saved, or 0.

save_cursor async

save_cursor(scope: Scope, name: str, seq: int) -> None

Save how far a named consumer of the log has got; a cursor only moves forward.