Skip to content

Assistants API

assistants

Durable long-lived assistants with an inbox and scheduler.

SPEND_EXHAUSTED module-attribute

SPEND_EXHAUSTED = 'daily spend cap reached'

The blocker reason of an llm assistant held back by the daily spend cap.

ArtifactMeta

Lifecycle metadata of one artifact (its screen is the view view_name).

UnknownArtifact

No artifact has this id.

CodeHandler

An in-process handler bound to a code assistant.

handle async
handle(message: Message, ctx: WakeContext) -> None

Process one message, buffering effects on ctx.

Source code in orqest/assistants/context.py
async def handle(self, message: Message, ctx: WakeContext) -> None:
    """Process one message, buffering effects on ``ctx``."""
    ...

StateValidationError

Assistant state does not satisfy the assistant's state schema.

WakeContext

WakeContext(
    *,
    address: str,
    now: datetime,
    state: dict[str, Any],
    state_schema: dict[str, Any] | None,
    contracts: ContractRegistry,
    clock: Callable[[], datetime] | None = None,
    ui_registry: ComponentRegistry | None = None,
    base_context: dict[str, Any] | None = None,
    stored_views: list[ViewSpec] | None = None,
    artifact_status: Callable[[str], Awaitable[str | None]]
    | None = None,
)

What a handler sees while processing one message.

Sends, state changes, scheduled wakes and published views are buffered here; the runtime commits them together with the message completion in one transaction, or discards them all if the handler raises.

Attributes:

Name Type Description
address

The assistant being run.

now

The time this context was created (tz-aware).

state

Working copy of the assistant's state.

Parameters:

Name Type Description Default
address str

The assistant being run.

required
now datetime

Current time (tz-aware).

required
state dict[str, Any]

Persisted state; the context works on a deep copy.

required
state_schema dict[str, Any] | None

JSON Schema for the state, or None to accept any dict.

required
contracts ContractRegistry

Registry used to validate outgoing messages.

required
clock Callable[[], datetime] | None

Timestamp source for outgoing messages; defaults to now.

None
ui_registry ComponentRegistry | None

Components views may use; defaults to :func:orqest.ui.registry.default_registry.

None
base_context dict[str, Any] | None

Binding context views are validated against (with "state" replaced by the working state); defaults to empty.

None
stored_views list[ViewSpec] | None

The assistant's views as stored before this wake. Only the LLM update_state tool reads them (to report views a patch breaks); the runtime passes them for llm assistants.

None
artifact_status Callable[[str], Awaitable[str | None]] | None

Async lookup of the status of this assistant's artifact id (or None if it has none), which the LLM artifact tools use to refuse early. The commit checks again.

None
Source code in orqest/assistants/context.py
def __init__(
    self,
    *,
    address: str,
    now: datetime,
    state: dict[str, Any],
    state_schema: dict[str, Any] | None,
    contracts: ContractRegistry,
    clock: Callable[[], datetime] | None = None,
    ui_registry: ComponentRegistry | None = None,
    base_context: dict[str, Any] | None = None,
    stored_views: list[ViewSpec] | None = None,
    artifact_status: Callable[[str], Awaitable[str | None]] | None = None,
) -> None:
    self.address = address
    self.now = now
    self.state = copy.deepcopy(state)
    self._state_schema = state_schema
    self._contracts = contracts
    self._clock = clock or (lambda: now)
    self._outbox: list[Message] = []
    self._scheduled: list[Wake] = []
    self._ui_registry = ui_registry
    self._base_context = base_context if base_context is not None else {}
    self._views: dict[str, ViewSpec] = {}
    self._stored_views = {v.name: v for v in stored_views or []}
    self._artifacts: dict[str, ArtifactShow | None] = {}
    self._artifact_status = artifact_status
outbox property
outbox: list[Message]

Buffered outgoing messages (a copy).

scheduled property
scheduled: list[Wake]

Buffered one-shot wakes (a copy).

views property
views: list[ViewSpec]

Buffered views, one per name, in first-publish order (deep copies).

artifacts property
artifacts: dict[str, ArtifactShow | None]

Buffered artifact changes by id: a show, or None for a dismissal (a copy).

send
send(
    recipient: str,
    message_type: str,
    payload: dict[str, Any],
    *,
    reply_to: str | None = None,
) -> str

Buffer a message to recipient and return its id.

The payload is JSON round-tripped, so the buffered copy is exactly what will be persisted.

Raises:

Type Description
ValueError

If recipient is not a valid address.

TypeError

If payload is not JSON-serialisable.

ContractViolation

If the recipient's contracts reject the message.

Source code in orqest/assistants/context.py
def send(
    self,
    recipient: str,
    message_type: str,
    payload: dict[str, Any],
    *,
    reply_to: str | None = None,
) -> str:
    """Buffer a message to ``recipient`` and return its id.

    The payload is JSON round-tripped, so the buffered copy is exactly
    what will be persisted.

    Raises:
        ValueError: If ``recipient`` is not a valid address.
        TypeError: If ``payload`` is not JSON-serialisable.
        ContractViolation: If the recipient's contracts reject the message.
    """
    check_identifier(recipient, kind="address")
    payload = json_roundtrip(payload, "payload")
    self._contracts.validate(recipient, message_type, payload)
    ts = self._clock()
    msg = Message(
        sender=self.address,
        recipient=recipient,
        type=message_type,
        payload=payload,
        reply_to=reply_to,
        available_at=ts,
        created_at=ts,
    )
    self._outbox.append(msg)
    return msg.id
reply
reply(
    message: Message,
    message_type: str,
    payload: dict[str, Any],
) -> str

Buffer a reply to message's sender; return the new message id.

Source code in orqest/assistants/context.py
def reply(self, message: Message, message_type: str, payload: dict[str, Any]) -> str:
    """Buffer a reply to ``message``'s sender; return the new message id."""
    return self.send(message.sender, message_type, payload, reply_to=message.id)
update_state
update_state(patch: dict[str, Any]) -> dict[str, Any]

Merge-patch the working state and validate it against the schema.

Returns:

Type Description
dict[str, Any]

The new working state.

Raises:

Type Description
StateValidationError

If the patch is not a dict or the patched state is not a JSON-serialisable dict satisfying the schema; the working copy is left unchanged.

Source code in orqest/assistants/context.py
def update_state(self, patch: dict[str, Any]) -> dict[str, Any]:
    """Merge-patch the working state and validate it against the schema.

    Returns:
        The new working state.

    Raises:
        StateValidationError: If the patch is not a dict or the patched
            state is not a JSON-serialisable dict satisfying the schema;
            the working copy is left unchanged.
    """
    if not isinstance(patch, dict):
        raise StateValidationError(f"patch must be a dict, got {type(patch).__name__}")
    if not isinstance(self.state, dict):
        raise StateValidationError(f"state must be a dict, got {type(self.state).__name__}")
    self.state = check_persistable_state(merge_patch(self.state, patch), self._state_schema)
    return self.state
schedule_once
schedule_once(at: datetime, reason: str) -> None

Buffer a one-shot wake at at (tz-aware).

Source code in orqest/assistants/context.py
def schedule_once(self, at: datetime, reason: str) -> None:
    """Buffer a one-shot wake at ``at`` (tz-aware)."""
    self._scheduled.append(Wake(kind="once", at=at, reason=reason))
publish_view
publish_view(spec: ViewSpec) -> list[str]

Validate spec and buffer it, replacing any view of the same name.

The view is JSON round-tripped first, so the buffered copy is exactly what will be persisted and later handler mutations cannot change it. It is validated against the base context with "state" set to the working state. Bindings that do not resolve are not problems (they render as placeholders); they are returned as warnings.

Returns:

Type Description
list[str]

One warning per binding that does not resolve in that context

list[str]

(empty when all resolve).

Raises:

Type Description
TypeError

If spec is not a ViewSpec or is not JSON-serialisable.

ViewValidationError

If the view has structural problems.

Source code in orqest/assistants/context.py
def publish_view(self, spec: ViewSpec) -> list[str]:
    """Validate ``spec`` and buffer it, replacing any view of the same name.

    The view is JSON round-tripped first, so the buffered copy is exactly
    what will be persisted and later handler mutations cannot change it.
    It is validated against the base context with ``"state"`` set to the
    working state. Bindings that do not resolve are not problems (they
    render as placeholders); they are returned as warnings.

    Returns:
        One warning per binding that does not resolve in that context
        (empty when all resolve).

    Raises:
        TypeError: If ``spec`` is not a ``ViewSpec`` or is not
            JSON-serialisable.
        ViewValidationError: If the view has structural problems.
    """
    if not isinstance(spec, ViewSpec):
        raise TypeError(f"spec must be a ViewSpec, got {type(spec).__name__}")
    try:
        spec = ViewSpec.model_validate_json(spec.model_dump_json())
    except PydanticSerializationError as exc:
        raise TypeError(f"view {spec.name!r} is not JSON-serialisable: {exc}") from exc
    if spec.name.startswith(ARTIFACT_VIEW_PREFIX):
        raise ViewValidationError(
            spec.name,
            [f"names starting with {ARTIFACT_VIEW_PREFIX!r} are reserved for artifacts"],
        )
    warnings = self._check_view(spec)
    self._views[spec.name] = spec
    return warnings
show_artifact
show_artifact(
    artifact_id: str,
    *,
    intent: str,
    title: str,
    a11y_label: str,
    root: ViewNode,
    allowed_actions: list[str] | None = None,
    expires_in_s: float | None = None,
    source_refs: list[str] | None = None,
    approval_requirements: list[str] | None = None,
) -> list[str]

Buffer an artifact to show: created, or updated if the id exists (version +1).

The tree is validated like :meth:publish_view and becomes the view art-<artifact_id>. Showing an id again in one wake replaces the earlier show (one version bump); showing a dismissed or expired artifact makes it active again. A pinned artifact stays pinned, and a show of one the owner kept frozen is ignored. An id with no artifact that names one of this assistant's views fails the commit.

Returns:

Type Description
list[str]

One warning per binding that does not resolve.

Raises:

Type Description
ValueError

For a malformed field or id, a bad expires_in_s or an invalid tree (:class:ViewValidationError).

TypeError

If the tree is not JSON-serialisable.

Source code in orqest/assistants/context.py
def show_artifact(
    self,
    artifact_id: str,
    *,
    intent: str,
    title: str,
    a11y_label: str,
    root: ViewNode,
    allowed_actions: list[str] | None = None,
    expires_in_s: float | None = None,
    source_refs: list[str] | None = None,
    approval_requirements: list[str] | None = None,
) -> list[str]:
    """Buffer an artifact to show: created, or updated if the id exists (version +1).

    The tree is validated like :meth:`publish_view` and becomes the view
    ``art-<artifact_id>``. Showing an id again in one wake replaces the earlier
    show (one version bump); showing a dismissed or expired artifact makes it
    active again. A pinned artifact stays pinned, and a show of one the owner kept
    frozen is ignored. An id with no artifact that names one of this assistant's
    views fails the commit.

    Returns:
        One warning per binding that does not resolve.

    Raises:
        ValueError: For a malformed field or id, a bad ``expires_in_s`` or an
            invalid tree (:class:`ViewValidationError`).
        TypeError: If the tree is not JSON-serialisable.
    """
    fields = checked_fields(
        artifact_id=artifact_id,
        intent=intent,
        title=title,
        a11y_label=a11y_label,
        allowed_actions=allowed_actions,
        source_refs=source_refs,
        approval_requirements=approval_requirements,
    )
    if expires_in_s is not None:
        if (
            isinstance(expires_in_s, bool)
            or not isinstance(expires_in_s, int | float)
            or not 0 < expires_in_s <= MAX_EXPIRY_S
        ):
            raise ValueError(f"expires_in_s must be between 0 and {MAX_EXPIRY_S} seconds")
    spec = ViewSpec(name=view_name_for(artifact_id), root=root)
    try:
        spec = ViewSpec.model_validate_json(spec.model_dump_json())
    except PydanticSerializationError as exc:
        raise TypeError(f"artifact {artifact_id!r} is not JSON-serialisable: {exc}") from exc
    warnings = self._check_view(spec)
    self._artifacts[artifact_id] = ArtifactShow(
        root=spec.root, freshness=self.now, expires_in_s=expires_in_s, **fields
    )
    return warnings
dismiss_artifact
dismiss_artifact(artifact_id: str) -> None

Buffer the dismissal of an artifact (a no-op at commit if it isn't on screen).

Dismissing an id shown earlier in the same wake drops that show. A pinned artifact can't be dismissed by the assistant: the commit leaves it as it is.

Source code in orqest/assistants/context.py
def dismiss_artifact(self, artifact_id: str) -> None:
    """Buffer the dismissal of an artifact (a no-op at commit if it isn't on screen).

    Dismissing an id shown earlier in the same wake drops that show. A pinned
    artifact can't be dismissed by the assistant: the commit leaves it as it is.
    """
    check_artifact_id(artifact_id)
    self._artifacts[artifact_id] = None
artifact_status async
artifact_status(artifact_id: str) -> str | None

The status of this assistant's artifact artifact_id, or None (no such one).

"kept" stands for pinned and frozen: the owner kept the screen as they saw it.

Source code in orqest/assistants/context.py
async def artifact_status(self, artifact_id: str) -> str | None:
    """The status of this assistant's artifact ``artifact_id``, or ``None`` (no such one).

    ``"kept"`` stands for pinned and frozen: the owner kept the screen as they saw it.
    """
    if self._artifact_status is None:
        return None
    return await self._artifact_status(artifact_id)
has_stored_view
has_stored_view(name: str) -> bool

Whether a view named name was stored before this wake.

Source code in orqest/assistants/context.py
def has_stored_view(self, name: str) -> bool:
    """Whether a view named ``name`` was stored before this wake."""
    return name in self._stored_views
validate
validate() -> None

Check everything buffered can be persisted (handlers may mutate directly).

Normalises state to its JSON form. Views need no check here: they are validated and JSON round-tripped when published.

Raises:

Type Description
StateValidationError

If the working state is not a JSON-serialisable dict satisfying the schema.

TypeError

If a buffered message payload is not JSON-serialisable.

Source code in orqest/assistants/context.py
def validate(self) -> None:
    """Check everything buffered can be persisted (handlers may mutate directly).

    Normalises ``state`` to its JSON form. Views need no check here: they
    are validated and JSON round-tripped when published.

    Raises:
        StateValidationError: If the working state is not a JSON-serialisable
            dict satisfying the schema.
        TypeError: If a buffered message payload is not JSON-serialisable.
    """
    self.state = check_persistable_state(self.state, self._state_schema)
    for msg in self._outbox:
        json_roundtrip(msg.payload, "payload")

Contract

Declares one message type an address accepts, with its payload schema.

ContractRegistry

ContractRegistry()

Registry of contracts keyed by (address, message_type).

Source code in orqest/assistants/contracts.py
def __init__(self) -> None:
    self._contracts: dict[tuple[str, str], Contract] = {}
register
register(contract: Contract) -> None

Register a contract.

Raises:

Type Description
ValueError

If (address, message_type) is already registered.

Source code in orqest/assistants/contracts.py
def register(self, contract: Contract) -> None:
    """Register a contract.

    Raises:
        ValueError: If ``(address, message_type)`` is already registered.
    """
    key = (contract.address, contract.message_type)
    if key in self._contracts:
        raise ValueError(f"contract already registered for {key}")
    Draft202012Validator.check_schema(contract.payload_schema)
    self._contracts[key] = contract
get
get(address: str, message_type: str) -> Contract | None

Return the contract for (address, message_type) or None.

Source code in orqest/assistants/contracts.py
def get(self, address: str, message_type: str) -> Contract | None:
    """Return the contract for ``(address, message_type)`` or ``None``."""
    return self._contracts.get((address, message_type))
for_address
for_address(address: str) -> list[Contract]

Return all contracts registered for address.

Source code in orqest/assistants/contracts.py
def for_address(self, address: str) -> list[Contract]:
    """Return all contracts registered for ``address``."""
    return [c for (a, _), c in self._contracts.items() if a == address]
validate
validate(
    recipient: str,
    message_type: str,
    payload: dict[str, Any],
) -> None

Validate a message against the recipient's contracts.

A recipient with no contracts accepts anything.

Raises:

Type Description
ContractViolation

If the type is not contracted or the payload fails schema validation.

Source code in orqest/assistants/contracts.py
def validate(self, recipient: str, message_type: str, payload: dict[str, Any]) -> None:
    """Validate a message against the recipient's contracts.

    A recipient with no contracts accepts anything.

    Raises:
        ContractViolation: If the type is not contracted or the payload
            fails schema validation.
    """
    contracts = self.for_address(recipient)
    if not contracts:
        return
    contract = self.get(recipient, message_type)
    if contract is None:
        allowed = sorted(c.message_type for c in contracts)
        raise ContractViolation(
            f"{recipient!r} does not accept message type {message_type!r}; allowed: {allowed}"
        )
    error = next(iter(Draft202012Validator(contract.payload_schema).iter_errors(payload)), None)
    if error is not None:
        raise ContractViolation(error.message)

ContractViolation

A message does not satisfy the recipient's contracts.

ViewSnapshot

A view as a renderer should show it, with the event sequence it reflects.

Attributes:

Name Type Description
resolved ResolvedView

The resolved view.

seq int

The seq of the last ui.view.init / ui.view.delta event this resolution includes; 0 when it was not emitted (the next event for the view is then an init).

Message

A message addressed to an assistant (or runtime endpoint).

Attributes:

Name Type Description
id str

Unique message id (uuid4 by default).

sender str

Address of the sender.

recipient str

Address of the recipient.

type str

Message type, matching ^[a-z][a-z0-9_.]{0,63}$.

payload dict[str, Any]

JSON payload.

reply_to str | None

Id of the message this replies to, if any.

status MessageStatus

Delivery lifecycle state.

attempts int

Number of processing attempts so far.

available_at datetime

Earliest time the message may be processed (tz-aware).

created_at datetime

Creation time (tz-aware).

last_error str | None

Error from the most recent failed attempt.

AssistantRuntime

AssistantRuntime(
    db_path: str | Path,
    *,
    factory: AgentFactory | None = None,
    contracts: ContractRegistry | None = None,
    memory: MemoryStore | None = None,
    bus: EventBus | None = None,
    clock: Callable[[], datetime] = _utc_now,
    model: Model | None = None,
    max_attempts: int = 5,
    backoff_base_s: float = 2.0,
    run_timeout_s: float | None = 300.0,
    ui_registry: ComponentRegistry | None = None,
    view_context: Callable[
        [AssistantRecord], Awaitable[dict[str, Any]]
    ]
    | None = None,
    view_context_timeout_s: float | None = 5.0,
    default_views: tuple[str, ...] = (),
    model_for: Callable[
        [AssistantRecord, list[Message]], Model | None
    ]
    | None = None,
    usage_limits: UsageLimits | None = UsageLimits(
        request_limit=20, tool_calls_limit=40
    ),
    daily_token_budget: int | None = None,
    budget_tz: str = "UTC",
    spend_cap: SpendCap | None = None,
    keeper: Keeper | None = None,
    owner_senders: frozenset[str] = frozenset(),
    wake_context: Callable[
        [AssistantRecord, list[Message]],
        Awaitable[dict[str, Any] | None],
    ]
    | None = None,
)

Runs durable assistants over one SQLite database.

Every processed message is either fully committed (state change, outgoing messages, scheduled wakes, published views, artifact changes and the message's completion in one transaction) or leaves no trace beyond a retry/failure record. The exception is a keeper's compartment tools: they act on the keeper's own file at once, so a run that fails afterwards keeps what they did. Use as an async context manager.

Parameters:

Name Type Description Default
db_path str | Path

SQLite database file (created if missing).

required
factory AgentFactory | None

Agent factory that spawns llm assistants; required by :meth:create and for llm assistants to run.

None
contracts ContractRegistry | None

Message contracts; defaults to an empty registry (accept all).

None
memory MemoryStore | None

Optional episodic memory for llm assistants (best-effort).

None
bus EventBus | None

Event bus for runtime events such as dead-lettered messages, and for live views, emitted best-effort after each commit (see :class:orqest.assistants.live_views.ViewService).

None
clock Callable[[], datetime]

Source of tz-aware "now".

_utc_now
model Model | None

Model for llm assistants; None resolves spec.agent.model.

None
max_attempts int

Processing attempts before a message is marked failed. A message whose attempt crashes the process counts that attempt too: at startup, an interrupted message that has used all its attempts is dead-lettered instead of being retried.

5
backoff_base_s float

Base of the exponential retry backoff, in seconds.

2.0
run_timeout_s float | None

Time limit for one handler call or model run; on expiry the run fails with TimeoutError and goes through the normal retry / dead-letter path. None disables the limit. :meth:tick explains how it bounds a whole tick.

300.0
ui_registry ComponentRegistry | None

Components assistants' views may use; defaults to :func:orqest.ui.registry.default_registry.

None
view_context Callable[[AssistantRecord], Awaitable[dict[str, Any]]] | None

Async builder of the binding context views are validated against (see :class:~orqest.assistants.live_views.ViewService); defaults to {"state": record.state}. A builder that raises, times out or returns a non-dict does not fail the run: a warning is logged and the default context is used. One exception: when run_timeout_s is not larger than view_context_timeout_s, a hung builder is cut off by the run timeout itself and fails the run. A builder that calls a lifecycle method on the address it builds for gets RuntimeError (it would wait for itself).

None
view_context_timeout_s float | None

Budget for one view_context call, capped by run_timeout_s; None leaves only that cap. On expiry the default context is used, as for a builder exception.

5.0
default_views tuple[str, ...]

View names every llm assistant shows: each one it has not published is a :func:~orqest.ui.view.fallback_view of its state (emitted, rendered and listed like a stored view; a stored view of the same name wins). Code assistants get no fallbacks.

()
daily_token_budget int | None

Daily tokens for llm assistants whose spec sets none; None is no limit. See :class:~orqest.assistants.budget.UsageLedger.

None
budget_tz str

IANA zone whose midnight starts a new budget day (also the spend cap's day).

'UTC'
spend_cap SpendCap | None

A daily cap on what all assistants spend together (see :class:~orqest.assistants.spend.SpendCap); None is no cap.

None
keeper Keeper | None

An open compartments keeper (the application opens and closes it). Each wake of an llm assistant reads its grants, which decide its compartment tools and whether its sends and memories get a leak check. If they cannot be read, the wake fails and is retried.

None
owner_senders frozenset[str]

Senders whose messages count as the owner's when a compartment release is prepared. Empty: no wake can prepare one.

frozenset()

Raises:

Type Description
ValueError

If run_timeout_s or view_context_timeout_s is not positive, daily_token_budget is below 1, budget_tz is unknown, or a default_views name is not a valid view name.

Source code in orqest/assistants/runtime.py
def __init__(
    self,
    db_path: str | Path,
    *,
    factory: AgentFactory | None = None,
    contracts: ContractRegistry | None = None,
    memory: MemoryStore | None = None,
    bus: EventBus | None = None,
    clock: Callable[[], datetime] = _utc_now,
    model: Model | None = None,
    max_attempts: int = 5,
    backoff_base_s: float = 2.0,
    run_timeout_s: float | None = 300.0,
    ui_registry: ComponentRegistry | None = None,
    view_context: Callable[[AssistantRecord], Awaitable[dict[str, Any]]] | None = None,
    view_context_timeout_s: float | None = 5.0,
    default_views: tuple[str, ...] = (),
    model_for: Callable[[AssistantRecord, list[Message]], Model | None] | None = None,
    usage_limits: UsageLimits | None = UsageLimits(request_limit=20, tool_calls_limit=40),
    daily_token_budget: int | None = None,
    budget_tz: str = "UTC",
    spend_cap: SpendCap | None = None,
    keeper: Keeper | None = None,
    owner_senders: frozenset[str] = frozenset(),
    wake_context: Callable[[AssistantRecord, list[Message]], Awaitable[dict[str, Any] | None]]
    | None = None,
) -> None:
    if run_timeout_s is not None and run_timeout_s <= 0:
        raise ValueError("run_timeout_s must be positive or None")
    if view_context_timeout_s is not None and view_context_timeout_s <= 0:
        raise ValueError("view_context_timeout_s must be positive or None")
    self._db_path = db_path
    self._factory = factory
    self._contracts = contracts if contracts is not None else ContractRegistry()
    self._memory = memory
    self._bus = bus
    self._clock = clock
    self._model = model
    self._model_for = model_for
    self._usage_limits = usage_limits
    self._budget = UsageLedger(daily_token_budget, budget_tz)
    self._spend = SpendLedger(spend_cap, budget_tz) if spend_cap is not None else None
    self._wake_context = wake_context
    self._keeper = keeper
    self._owner_senders = owner_senders
    self._max_attempts = max_attempts
    self._backoff_base_s = backoff_base_s
    self._run_timeout_s = run_timeout_s
    self._ui_registry = ui_registry if ui_registry is not None else default_registry()
    budgets = [t for t in (view_context_timeout_s, run_timeout_s) if t is not None]
    self._view_context = SafeViewContext(view_context, min(budgets) if budgets else None)
    self._view_svc = ViewService(
        self._ui_registry, self._view_context, bus, run_timeout_s, default_views
    )
    self._live = self._view_svc.live  # the last-emitted cache (inspected by tests)
    self._db: aiosqlite.Connection | None = None
    self._inbox: Inbox | None = None
    self._store: AssistantStore | None = None
    self._scheduler: Scheduler | None = None
    self._views: ViewStore | None = None
    self._artifacts: ArtifactStore | None = None
    self._purge_pending = False
    self._handlers: dict[str, CodeHandler] = {}
    self._locks: dict[str, asyncio.Lock] = {}
    self._warned_blockers: set[tuple[str, ...]] = set()
inbox property
inbox: Inbox

The message inbox, for read-only inspection by tests and admin views.

Calls on it bypass the runtime's transaction lock, so they may observe a concurrently running tick's uncommitted writes. Do not write through it.

__aenter__ async
__aenter__() -> Self

Open the database and recover messages interrupted by a crash.

An interrupted (processing) message that has used all max_attempts crashed the runtime on its last attempt: it is dead-lettered (assistant.message.dead). Others return to pending.

Source code in orqest/assistants/runtime.py
async def __aenter__(self) -> Self:
    """Open the database and recover messages interrupted by a crash.

    An interrupted (``processing``) message that has used all
    ``max_attempts`` crashed the runtime on its last attempt: it is
    dead-lettered (``assistant.message.dead``). Others return to pending.
    """
    self._db = await open_db(self._db_path)
    self._inbox = Inbox(self._db)
    self._store = AssistantStore(self._db)
    self._scheduler = Scheduler(self._db, self._inbox, self._store)
    self._views = ViewStore(self._db)
    self._artifacts = ArtifactStore(self._db, self._views, self._ui_registry)
    try:
        async with transaction(self._db):
            dead = await self._inbox.fail_exhausted(self._max_attempts)
            await self._budget.load(self._db, self._clock())
            if self._spend is not None:
                await self._spend.load(self._db, self._clock())
            await self._inbox.recover()
            for retired in await self._store.list(status="retired"):
                await self._inbox.fail_pending(retired.address, "recipient retired")
    except BaseException:
        await self._close()
        raise
    for msg in dead:
        await self._emit_dead(msg.recipient, msg, msg.last_error or "")
    await truncate_wal(self._db)  # a purge a previous run left pending; one try
    return self
__aexit__ async
__aexit__(*exc_info: object) -> None

Close the database. Handlers are unbound (re-register on every start).

Source code in orqest/assistants/runtime.py
async def __aexit__(self, *exc_info: object) -> None:
    """Close the database. Handlers are unbound (re-register on every start)."""
    await self._close()
get async
get(address: str) -> AssistantRecord

Fetch an assistant record.

Raises:

Type Description
UnknownRecipient

If no assistant has this address.

Source code in orqest/assistants/runtime.py
async def get(self, address: str) -> AssistantRecord:
    """Fetch an assistant record.

    Raises:
        UnknownRecipient: If no assistant has this address.
    """
    db, _, store = self._conn()
    async with transaction(db):
        record = await store.get(address)
    if record is None:
        raise UnknownRecipient(address)
    return record
register_code async
register_code(
    address: str,
    handler: CodeHandler,
    *,
    state_schema: dict[str, Any] | None = None,
    initial_state: dict[str, Any] | None = None,
) -> None

Bind an in-process handler, creating the code record if missing.

An existing record keeps its persisted state and schema; only the handler is bound (a warning is logged if a different state_schema is passed). Handlers live in memory, so register on every start.

Raises:

Type Description
ValueError

If the address is invalid or belongs to an llm assistant.

StateValidationError

If a new record's initial state is not strict JSON or violates the schema.

Source code in orqest/assistants/runtime.py
async def register_code(
    self,
    address: str,
    handler: CodeHandler,
    *,
    state_schema: dict[str, Any] | None = None,
    initial_state: dict[str, Any] | None = None,
) -> None:
    """Bind an in-process handler, creating the ``code`` record if missing.

    An existing record keeps its persisted state and schema; only the
    handler is bound (a warning is logged if a different ``state_schema``
    is passed). Handlers live in memory, so register on every start.

    Raises:
        ValueError: If the address is invalid or belongs to an llm assistant.
        StateValidationError: If a new record's initial state is not strict
            JSON or violates the schema.
    """
    check_identifier(address, kind="address")
    db, _, store = self._conn()
    state = dict(initial_state or {})
    async with transaction(db):
        existing = await store.get(address)
        if existing is None:
            if state_schema is not None:
                Draft202012Validator.check_schema(state_schema)
            state = check_persistable_state(state, state_schema)
            await store.insert(
                AssistantRecord(
                    address=address,
                    kind="code",
                    status="active",
                    version=1,
                    state=state,
                    state_schema=state_schema,
                )
            )
        elif existing.kind != "code":
            raise ValueError(f"assistant {address!r} is a {existing.kind!r} assistant")
        elif state_schema is not None and state_schema != existing.state_schema:
            logger.warning(
                "code assistant {a!r} keeps its stored state_schema; the different"
                " state_schema passed to register_code is ignored",
                a=address,
            )
    self._handlers[address] = handler
create async
create(
    address: str, spec: AssistantSpec
) -> AssistantRecord

Create an llm assistant from a spec.

Inserts the record (state = spec.initial_state), snapshots the spec version and installs the spec's wakes, all in one transaction, then emits assistant.lifecycle with action="create".

Returns:

Type Description
AssistantRecord

The created record.

Raises:

Type Description
RuntimeError

If the runtime has no agent factory.

ValueError

If the address is invalid, taken or in owner_senders, an allowed_contracts ref is not registered, or the allowed contracts cannot become distinct tools (name collision, name over 64 characters, non-object payload schema).

StateValidationError

If spec.initial_state is not strict JSON (e.g. holds NaN).

Source code in orqest/assistants/runtime.py
async def create(self, address: str, spec: AssistantSpec) -> AssistantRecord:
    """Create an llm assistant from a spec.

    Inserts the record (state = ``spec.initial_state``), snapshots the spec
    version and installs the spec's wakes, all in one transaction, then
    emits ``assistant.lifecycle`` with ``action="create"``.

    Returns:
        The created record.

    Raises:
        RuntimeError: If the runtime has no agent factory.
        ValueError: If the address is invalid, taken or in ``owner_senders``, an
            ``allowed_contracts`` ref is not registered, or the allowed
            contracts cannot become distinct tools (name collision, name
            over 64 characters, non-object payload schema).
        StateValidationError: If ``spec.initial_state`` is not strict JSON
            (e.g. holds NaN).
    """
    if self._factory is None:
        raise RuntimeError("create() needs an AgentFactory; pass factory= to AssistantRuntime")
    check_identifier(address, kind="address")
    if address in self._owner_senders:
        raise ValueError(f"{address!r} is an owner sender: its messages would be the owner's")
    check_spec_contracts(spec, self._contracts)
    db, _, store = self._conn()
    state = check_persistable_state(dict(spec.initial_state), spec.state_schema)
    record = AssistantRecord(
        address=address,
        kind="llm",
        status="active",
        version=spec.version,
        spec=spec,
        state=state,
        state_schema=spec.state_schema,
    )
    async with transaction(db):
        await store.insert(record)  # ValueError if the address exists
        await store.save_version(address, spec.version, spec, state)
        await self._sched().sync_spec_wakes(address, spec.schedule, self._clock())
    await self._emit_lifecycle(address, "create", spec.version)
    return record
pause async
pause(address: str) -> None

Stop processing an assistant until :meth:resume.

Its pending messages wait; recurring wakes are skipped, once wakes are enqueued and wait in the inbox. Waits for an in-flight run of the assistant to finish.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or retired.

RuntimeError

If called from inside this assistant's own run.

Source code in orqest/assistants/runtime.py
async def pause(self, address: str) -> None:
    """Stop processing an assistant until :meth:`resume`.

    Its pending messages wait; recurring wakes are skipped, ``once`` wakes
    are enqueued and wait in the inbox. Waits for an in-flight run of the
    assistant to finish.

    Raises:
        UnknownRecipient: If the assistant is missing or retired.
        RuntimeError: If called from inside this assistant's own run.
    """
    await self._set_status(address, "paused", "pause")
resume async
resume(address: str) -> None

Resume a paused assistant.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or retired.

RuntimeError

If called from inside this assistant's own run.

Source code in orqest/assistants/runtime.py
async def resume(self, address: str) -> None:
    """Resume a paused assistant.

    Raises:
        UnknownRecipient: If the assistant is missing or retired.
        RuntimeError: If called from inside this assistant's own run.
    """
    await self._set_status(address, "active", "resume")
retire async
retire(address: str) -> None

Retire an assistant permanently.

Pending messages become failed (last_error="recipient retired") and its wakes go inactive. Retired is terminal.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or already retired.

RuntimeError

If called from inside this assistant's own run.

Source code in orqest/assistants/runtime.py
async def retire(self, address: str) -> None:
    """Retire an assistant permanently.

    Pending messages become ``failed`` (``last_error="recipient retired"``)
    and its wakes go inactive. Retired is terminal.

    Raises:
        UnknownRecipient: If the assistant is missing or already retired.
        RuntimeError: If called from inside this assistant's own run.
    """
    await self._set_status(address, "retired", "retire")
redesign async
redesign(
    address: str,
    spec: AssistantSpec,
    *,
    migrate: Callable[
        [dict[str, Any]],
        dict[str, Any] | Awaitable[dict[str, Any]],
    ]
    | None = None,
) -> AssistantRecord

Replace an llm assistant's spec with the next version, migrating its state.

The new state is migrate(old_state) (default: unchanged; migrate may be sync or async) and must satisfy spec.state_schema. The current state is read and migrated while the address lock is held, so no run of this assistant can commit in between; the new spec, state, version snapshot and wakes are then written in one transaction. A failure anywhere leaves everything as it was.

Returns:

Type Description
AssistantRecord

The updated record.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or retired.

TypeError

If the assistant is a code assistant.

ValueError

If spec.version is not current + 1 or an allowed contract is not registered.

StateValidationError

If the migrated state is invalid.

RuntimeError

If called from inside this assistant's own run.

Source code in orqest/assistants/runtime.py
async def redesign(
    self,
    address: str,
    spec: AssistantSpec,
    *,
    migrate: Callable[[dict[str, Any]], dict[str, Any] | Awaitable[dict[str, Any]]]
    | None = None,
) -> AssistantRecord:
    """Replace an llm assistant's spec with the next version, migrating its state.

    The new state is ``migrate(old_state)`` (default: unchanged; ``migrate``
    may be sync or async) and must satisfy ``spec.state_schema``. The
    current state is read and migrated while the address lock is held, so
    no run of this assistant can commit in between; the new spec, state,
    version snapshot and wakes are then written in one transaction. A
    failure anywhere leaves everything as it was.

    Returns:
        The updated record.

    Raises:
        UnknownRecipient: If the assistant is missing or retired.
        TypeError: If the assistant is a code assistant.
        ValueError: If ``spec.version`` is not ``current + 1`` or an
            allowed contract is not registered.
        StateValidationError: If the migrated state is invalid.
        RuntimeError: If called from inside this assistant's own run.
    """
    self._check_not_own_run(address, "redesign")
    db, _, store = self._conn()
    async with self._lock_for(address):
        async with transaction(db):
            record = await self._active_record(store, address)
        if record.kind != "llm":
            raise TypeError(f"{address!r} is a code assistant; it has no spec to redesign")
        if spec.version != record.version + 1:
            raise ValueError(f"spec.version must be {record.version + 1}, got {spec.version}")
        check_spec_contracts(spec, self._contracts)
        # Migrate outside any transaction (it may be slow or async); the
        # address lock keeps runs and other lifecycle calls out meanwhile.
        old = json_roundtrip(record.state, "state")
        migrated = old if migrate is None else migrate(old)
        if inspect.isawaitable(migrated):
            migrated = await migrated
        new_state = check_persistable_state(migrated, spec.state_schema)
        async with transaction(db):
            await self._view_store().snapshot(address, record.version)
            await store.replace_spec(address, spec, new_state)
            await store.save_version(address, spec.version, spec, new_state)
            await self._sched().sync_spec_wakes(address, spec.schedule, self._clock())
        await self._emit_views(address, [])  # under the lock, outside the transaction
    await self._emit_lifecycle(address, "redesign", spec.version)
    return record.with_spec(spec, new_state)
rollback async
rollback(address: str, version: int) -> AssistantRecord

Restore an old version's spec and state as a new version.

History stays append-only: the old content is copied to current + 1.

Returns:

Type Description
AssistantRecord

The updated record.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or retired.

TypeError

If the assistant is a code assistant.

ValueError

If version was never saved.

RuntimeError

If called from inside this assistant's own run.

Source code in orqest/assistants/runtime.py
async def rollback(self, address: str, version: int) -> AssistantRecord:
    """Restore an old version's spec and state as a new version.

    History stays append-only: the old content is copied to
    ``current + 1``.

    Returns:
        The updated record.

    Raises:
        UnknownRecipient: If the assistant is missing or retired.
        TypeError: If the assistant is a code assistant.
        ValueError: If ``version`` was never saved.
        RuntimeError: If called from inside this assistant's own run.
    """
    self._check_not_own_run(address, "rollback")
    db, _, store = self._conn()
    async with self._lock_for(address):
        async with transaction(db):
            record = await self._active_record(store, address)
            if record.kind != "llm":
                raise TypeError(
                    f"{address!r} is a code assistant; it has no versions to roll back"
                )
            saved = await store.get_version(address, version)
            if saved is None or saved[0] is None:
                raise ValueError(f"{address!r} has no version {version}")
            old_spec, old_state = saved
            new_version = record.version + 1
            spec = old_spec.model_copy(update={"version": new_version})
            check_spec_contracts(spec, self._contracts)
            await self._view_store().snapshot(address, record.version)
            await self._view_store().restore(address, version)
            await store.replace_spec(address, spec, old_state)
            await store.save_version(address, new_version, spec, old_state)
            await self._sched().sync_spec_wakes(address, spec.schedule, self._clock())
        await self._emit_views(address, [])  # under the lock, outside the transaction
    await self._emit_lifecycle(address, "rollback", new_version)
    return record.with_spec(spec, old_state)
send async
send(
    sender: str,
    recipient: str,
    message_type: str,
    payload: dict[str, Any],
    *,
    reply_to: str | None = None,
) -> str

Enqueue a message to an existing, non-retired assistant.

Returns:

Type Description
str

The new message id.

Raises:

Type Description
UnknownRecipient

If the recipient is missing or retired.

ContractViolation

If the recipient's contracts reject the message.

Source code in orqest/assistants/runtime.py
async def send(
    self,
    sender: str,
    recipient: str,
    message_type: str,
    payload: dict[str, Any],
    *,
    reply_to: str | None = None,
) -> str:
    """Enqueue a message to an existing, non-retired assistant.

    Returns:
        The new message id.

    Raises:
        UnknownRecipient: If the recipient is missing or retired.
        ContractViolation: If the recipient's contracts reject the message.
    """
    db, inbox, store = self._conn()
    now = self._clock()
    msg = Message(
        sender=sender,
        recipient=recipient,
        type=message_type,
        payload=payload,
        reply_to=reply_to,
        available_at=now,
        created_at=now,
    )
    async with transaction(db):
        status = await store.get_status(recipient)
        if status is None or status == "retired":
            raise UnknownRecipient(recipient)
        self._contracts.validate(recipient, message_type, payload)
        return await inbox.enqueue(msg)
is_owner_turn async
is_owner_turn(
    message_id: str,
    owner_senders: frozenset[str] | None = None,
) -> bool

Whether message_id is the owner's turn in progress.

What to wire into :class:~orqest.compartments.Keeper's is_owner_turn. True only for an existing message whose sender is in owner_senders (by default the constructor's) and that an assistant is processing right now, so neither a message already handled nor one still waiting counts.

Source code in orqest/assistants/runtime.py
async def is_owner_turn(
    self, message_id: str, owner_senders: frozenset[str] | None = None
) -> bool:
    """Whether ``message_id`` is the owner's turn in progress.

    What to wire into :class:`~orqest.compartments.Keeper`'s ``is_owner_turn``.
    True only for an existing message whose sender is in ``owner_senders`` (by
    default the constructor's) and that an assistant is processing right now, so
    neither a message already handled nor one still waiting counts.
    """
    if owner_senders is None:
        owner_senders = self._owner_senders
    db, inbox, _ = self._conn()
    async with transaction(db):
        message = await inbox.get(message_id)
    return (
        message is not None
        and message.status == "processing"
        and message.sender in owner_senders
    )
list_artifacts async
list_artifacts(
    *, status: set[str] | None = None
) -> list[ArtifactMeta]

Artifacts of every assistant, newest-updated first.

Parameters:

Name Type Description Default
status set[str] | None

Only artifacts with one of these statuses (active, pinned, dismissed, expired); all when None.

None
Source code in orqest/assistants/runtime.py
async def list_artifacts(self, *, status: set[str] | None = None) -> list[ArtifactMeta]:
    """Artifacts of every assistant, newest-updated first.

    Args:
        status: Only artifacts with one of these statuses (``active``, ``pinned``,
            ``dismissed``, ``expired``); all when ``None``.
    """
    db, _, _ = self._conn()
    async with transaction(db):
        return await self._artifact_store().list(status=status)
search_artifacts async
search_artifacts(
    query: str, *, limit: int = 20
) -> list[ArtifactMeta]

Artifacts of any status whose title and intent contain every word of query.

Matching ignores case and compatibility forms (NFKC); at most 20 words and 1000 characters of the query count, limit is clamped to 1..100, and a query that isn't valid text finds nothing.

Source code in orqest/assistants/runtime.py
async def search_artifacts(self, query: str, *, limit: int = 20) -> list[ArtifactMeta]:
    """Artifacts of any status whose title and intent contain every word of ``query``.

    Matching ignores case and compatibility forms (NFKC); at most 20 words and 1000
    characters of the query count, ``limit`` is clamped to 1..100, and a query that
    isn't valid text finds nothing.
    """
    db, _, _ = self._conn()
    async with transaction(db):
        return await self._artifact_store().search(query, limit=limit)
pin_artifact async
pin_artifact(
    address: str, artifact_id: str, pinned: bool
) -> ArtifactMeta

Pin address's artifact (it then never expires) or unpin it.

Any artifact can be pinned, a dismissed or expired one keeping what it showed. Unpinning one that isn't pinned does nothing. Unpinning a pinned one returns a frozen one to dismissed and a live one to active, with the deadline it had, so one whose time passed expires at the next poll.

Raises:

Type Description
UnknownArtifact

If the assistant has no such artifact.

Source code in orqest/assistants/runtime.py
async def pin_artifact(self, address: str, artifact_id: str, pinned: bool) -> ArtifactMeta:
    """Pin ``address``'s artifact (it then never expires) or unpin it.

    Any artifact can be pinned, a dismissed or expired one keeping what it showed.
    Unpinning one that isn't pinned does nothing. Unpinning a pinned one returns a
    frozen one to ``dismissed`` and a live one to ``active``, with the deadline it
    had, so one whose time passed expires at the next poll.

    Raises:
        UnknownArtifact: If the assistant has no such artifact.
    """
    db, _, _ = self._conn()
    async with transaction(db):
        meta, changed = await self._artifact_store().set_pinned(
            address, artifact_id, pinned, self._clock()
        )
    if changed:
        await self._emit_artifacts([ArtifactChange(event_type="ui.artifact.pin", meta=meta)])
    return meta
delete_artifact async
delete_artifact(address: str, artifact_id: str) -> None

Remove address's artifact for real: row, search text, snapshot and view.

For the owner (the application), not a model tool. The freed pages are zeroed and the write-ahead log truncated, so the text is gone from the file. Emits ui.artifact.delete. Waits for an in-flight run of the assistant.

The truncation waits only briefly. If another connection keeps the log in use, the call still succeeds, because the row is gone, but the text stays in the log: a warning names the artifact, and the truncation is retried on every poll (tick() / run_forever) until it succeeds, and once at the next open.

A retired assistant's screens aren't emitted again: only ui.artifact.delete.

Raises:

Type Description
UnknownArtifact

If the assistant has no such artifact.

RuntimeError

If called from inside this assistant's own run.

Source code in orqest/assistants/runtime.py
async def delete_artifact(self, address: str, artifact_id: str) -> None:
    """Remove ``address``'s artifact for real: row, search text, snapshot and view.

    For the owner (the application), not a model tool. The freed pages are zeroed
    and the write-ahead log truncated, so the text is gone from the file. Emits
    ``ui.artifact.delete``. Waits for an in-flight run of the assistant.

    The truncation waits only briefly. If another connection keeps the log in use,
    the call still succeeds, because the row is gone, but the text stays in the log:
    a warning names the artifact, and the truncation is retried on every poll
    (``tick()`` / ``run_forever``) until it succeeds, and once at the next open.

    A retired assistant's screens aren't emitted again: only ``ui.artifact.delete``.

    Raises:
        UnknownArtifact: If the assistant has no such artifact.
        RuntimeError: If called from inside this assistant's own run.
    """
    self._check_not_own_run(address, "delete an artifact of")
    db, _, store = self._conn()
    async with self._lock_for(address):
        async with transaction(db):
            meta = await self._artifact_store().get(address, artifact_id)
            if meta is None:
                raise UnknownArtifact(artifact_id)
            await self._artifact_store().delete(address, artifact_id)
            status = await store.get_status(address)
        if not await self._truncate_wal():
            logger.warning(
                "artifact {i!r} of {a!r} deleted; purge pending: its text stays in the"
                " write-ahead log until a truncating checkpoint can run",
                i=artifact_id,
                a=address,
            )
        if status != "retired":
            await self._emit_views(address, [])
    await self._emit_artifacts([ArtifactChange(event_type="ui.artifact.delete", meta=meta)])
artifact_action async
artifact_action(
    address: str,
    artifact_id: str,
    action: str,
    value: dict[str, Any],
    *,
    sender: str,
) -> str

Send a user action on address's artifact to that assistant.

Refuses an action the artifact doesn't list in allowed_actions and any action on a frozen artifact (dismissed, expired, or retired with it), so a stale tap never reaches the assistant. Otherwise sends it a ui.action message {artifact_id, action, value}, so voice and touch reach the same place. An assistant whose address has registered contracts must list ui.action there.

sender is taken as given and is not checked against owner_senders: a voice or touch action counts as an owner turn only if the application passes a verified owner sender. Pass anything else and the assistant sees an ordinary message.

Returns:

Type Description
str

The new message id.

Raises:

Type Description
UnknownArtifact

If the assistant has no such artifact.

ValueError

If the action isn't allowed or the artifact is frozen.

TypeError

If value is not a dict.

ContractViolation

If the assistant's contracts reject ui.action.

UnknownRecipient

If the assistant is retired.

Source code in orqest/assistants/runtime.py
async def artifact_action(
    self, address: str, artifact_id: str, action: str, value: dict[str, Any], *, sender: str
) -> str:
    """Send a user action on ``address``'s artifact to that assistant.

    Refuses an action the artifact doesn't list in ``allowed_actions`` and any action
    on a frozen artifact (dismissed, expired, or retired with it), so a stale tap
    never reaches the assistant. Otherwise sends it a ``ui.action`` message
    ``{artifact_id, action, value}``, so voice and touch reach the same place. An
    assistant whose address has registered contracts must list ``ui.action`` there.

    ``sender`` is taken as given and is not checked against ``owner_senders``: a
    voice or touch action counts as an owner turn only if the application passes a
    verified owner sender. Pass anything else and the assistant sees an ordinary
    message.

    Returns:
        The new message id.

    Raises:
        UnknownArtifact: If the assistant has no such artifact.
        ValueError: If the action isn't allowed or the artifact is frozen.
        TypeError: If ``value`` is not a dict.
        ContractViolation: If the assistant's contracts reject ``ui.action``.
        UnknownRecipient: If the assistant is retired.
    """
    if not isinstance(value, dict):
        raise TypeError(f"value must be a dict, got {type(value).__name__}")
    db, _, _ = self._conn()
    async with transaction(db):
        meta = await self._artifact_store().get(address, artifact_id)
    if meta is None:
        raise UnknownArtifact(artifact_id)
    if meta.frozen:
        raise ValueError(f"artifact {artifact_id!r} is no longer on screen ({meta.status})")
    if action not in meta.allowed_actions:
        raise ValueError(f"action {action!r} is not allowed on artifact {artifact_id!r}")
    payload = {"artifact_id": artifact_id, "action": action, "value": value}
    return await self.send(sender, address, "ui.action", payload)
schedule_once async
schedule_once(
    address: str, at: datetime, reason: str
) -> str

Persist a one-shot wake for an assistant.

Returns:

Type Description
str

The wake id.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or retired.

ValueError

If at is not timezone-aware.

Source code in orqest/assistants/runtime.py
async def schedule_once(self, address: str, at: datetime, reason: str) -> str:
    """Persist a one-shot wake for an assistant.

    Returns:
        The wake id.

    Raises:
        UnknownRecipient: If the assistant is missing or retired.
        ValueError: If ``at`` is not timezone-aware.
    """
    if at.tzinfo is None or at.utcoffset() is None:
        raise ValueError("'at' must be timezone-aware")
    db, _, store = self._conn()
    now = self._clock()
    async with transaction(db):
        status = await store.get_status(address)
        if status is None or status == "retired":
            raise UnknownRecipient(address)
        return await self._sched().add_once(
            address, Wake(kind="once", at=at, reason=reason), now
        )
tick async
tick() -> int

Process due messages for every runnable recipient once.

Recipients are chosen at the start of the tick, so a recipient first messaged during this tick runs on a later one. Different recipients run concurrently, and the tick returns when the slowest has finished. A code assistant's due messages run in FIFO order, claimed and committed one at a time, at most 20 per tick. An llm assistant claims its due batch (at most 20) and handles it in one model run committed as one unit. Each run is bounded by run_timeout_s; with a bus set, live views are emitted after every commit, each emission bounded by another run_timeout_s. Handler and model exceptions (including a timeout, or a CancelledError that is not a cancellation of the tick) are retried or dead-lettered (for every message of the batch) and never escape. A recipient whose record cannot be decoded is skipped (logged once); its messages wait.

Returns:

Type Description
int

The number of messages completed.

Raises:

Type Description
BaseException

A BaseException from a handler propagates unchanged (the crash path; the in-flight message stays processing until :meth:Inbox.recover on the next start).

Exception

Errors from the runtime's own commit or fail transactions (database errors) propagate too. This is crash-early: the run loop treats them as fatal. Everything is rolled back and the in-flight message is recovered on restart.

Source code in orqest/assistants/runtime.py
async def tick(self) -> int:
    """Process due messages for every runnable recipient once.

    Recipients are chosen at the start of the tick, so a recipient first
    messaged during this tick runs on a later one. Different recipients run
    concurrently, and the tick returns when the slowest has finished. A
    code assistant's due messages run in FIFO order, claimed and committed
    one at a time, at most 20 per tick. An llm assistant claims its due
    batch (at most 20) and handles it in one model run committed as one
    unit. Each run is bounded by ``run_timeout_s``; with a bus set, live
    views are emitted after every commit, each emission bounded by
    another ``run_timeout_s``. Handler and model exceptions (including a
    timeout, or a ``CancelledError`` that is not a cancellation of the
    tick) are retried or dead-lettered (for every message of the batch)
    and never escape. A recipient whose record cannot be decoded is
    skipped (logged once); its messages wait.

    Returns:
        The number of messages completed.

    Raises:
        BaseException: A ``BaseException`` from a handler propagates
            unchanged (the crash path; the in-flight message stays
            ``processing`` until :meth:`Inbox.recover` on the next start).
        Exception: Errors from the runtime's own commit or fail
            transactions (database errors) propagate too. This is
            crash-early: the run loop treats them as fatal. Everything is
            rolled back and the in-flight message is recovered on restart.
    """
    now = self._clock()
    runnable = await self._due_runnable(now)
    tasks = [asyncio.create_task(self._run_recipient(a, now)) for a in runnable]
    try:
        counts = await asyncio.gather(*tasks)
    except BaseException:
        # One run crashed: stop the others so nothing touches the
        # connection after tick() returns (their messages stay in
        # ``processing`` until ``recover()`` on the next start).
        for t in tasks:
            t.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)
        raise
    return sum(counts)
run_forever async
run_forever(poll_interval_s: float = 0.5) -> None

Process messages until cancelled, one worker task per recipient.

Unlike :meth:tick, a slow recipient never delays the others: each runnable recipient with due messages gets its own worker (one run, as in a tick), never two at once. The loop sleeps up to poll_interval_s only when no worker started or finished, or the finished ones completed nothing (see :func:~orqest.assistants.workers.supervise), so a backlog drains without delay. Cancelling it cancels and awaits every worker, then the CancelledError propagates; cancel it before leaving the runtime's async with. It starts by returning every processing message to pending, so restarting it in the same open runtime resumes what a cancelled or crashed loop left in flight; never run it alongside :meth:tick or a second run_forever.

Raises:

Type Description
BaseException

Fatal errors, as for :meth:tick (a handler's BaseException, the runtime's own transaction errors, a worker cancelled while the loop is not), after every other worker is cancelled and awaited.

Source code in orqest/assistants/runtime.py
async def run_forever(self, poll_interval_s: float = 0.5) -> None:
    """Process messages until cancelled, one worker task per recipient.

    Unlike :meth:`tick`, a slow recipient never delays the others: each
    runnable recipient with due messages gets its own worker (one run, as
    in a tick), never two at once. The loop sleeps up to
    ``poll_interval_s`` only when no worker started or finished, or the
    finished ones completed nothing (see :func:`~orqest.assistants.workers.supervise`),
    so a backlog drains without delay. Cancelling it cancels and awaits
    every worker, then the ``CancelledError`` propagates; cancel it before
    leaving the runtime's ``async with``. It starts by returning every
    ``processing`` message to ``pending``, so restarting it in the same
    open runtime resumes what a cancelled or crashed loop left in flight;
    never run it alongside :meth:`tick` or a second ``run_forever``.

    Raises:
        BaseException: Fatal errors, as for :meth:`tick` (a handler's
            ``BaseException``, the runtime's own transaction errors, a
            worker cancelled while the loop is not), after every other
            worker is cancelled and awaited.
    """
    db, inbox, _ = self._conn()
    async with transaction(db):
        await inbox.recover()
    await supervise(
        self._due_runnable,
        self._run_recipient,
        self._clock,
        poll_interval_s,
        redact=self._keeper is not None,
    )
spend_blocker
spend_blocker(
    address: str, now: datetime | None = None
) -> str | None

:data:~orqest.assistants.spend.SPEND_EXHAUSTED if the day is used up for address.

The same rule as assistant.spend.exhausted: spent + run_reserve passes its limit (the cap, or outside priority the cap less the reserve). Amounts held for runs in flight are ignored, so an application can use it to refuse a direct model call or to say the budget is used without a passing run making that false; only the start of an llm run counts those holds. None without a spend_cap. Synchronous; now defaults to the runtime's clock.

Source code in orqest/assistants/runtime.py
def spend_blocker(self, address: str, now: datetime | None = None) -> str | None:
    """:data:`~orqest.assistants.spend.SPEND_EXHAUSTED` if the day is used up for ``address``.

    The same rule as ``assistant.spend.exhausted``: ``spent + run_reserve``
    passes its limit (the cap, or outside ``priority`` the cap less the
    reserve). Amounts held for runs in flight are ignored, so an application
    can use it to refuse a direct model call or to say the budget is used
    without a passing run making that false; only the start of an llm run
    counts those holds. ``None`` without a ``spend_cap``. Synchronous;
    ``now`` defaults to the runtime's clock.
    """
    if self._spend is None:
        return None
    return SPEND_EXHAUSTED if self._spend_exhausted(address, now or self._clock()) else None
charge async
charge(
    address: str, usage: RunUsage, model_name: str | None
) -> float

Charge a model call made outside an llm wake to address.

Adds the tokens to its daily token budget and the priced amount to the spend. Safe to call from inside a code handler (it runs outside the wake's transaction).

Returns:

Type Description
float

The amount charged (0.0 without a spend_cap).

Raises:

Type Description
Exception

A failed write propagates, but the amount still counts in this process (the in-memory mirrors were updated first; a restart loses it). A code handler that lets it propagate is retried, and so charges again.

Source code in orqest/assistants/runtime.py
async def charge(self, address: str, usage: RunUsage, model_name: str | None) -> float:
    """Charge a model call made outside an llm wake to ``address``.

    Adds the tokens to its daily token budget and the priced amount to the
    spend. Safe to call from inside a code handler (it runs outside the
    wake's transaction).

    Returns:
        The amount charged (``0.0`` without a ``spend_cap``).

    Raises:
        Exception: A failed write propagates, but the amount still counts in
            this process (the in-memory mirrors were updated first; a restart
            loses it). A code handler that lets it propagate is retried, and
            so charges again.
    """
    db, now = self._conn()[0], self._clock()
    amount, error = 0.0, None
    if self._spend is not None:
        try:
            amount = await self._spend.record(db, address, now, usage, model_name)
        except Exception as exc:
            error = exc
    try:
        await self._budget.record(db, address, now, usage)
    except Exception as exc:
        error = error or exc
    if error is not None:
        raise error
    return amount
spend_today async
spend_today() -> SpendSummary | None

Today's spend by address, or None without a spend_cap.

Source code in orqest/assistants/runtime.py
async def spend_today(self) -> SpendSummary | None:
    """Today's spend by address, or ``None`` without a ``spend_cap``."""
    return None if self._spend is None else self._spend.summary(self._clock())
render_view async
render_view(address: str, name: str) -> ViewSnapshot

Snapshot one view for a renderer that is (re)loading.

The last-emitted resolution and its event seq (so a renderer that subscribed first can apply exactly the events after it), else a fresh resolution with seq 0; see :meth:~orqest.assistants.live_views.ViewService.render.

A name with the artifact prefix gets a frozen artifact's snapshot or a live artifact's view, and never a fallback view of the raw state.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or retired, and the name is not that of a frozen artifact.

UnknownArtifact

If the name has the artifact prefix and no such artifact can be shown (unknown, deleted, or its view or snapshot can't be decoded).

ValueError

If no view is stored and name is not a valid view name.

Source code in orqest/assistants/runtime.py
async def render_view(self, address: str, name: str) -> ViewSnapshot:
    """Snapshot one view for a renderer that is (re)loading.

    The last-emitted resolution and its event ``seq`` (so a renderer that
    subscribed first can apply exactly the events after it), else a fresh
    resolution with ``seq`` 0; see
    :meth:`~orqest.assistants.live_views.ViewService.render`.

    A name with the artifact prefix gets a frozen artifact's snapshot or a live
    artifact's view, and never a fallback view of the raw state.

    Raises:
        UnknownRecipient: If the assistant is missing or retired, and the name is not
            that of a frozen artifact.
        UnknownArtifact: If the name has the artifact prefix and no such artifact can
            be shown (unknown, deleted, or its view or snapshot can't be decoded).
        ValueError: If no view is stored and ``name`` is not a valid view name.
    """
    db, _, store = self._conn()
    prefix = ARTIFACT_VIEW_PREFIX
    artifact_id = name.removeprefix(prefix) if name.startswith(prefix) else None
    async with transaction(db):
        frozen = (
            await self._artifact_store().snapshot(address, artifact_id)
            if artifact_id is not None
            else None
        )
        if frozen is None:
            record = await self._active_record(store, address)
            spec = await self._view_store().get(address, name)
    if frozen is not None:
        return ViewSnapshot(resolved=frozen, seq=0)
    if artifact_id is not None and spec is None:
        raise UnknownArtifact(artifact_id)
    return await self._view_svc.render(record, name, spec)
list_views async
list_views(address: str) -> list[str]

Names of address's views (stored, plus default fallbacks for llm), sorted.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or retired.

Source code in orqest/assistants/runtime.py
async def list_views(self, address: str) -> list[str]:
    """Names of ``address``'s views (stored, plus default fallbacks for llm), sorted.

    Raises:
        UnknownRecipient: If the assistant is missing or retired.
    """
    db, _, store = self._conn()
    async with transaction(db):
        record = await self._active_record(store, address)
        stored = await self._view_store().list(address)
    return [v.name for v in self._view_svc.effective(stored, record.kind)]
refresh_views async
refresh_views(address: str) -> None

Re-resolve address's views and emit what changed, as after a commit.

For bindings fed by view_context data that changed outside any run. Takes the address lock (so it waits for an in-flight run) and emits best-effort like a commit does; without a bus it only checks the address.

Raises:

Type Description
UnknownRecipient

If the assistant is missing or retired.

RuntimeError

If called from inside this assistant's own run.

Source code in orqest/assistants/runtime.py
async def refresh_views(self, address: str) -> None:
    """Re-resolve ``address``'s views and emit what changed, as after a commit.

    For bindings fed by ``view_context`` data that changed outside any
    run. Takes the address lock (so it waits for an in-flight run) and
    emits best-effort like a commit does; without a bus it only checks
    the address.

    Raises:
        UnknownRecipient: If the assistant is missing or retired.
        RuntimeError: If called from inside this assistant's own run.
    """
    self._check_not_own_run(address, "refresh the views of")
    db, _, store = self._conn()
    async with self._lock_for(address):
        async with transaction(db):
            await self._active_record(store, address)
        await self._emit_views(address, [])

UnknownRecipient

The addressed assistant does not exist or is retired.

Wake

A declarative wake-up schedule (daily, weekly, or a single instant).

Attributes:

Name Type Description
kind Literal['daily', 'weekly', 'once']

Recurrence kind.

at_time time | None

Local wall-clock time (daily / weekly).

weekday int | None

0=Monday ... 6=Sunday (weekly only).

at datetime | None

Timezone-aware instant (once only).

tz str

IANA timezone name used to interpret at_time.

reason str

Free-form note on why the wake exists.

AssistantSpec

Serializable definition of a durable assistant.

Attributes:

Name Type Description
agent AgentSpec

LLM agent definition; must use output_schema (not output_type) and carry no tools.

state_schema dict[str, Any]

JSON Schema for the assistant's persistent state.

initial_state dict[str, Any]

Starting state; must validate against state_schema.

schedule list[Wake]

Recurring/one-off wakes.

allowed_contracts list[ContractRef]

Contracts the assistant may invoke; its only capability channel besides runtime tools.

version int

Spec version.

daily_token_budget int | None

Tokens (input + output) the assistant may use per day before its messages wait for the next day; None uses the runtime's default.

ContractRef

Reference to a contract an assistant may send to.

SpendCap dataclass

SpendCap(
    daily: float,
    price: Callable[[str | None, RunUsage], float],
    priority: frozenset[str] = frozenset(),
    reserve: float = 0.0,
    run_reserve: float = 0.0,
)

A daily cap on what all assistants spend together.

Orqest does not know a currency: price turns a model name and a run's usage into an amount, and daily is in the same unit.

Parameters:

Name Type Description Default
daily float

Amount per day across all assistants; must be positive.

required
price Callable[[str | None, RunUsage], float]

(model_name, usage) -> amount; model_name is None when no name is known. If it raises (or returns a negative or non-finite number) the rest of the day is charged, so a broken price cannot lift the cap.

required
priority frozenset[str]

Addresses that may spend the reserve.

frozenset()
reserve float

The last part of the day only priority addresses may use.

0.0
run_reserve float

The amount held for each llm run in flight (taken when the run is claimed, released when it is charged). An address is blocked when one more run would not fit: spent + held + run_reserve above its limit. With 0 (the default) only spent counts, so runs that start together may each overshoot; with it set, a run overshoots only by its actual cost above the reservation.

0.0

Raises:

Type Description
ValueError

Unless daily > 0, 0 <= reserve < daily and 0 <= run_reserve <= daily.

SpendSummary

What was spent on one budget day.

AssistantRecord

A stored assistant.

Attributes:

Name Type Description
address str

Unique assistant address.

kind Literal['llm', 'code']

"llm" (spec-driven) or "code" (registered handler).

status AssistantStatus

Lifecycle status.

version int

Current spec version.

spec AssistantSpec | None

The spec for llm assistants; None for code assistants.

state dict[str, Any]

Current persistent state.

state_schema dict[str, Any] | None

JSON Schema for state (mirrors spec.state_schema for llm assistants); None means any dict is accepted.

with_spec
with_spec(
    spec: AssistantSpec, state: dict[str, Any]
) -> AssistantRecord

This record as stored after spec and state replaced its own.

Source code in orqest/assistants/store.py
def with_spec(self, spec: AssistantSpec, state: dict[str, Any]) -> "AssistantRecord":
    """This record as stored after ``spec`` and ``state`` replaced its own."""
    fields = {"version": spec.version, "spec": spec, "state_schema": spec.state_schema}
    return self.model_copy(update={**fields, "state": state})

ViewValidationError

ViewValidationError(name: str, problems: list[str])

A published view has structural problems (unknown block type, invalid data).

Attributes:

Name Type Description
problems

One line per problem, as reported by :func:orqest.ui.view.validate_view.

Parameters:

Name Type Description Default
name str

The view's name.

required
problems list[str]

The problem lines (non-empty).

required
Source code in orqest/assistants/views.py
def __init__(self, name: str, problems: list[str]) -> None:
    self.problems = list(problems)
    super().__init__(f"view {name!r} is invalid: " + "; ".join(self.problems))

merge_patch

merge_patch(
    target: dict[str, Any], patch: dict[str, Any]
) -> dict[str, Any]

Apply an RFC 7386 JSON merge patch and return the result.

None deletes a key, nested dicts merge recursively, and any other value replaces. Neither argument is mutated.

Parameters:

Name Type Description Default
target dict[str, Any]

The document to patch.

required
patch dict[str, Any]

The merge patch.

required

Returns:

Type Description
dict[str, Any]

A new dict with the patch applied.

Source code in orqest/assistants/context.py
def merge_patch(target: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]:
    """Apply an RFC 7386 JSON merge patch and return the result.

    ``None`` deletes a key, nested dicts merge recursively, and any other value
    replaces. Neither argument is mutated.

    Args:
        target: The document to patch.
        patch: The merge patch.

    Returns:
        A new dict with the patch applied.
    """
    result = copy.deepcopy(target)
    for key, value in patch.items():
        if value is None:
            result.pop(key, None)
        elif isinstance(value, dict):
            existing = result.get(key)
            result[key] = merge_patch(existing if isinstance(existing, dict) else {}, value)
        else:
            result[key] = copy.deepcopy(value)
    return result

next_fire

next_fire(
    wake: Wake, after: datetime
) -> dt.datetime | None

Return the next fire time strictly after after as a UTC datetime.

Parameters:

Name Type Description Default
wake Wake

The schedule.

required
after datetime

Timezone-aware reference instant.

required

Returns:

Type Description
datetime | None

A UTC-aware datetime > after, or None for a once wake

datetime | None

that is not in the future.

Source code in orqest/assistants/schedule.py
def next_fire(wake: Wake, after: dt.datetime) -> dt.datetime | None:
    """Return the next fire time strictly after ``after`` as a UTC datetime.

    Args:
        wake: The schedule.
        after: Timezone-aware reference instant.

    Returns:
        A UTC-aware datetime ``> after``, or ``None`` for a ``once`` wake
        that is not in the future.
    """
    if wake.kind == "once":
        assert wake.at is not None
        at = wake.at.astimezone(dt.UTC)
        return at if at > after else None

    assert wake.at_time is not None
    zone = ZoneInfo(wake.tz)
    start = after.astimezone(zone).date()
    for offset in range(_MAX_LOOKAHEAD_DAYS + 1):
        day = start + dt.timedelta(days=offset)
        if wake.kind == "weekly" and day.weekday() != wake.weekday:
            continue
        candidate = dt.datetime.combine(day, wake.at_time, tzinfo=zone).astimezone(dt.UTC)
        if candidate > after:
            return candidate
    raise AssertionError("unreachable: no fire time within lookahead window")