Skip to content

RoomKit

RoomKit

RoomKit(store=None, identity_resolver=None, identity_channel_types=None, inbound_router=None, lock_manager=None, realtime=None, max_chain_depth=5, agent_response_policy=AGENT_CHAIN, identity_timeout=10.0, process_timeout=30.0, stt=None, tts=None, voice=None, task_runner=None, delivery_strategy=None, delivery_backend=None, status_bus=None, telemetry=None, inbound_rate_limit=None, orchestration=None, persistence_policy=None, delivery_gap_timeout=30.0, delivery_claim_lock_manager=None, verification_policy=None, media_resolver=None, attached_media=None, turn_backend=None, error_classes=())

Central orchestrator tying rooms, channels, hooks, and storage.

Initialise the RoomKit orchestrator.

Parameters:

Name Type Description Default
store ConversationStore | None

Persistent storage backend. Defaults to InMemoryStore.

None
identity_resolver IdentityResolver | None

Optional resolver for identifying inbound senders. Without one, an event's participant_id is whatever the channel stamped on it (RFC §11.6) — so it is only as trustworthy as the transport that supplied it, and the edit/delete author check (RFC §10.3) is decided from it. Derive the sender id from an authenticated session rather than a client-supplied field, or install a resolver. See the Security Hardening guide.

None
identity_channel_types set[ChannelType] | None

Restrict identity resolution to specific channel types. If None (default), resolution runs for all channels. Set to e.g. {ChannelType.SMS} to only resolve identity for SMS. Applies wherever resolution runs, the conference arrival path included — see :meth:identity_enabled_for.

None
inbound_router InboundRoomRouter | None

Strategy for routing inbound messages to rooms. Defaults to DefaultInboundRoomRouter.

None
lock_manager RoomLockManager | None

Per-room locking backend. Defaults to InMemoryLockManager. For multi-process deployments, supply a distributed implementation (e.g. Redis-backed).

None
realtime RealtimeBackend | None

Realtime backend for ephemeral events (typing, presence). Defaults to InMemoryRealtime. For multi-process deployments, supply a distributed implementation (e.g. Redis pub/sub).

None
max_chain_depth int

Maximum reentry chain depth to prevent infinite loops.

5
identity_timeout float

Timeout in seconds for identity resolution calls.

10.0
verification_policy VerificationPolicy | None

How long an identity verification and its requests last, and how many attempts a request accepts (RFC §11.7). Passing one also turns on the inbound side: an identified sender's messages are labelled with their verification and, while it is not verified, held from the room's agents. Omitted, the API works with the defaults and the pipeline is unchanged.

None
media_resolver MediaResolver | None

The bytes of a media the application holds (RFC §6.4): async (media, room_id) -> bytes | None. A MediaContent whose URL is neither a data: URI nor a link (http, https) is a reference, in a scheme the application chooses; every AI channel registered here asks this resolver for its bytes as it builds a turn, so the store and broadcasts carry the reference alone. Any participant can write a reference: answer only for a media the room may show, None otherwise. Without a resolver, a referenced image reads as unavailable to the model.

None
attached_media AttachedMedia | None

The media an event carries outside its content, for an application that keeps a message's files beside its words (RFC §6.4): (event) -> Sequence[MediaContent], the same media in the same order each time it is asked. Every AI channel registered here reads the events of a turn, history and input alike, with the media named after their own content, as a composite; a reference among them is resolved by media_resolver. The store and broadcasts keep the event as stored. A reader that raises names none for that event.

None
turn_backend TurnBackend | None

What carries the turns of the intelligence channels (RFC §10.6). Defaults to InMemoryTurnBackend: every turn runs in this process, as serialized messages, on the kit's own executor, which reads the channels registered here.

None
error_classes Iterable[type[Exception]]

The application's exception classes, with their subclasses, that an error crossing the turn backend is rebuilt as (RFC §10.6.8), on this kit and on its own executor, beyond RoomKit's and Python's built-in ones: an error a turn raised reaches InboundResult.error, ON_ERROR and the chain of causes as the class it was raised as, its attributes kept. Any other class comes back as a RemoteTurnError that keeps its JSON attributes and reads as the nearest ancestor rebuilt here (a ProviderError subclass, a TimeoutError). An executor in another process declares its own (TurnExecutor(error_classes=...)).

()
process_timeout float

Timeout in seconds for the locked processing phase.

30.0
stt STTProvider | None

Optional speech-to-text provider for transcription.

None
tts TTSProvider | None

Optional text-to-speech provider for synthesis.

None
voice VoiceBackend | None

Optional voice backend for real-time audio transport.

None
task_runner TaskRunner | None

Pluggable backend for delegated background tasks. Defaults to InMemoryTaskRunner.

None
delivery_strategy DeliveryStrategy | str | None

Controls when proactive content is delivered, a background task's result included: the result is handed back through deliver() after the ON_TASK_COMPLETED hook (RFC §23.3). deliver() takes a strategy per call.

None
delivery_backend DeliveryBackend | None

Persistent delivery backend. When set, kit.deliver() enqueues items instead of executing in-process, and a worker loop dequeues and executes them. Defaults to None (in-process delivery).

None
status_bus StatusBus | None

Shared status bus for multi-agent coordination. Defaults to a StatusBus with InMemoryStatusBackend. Access via kit.status_bus.

None
telemetry TelemetryConfig | TelemetryProvider | None

Optional telemetry provider or config for span/metric collection. Accepts a TelemetryProvider instance or a TelemetryConfig. Defaults to NoopTelemetryProvider.

None
inbound_rate_limit RateLimit | None

Optional rate limit applied to all inbound messages before any processing. Messages exceeding the limit are dropped with reason="rate_limited". Keyed per channel_id.

None
orchestration Orchestration | None

Default orchestration strategy applied to rooms created via create_room() unless overridden per-room.

None
persistence_policy PersistencePolicy | None

Controls which event types are persisted. When None (default), all events are persisted. Use PersistencePolicy(exclude_types={...}) to skip specific types or PersistencePolicy(persist_types={...}) to whitelist.

None
delivery_gap_timeout float

Seconds a delivery lane waits on a cursor hole owned by an absent worker (one that committed events and crashed before delivering them) before skipping over it with a delivery_skipped framework event (RFC §10.2). The skip bounds the loss to the crash window; it never covers an index this process holds a plan for.

30.0
delivery_claim_lock_manager RoomLockManager | None

Lock manager used for the per-room delivery claims. Defaults to lock_manager. Supply a separate PostgresAdvisoryLockManager (own pool) in multi-process deployments: a claim is held for the length of a delivery set — provider round trips included — and must not starve the room-lock pool that commits depend on.

None

store property

store

The backing conversation store.

hook_engine property

hook_engine

The kit's hook engine (RFC §10.6.6): a hook on a trigger a turn fires registered here is the kit's own executor's.

realtime property

realtime

The realtime backend for ephemeral events.

status_bus property

status_bus

Shared status bus for multi-agent coordination.

lock_manager property

lock_manager

The per-room lock manager.

create_room instance-attribute

create_room

get_room instance-attribute

get_room

register_channel instance-attribute

register_channel

attach_channel instance-attribute

attach_channel

detach_channel instance-attribute

detach_channel

join instance-attribute

join

deliver instance-attribute

deliver

close_room async

close_room(room_id, *, organization_id=None)

Close a room (RFC §5.1).

The room's due timer transitions apply first. A room already CLOSED is returned as it is: nothing is written, no hook fires and no framework event is emitted.

organization_id scopes the operation to one tenant (RFC §17.2); a room belonging to another organization is reported as not found.

Raises:

Type Description
TransitionRefusedError

the room is ARCHIVED, which no call leaves; nothing is written.

archive_room async

archive_room(room_id, *, organization_id=None)

Archive a room — the terminal storage state (RFC §5.1).

ARCHIVED refuses new events exactly as CLOSED does; the difference is intent. A closed room MAY be reopened by returning it to ACTIVE; an archived one is done. History, participants and bindings stay readable at every status, archived included.

This is the only path to the status, and therefore the only source of the room_archived framework event (§8.2). The room's due timer transitions apply first. A room already ARCHIVED is returned as it is: nothing is written or emitted.

check_room_timers async

check_room_timers(room_id, *, organization_id=None)

Apply the room's due timer transitions (RFC §5.1), for a room nobody writes to.

An ACTIVE room pauses once inactive_after_seconds passed since its last activity, or since its creation before any; a PAUSED room closes once closed_after_seconds passed since paused_at. Each transition takes the instant it fell due, however late the check: one long after both pauses the room at the first instant and closes it at the second, in one write. Each emits room_paused or room_closed (reason = timer), then fires ON_ROOM_PAUSED or ON_ROOM_CLOSED once the room lock is released: their hooks have started when this returns, which does not wait for them (RFC §9.3). Every locked operation on the room applies them as well.

Returns the room as stored once its due transitions are applied. organization_id scopes the check to one tenant (RFC §17.2).

check_all_timers async

check_all_timers(*, organization_id=None)

Check the timers of every ACTIVE and PAUSED room (:meth:check_room_timers) and return the rooms that transitioned.

organization_id limits the check to one tenant's rooms; with none, every room is checked.

update_room_metadata async

update_room_metadata(room_id, metadata, *, organization_id=None)

Update room metadata.

A key only the framework writes is dropped with a warning, the rest written: one under roomkit: (RFC §5.1), a detach's revocation (roomkit:detached_channels) and what the room keeps for a channel (roomkit:channel_state:) among them, a key of the room's private state (author_register, _speak_queue_results, RFC §14.1) or orchestration's (_conversation_state, RFC §19.2; _discussion, _speak_queue, RFC §19.7.5 rule 16). So a read-modify-write ({**room.metadata, ...}) writes its own keys and leaves the framework's as they are.

set_agent_response_policy async

set_agent_response_policy(room_id, policy, *, organization_id=None)

Set what an agent's own output solicits in this room (RFC §19.3.1).

The policy is chosen at creation, but a room rarely knows then how many agents it will end up holding: one that gains a second agent is a different room, because under AGENT_CHAIN the first answer solicits the other agent, whose answer comes back, down to max_chain_depth. Switching to ADDRESSED_ONLY at that moment is what keeps a room of independent agents from answering itself.

Applies to events processed after it — an event already broadcast is not reconsidered. No-op when the room already holds policy.

install_strategy async

install_strategy(room_id, strategy, *, organization_id=None)

Install strategy in a room, new or already in use (RFC §19.7).

The strategy's agents are registered and attached as intelligence channels, then its install runs; the room's timeline stays, and the agents' turns read it. organization_id scopes the call to one tenant (RFC §17.2).

A Discussion installed in a room that holds a discussion, installed through this kit or stored by another process, takes its place and keeps its queue (RFC §19.7.5 rule 1): how a process that restarted takes the discussion back, and how the host changes its agents.

Raises:

Type Description
ValueError

the room holds a strategy already (uninstall it first), or the strategy refuses the room.

uninstall_strategy async

uninstall_strategy(room_id, *, organization_id=None)

Take the room's strategy back out (RFC §19.7): its own uninstall step, then what its install added for the room. The room answers by its agent_response_policy again and may take another strategy. A discussion is uninstalled from any process serving the room, one where no host installed it included (RFC §19.7.5 rule 16). Whether a strategy was installed.

room_strategy

room_strategy(room_id, *, organization_id=None)

The strategy installed in room_id through this kit, if any. organization_id scopes the read to one tenant (RFC §17.2): a room of another organization reads as holding none.

room_strategy_is_current async

room_strategy_is_current(room_id, kind, *, organization_id=None)

Whether the strategy of kind this process installed in room_id is the one the room stores now (RFC §19.7).

A strategy stored with the room, a discussion (RFC §19.7.5 rule 16), may be replaced by another process's install with another configuration, after which this process gives no turn. False then, when this process installed none, and once it was uninstalled; the room's stored state is read when called. An uninstall another process made is taken here at once: :meth:room_strategy answers None from then on, where a replaced install still names this process's own. A host that finds it false installs again only while its own state still wants the discussion, else it would bring back one another process took out::

if wanted and not await kit.room_strategy_is_current(room_id, Discussion):
    await kit.install_strategy(room_id, Discussion(agents))

organization_id scopes the call to one tenant (RFC §17.2).

Raises:

Type Description
TypeError

kind is not a strategy stored with the room.

RoomNotFoundError

the room does not exist in the scope.

claim_room_strategy async

claim_room_strategy(room_id, strategy, *, organization_id=None)

Claim room_id for strategy, or refuse: a room holds one strategy (RFC §19.7). :meth:install_strategy claims for the strategy it installs; a strategy installed by calling its install directly calls this first, as the built-in ones do.

A Discussion may claim a room holding a discussion no install of this kit recorded, to take its place (RFC §19.7.5 rule 1). The room is read first, as an install reads it: a discussion another process stored is this room's here too (rule 16).

organization_id is the organization the caller acts for (RFC §17.2): the room is read with it, and another organization's room is not found, whatever strategy it holds.

Raises:

Type Description
RoomNotFoundError

organization_id is set and the room is missing or another organization's.

ValueError

the room holds another strategy or a discussion.

speak_queue

speak_queue(room_id, *, organization_id=None)

The speak queue of the discussion room_id holds in this process, or None when it holds none (RFC §19.7.5 rule 17). organization_id scopes the read to one tenant (RFC §17.2): a room of another reads as holding none.

listen_only async

listen_only(room_id, channel_ids, *, organization_id=None)

Have agents of a discussion only listen (RFC §19.7.5 rule 12).

An agent that only listens keeps its place in the queue and takes no turn an agent's message asks for; a person's message that names it gives it one turn. Setting the state on the agent whose turn runs cuts that turn, as a Cancel does; what the turn committed stays.

Raises:

Type Description
ValueError

the room holds no discussion in this process (or in organization_id's scope).

talk_again async

talk_again(room_id, channel_ids, *, organization_id=None)

End the listening state of agents of a discussion (RFC §19.7.5 rule 12).

Raises:

Type Description
ValueError

the room holds no discussion in this process (or in organization_id's scope).

mute async

mute(room_id, channel_id, *, organization_id=None)

Mute a channel in a room. Muting a muted channel writes nothing and fires nothing (RFC §7.2).

unmute async

unmute(room_id, channel_id, *, organization_id=None)

Unmute a channel in a room. Unmuting a channel that is not muted writes nothing and fires nothing (RFC §7.2).

set_visibility async

set_visibility(room_id, channel_id, visibility, *, organization_id=None)

Set visibility for a channel in a room. An invalid visibility, and internal, which marks a record the framework wrote, raise ValueError (RFC §7.3). The visibility the binding holds already writes nothing (RFC §7.2).

set_access async

set_access(room_id, channel_id, access, *, organization_id=None)

Set access level for a channel in a room. The access the binding holds already writes nothing (RFC §7.2).

update_binding_metadata async

update_binding_metadata(room_id, channel_id, metadata, *, organization_id=None)

Update metadata on a channel binding, merged into what it holds. An update that changes nothing writes nothing (RFC §7.2).

get_channel

get_channel(channel_id)

Get a registered channel by ID.

list_channels

list_channels()

List all registered channels.

get_binding async

get_binding(room_id, channel_id, *, organization_id=None)

Get a channel binding. Raises ChannelNotFoundError if missing.

list_bindings async

list_bindings(room_id, *, organization_id=None)

List all channel bindings for a room.

get_timeline async

get_timeline(room_id, offset=0, limit=50, visibility_filter=None, *, after_index=None, before_index=None, newest_first=False, include_blocked=False, organization_id=None)

Query the event timeline for a room.

Supports offset-based (offset/limit) and cursor-based (after_index/before_index) pagination. When a cursor parameter is set, offset is ignored.

The offset-based default is the oldest limit events — page 1 of a log reads from the beginning. Pass newest_first=True for the most recent limit instead (still ascending), which is the shape a reconnect snapshot wants: what was just said, not how the room opened.

The page holds what the room received: a row stored BLOCKED is served only when include_blocked asks for it, the audit read (RFC §14.1).

Parameters:

Name Type Description Default
room_id str

Room to query.

required
offset int

Number of events to skip (offset-based mode), counted from the newest end when newest_first is set.

0
limit int

Maximum number of events to return.

50
visibility_filter str | None

Optional visibility value to filter by.

None
after_index int | None

Return events with index > after_index.

None
before_index int | None

Return events with index < before_index.

None
newest_first bool

In offset-based mode, return the most recent limit events instead of the oldest. Ignored when a cursor is supplied.

False
include_blocked bool

Serve the rows the room refused too (status BLOCKED), for audit.

False

list_tasks async

list_tasks(room_id, status=None, *, organization_id=None)

List tasks for a room, optionally filtered by status.

delegate async

delegate(room_id, agent_id, task, *, wait=False, context=None, share_channels=None, notify=None, on_complete=None, require_structured_result=False, max_result_retries=3, result_tool=None, post_status=True, brief=None, conversation=0, hand_back='relay', max_result_chars=MAX_RESULT_CHARS, organization_id=None)

Delegate a task to an agent in a child room.

Creates a child room linked to room_id, attaches the agent and any shared channels, then either runs the agent inline or submits the task for background execution.

Parameters:

Name Type Description Default
room_id str

Parent room ID.

required
agent_id str

Channel ID of the agent to run the task.

required
task str

What was asked: the agent reads it unless brief is given, and a hand-back, the StatusBus and a turn's notes name the task by it (RFC §23.3 step 4).

required
wait bool

If True, run the agent inline and return a pre-completed :class:DelegatedTask. If False (default), submit as a background task.

False
context dict[str, Any] | None

Host metadata, kept as the child room's task_context for hooks, tools and the host: no model reads it, so a host's data does not reach a vendor through it. What the agent should read goes in task or brief.

None
share_channels list[str] | None

Channel IDs from the parent to share.

None
notify str | None

Channel the result is handed to when a background task completes (RFC §23.3): an agent receives it, bounded, as an instruction and answers through the room's transport; a transport receives it as a delivery. Defaults to agent_id.

None
on_complete Any | None

Optional async callback (DelegatedTaskResult) -> None.

None
require_structured_result bool

Inline runs only: the agent must hand its work back by calling a result tool, re-prompted up to max_result_retries times; the result's output is then the tool's JSON payload.

False
max_result_retries int

How many times a turn ending without the call is re-prompted.

3
result_tool ResultTool | None

The tool to force, when not submit_result (:data:~roomkit.orchestration.result.SUBMIT_RESULT).

None
post_status bool

Follow the task on :attr:status_bus (RFC §23.3): pending once announced, then completed or failed. False for a caller that posts its tasks there itself (an orchestration strategy's worker run), so none shows twice.

True
brief str | None

What the agent is told instead of task, when it says more (how to work, what to report); it never reaches the parent room.

None
conversation int

How many of the parent room's last messages the agent is handed, those the notified channel may read, quoted as data (0: none). Its child room starts empty.

0
hand_back str

How a background task's result reaches the room: "relay", the notified channel is told it (step 8), or "post", it is posted as it is, as a message of the notified agent, without a turn of its model. "post" needs notify (or agent_id) to name an intelligence channel attached to the room, and a background task.

'relay'
max_result_chars int

How much of the worker's output a relayed result carries: past it, the output is cut and says so (RFC §23.3 step 8). A posted result is not cut.

MAX_RESULT_CHARS
organization_id str | None

The organization the caller acts for (RFC §17.2): the parent room is read with it before anything is created or run.

None

Returns:

Name Type Description
A DelegatedTask

class:DelegatedTask handle. When wait is True,

DelegatedTask

the result is already set. When False, call .wait()

DelegatedTask

to block for the result, or let it run fire-and-forget.

Raises:

Type Description
RoomNotFoundError

If the parent room doesn't exist, or is another organization's.

ChannelNotRegisteredError

If the agent channel isn't registered.

ValueError

An unknown hand_back, a "post" the notified channel cannot take, a negative conversation, or a max_result_chars below 1 or no integer.

cancel_task async

cancel_task(task_id, *, organization_id=None)

Cancel a delegated task still running in the background (RFC §23.3).

The task ends cancelled, as any task cancelled from outside: ON_TASK_COMPLETED fires, the StatusBus posts its end, and the channel its result was going to is told it was cancelled. A task that already ended, or that the framework's task runner does not hold (an inline delegation), is left as it stands. Calls cancelling it at once, this one and an agent's cancel_task among them, cancel it once.

organization_id is the organization the caller acts for (RFC §17.2): only a task running for one of its rooms is cancelled; another organization's, as a task the runner does not hold, is left as it stands.

Returns:

Type Description
bool

True when the task was running and is now cancelled.

list_observations async

list_observations(room_id, *, organization_id=None)

List observations for a room.

leave async

leave(session)

Remove a participant from a room.

Stops listening, unbinds the session, removes recording tracks, and disconnects the backend.

Parameters:

Name Type Description Default
session VoiceSession | VideoSession

The session to leave.

required

process_inbound async

process_inbound(message, *, room_id=None, defer_delivery=False, organization_id=None)

Process an inbound message through the full pipeline.

Parameters:

Name Type Description Default
message InboundMessage

The inbound message to process.

required
room_id str | None

Explicit room to route to, bypassing the inbound router. Useful for shared channels attached to multiple rooms.

None
defer_delivery bool

Return at the commit instead of waiting for the delivery set (RFC §10.1 step 18 detached completion). The result carries the committed event — a hook refusal is still decided under the room lock and reported synchronously — and result.delivery holds a :class:DeliveryHandle on the rest of the turn: delivery execution, reentry passes (an AI reply included) and streamed responses, all following in the room's lane. For a caller that must answer with the committed event while the agent's turn runs on (an HTTP route returning 200, say); delivery_results is backfilled by delivery.wait().

False
organization_id str | None

The organization the caller acts for (RFC §17.2). The router is given it, with the sender's identity resolved within it, and the default router searches that organization's rooms only (every room when it is unset). The room the message would land in is checked against it before any event is committed or any channel auto-attached: a room belonging to another organization is reported as not found, whether the caller named it or a custom router answered it; a room the caller names, or a router answers, that does not exist yet is created under it. That auto-create makes a miss observable, so a scoped caller passes room ids it resolved itself, never one it was handed. Left unset, the read is unscoped and behaves as it always has. A library has no caller or auth context of its own, so the scope has to come from the caller: the row that mapped an external identity (a chat, a number) to a room is where it usually lives.

None

Cancelling an awaited call stops only its turns (the message is still delivered to the room's other channels) and drains owned generation, tools and streams before propagating CancelledError. Cleanup has a five-second budget; TimeoutError reports that work is still unwinding and its resources must be kept. Deferred callers explicitly use result.delivery.cancel(), and any code by the message's delivery_key (:meth:cancel_delivery); cancelling a handle's wait() cancels only that wait. Committed timeline events are retained in every case.

Called from the room's own work, the message is part of it (RFC §9.5.1): sent into its room under the room lock, from an off-lock hook's body or from a channel's parse, it is adopted by the event being processed and takes no ticket; from a turn or a delivery it is a new arrival. It draws on the reentry budget of that event, or of the cascade that delivers, as it starts: past it, it is refused reentry_loop_cap with no event, before anything else when it names its room (its channel not looked up, nothing attached), once routing knows its room when it is routed. Named with an organization_id, the room is read with it before the budget: another organization's room is not found, and nothing is drawn (RFC §17.2). A message sent within a turn is at least as deep as the turn's response (RFC §8.3).

A message with no room_id under the framework's own name, system, is refused reserved_sender with nothing read or written (RFC §10.1 step 2): the framework names the room it writes to, and a host writing under that name passes room_id. A host naming the room sets sender_id itself, and never copies a client's.

A routed message whose room, created for it, names someone else once its ON_ROOM_CREATED hooks are over (a concurrent sender recorded there, or a hook's binding) is routed once more; when no room opened for it is still its own, it is refused room_taken, nothing of it stored (RFC §10.1 step 2).

Raises:

Type Description
ChannelNotRegisteredError

the message's channel is not registered (a message refused past its room's work budget first excepted).

ReentrantCallError

the message is routed (no room_id) into the room whose lock the caller holds or in whose admission order it stands (an off-lock hook's body, a parse); nothing is written.

ValueError

its content, or the event its channel parses, holds more than five composite levels (RFC §5.3); nothing is stored. Its channel is a host channel, which receives no external payload (RFC §10.5); nothing is read or written.

send_event async

send_event(room_id, channel_id, content, event_type=MESSAGE, chain_depth=0, participant_id=None, metadata=None, visibility=ALL, provider=None, response_visibility=None, created_at=None, parent_event_id=None, idempotency_key=None, addressed_to=None, organization_id=None, standalone=False)

Send an event directly into a room from a channel.

Parameters:

Name Type Description Default
room_id str

Target room ID

required
channel_id str

Source channel ID

required
content Any

Event content (TextContent, RichContent, etc.)

required
event_type EventType

Type of event (default MESSAGE)

MESSAGE
chain_depth int

Depth in response chain (for loop prevention)

0
participant_id str | None

Optional participant/sender ID for the event source

None
metadata dict[str, Any] | None

Optional event metadata

None
visibility str

Event visibility, a keyword (all, none, transport, intelligence) or channel ids (RFC §7.3); committed intersected with the source binding's. internal, which marks a record the framework wrote, raises ValueError: an event stored for no channel takes none

ALL
provider str | None

Optional provider/backend name for event attribution

None
response_visibility str | None

Controls where the AI's response is delivered. Uses the same vocabulary as visibility. None means no restriction. internal raises ValueError, as for visibility.

None
addressed_to list[str] | None

The intelligence channels this event asks to act (RFC §19.3). An address is set by a sender, and direct injection has a sender like any other entry point: a caller storing a message whose answer it triggers separately passes [] so the stored message solicits nobody, and one talking to a specific agent in a room that holds several names it. None leaves the event unaddressed — the router decides, or every eligible intelligence channel acts.

None
parent_event_id str | None

In-app thread parent. The locked pipeline normalises it to the thread root (flat two-level model); see :meth:_resolve_thread_root.

None
idempotency_key str | None

Stable de-duplication key, unique per room and per source channel (RFC §13.4). When set, the locked pipeline's idempotency check skips a re-send from the same channel that carries the same key — so a caller that may replay a publish (an outbox dispatcher redelivering after a crash) gets at-most-once persistence for a given key. None keeps the prior behaviour (no de-duplication), matching inbound events that carry no key.

None
standalone bool

For an INSTRUCTION only: the turn it opens reads nothing of the room — no history, no memory provider call (RFC §10.1.1 step 7). Raises on any other event type.

False

Called from the room's own work, the event is part of it (RFC §9.5.1): under the room lock (a locked hook, code under the lock) it commits ahead of the event being processed, takes no ticket and runs every hook under the lock, what its hooks inject committing once the section holding the lock released it; from an off-lock hook's body or a channel's parse it is adopted beside that event, takes no ticket and takes the lock for its own commit. Either way it draws on that event's reentry budget, and from a turn or a delivery on the budget of the cascade that delivers: past it, it is stored BLOCKED reentry_loop_cap with no hook run, and that record is returned. A call made within a turn is at least as deep as the turn's response (RFC §8.3).

Raises:

Type Description
ChannelNotRegisteredError

the kit registers no channel channel_id, raised before anything is read (RFC §10.5), whether or not the room still binds it.

RoomNotFoundError

the room is missing, or another organization's.

ChannelNotFoundError

the room does not bind channel_id.

RoomClosedError

the room's status refuses new events (RFC §5.1).

ChangeRefusedError

an edit or a delete step 8a refused.

ProcessTimeoutError

process_timeout passed before the commit.

ValueError

an argument the pipeline would refuse, content holding more than five composite levels included (RFC §5.3).

commit_event async

commit_event(room_id, event, *, organization_id=None)

Commit a record no member receives to the room's timeline (RFC §10.5).

For a trace, a display snapshot, the copy a branched conversation starts from. The record takes the room's next index, which its delivery lane passes at its turn with nothing to run, so the room's next event waits on it no longer than on the events before it; no delivery set, no hook and no broadcast follow. It is no activity (RFC §5.1): the room's last_activity_at stays, and a PAUSED room stays paused. It is stored as given, whatever the persistence policy, but for its thread parent, rooted as every committed event's is (a reply named is replaced by its thread's root, an event the room does not hold dropped, RFC §10.1 step 8), and the record of its author, which the room fixes when the event names one (metadata["author"], RFC §10.1 step 12, any value given dropped); the source write rule (RFC §7.5 rule 2) does not apply to it. An event the members must receive goes through :meth:send_event.

The room is read under its lock, which a hook already holding it re-enters, scoped to organization_id (RFC §17.2).

Raises:

Type Description
ValueError

event names another room, carries an idempotency_key in the framework's publication namespace (roomkit:publication:), or holds more than five composite levels (RFC §5.3); nothing is read or written.

RoomNotFoundError

the room is missing, or another organization's.

RoomClosedError

the room's status refuses new events (RFC §5.1); nothing is written.

IdempotencyKeyTakenError

the room holds an event of the record's source channel under its idempotency key: a record is never a replay (RFC §10.5, §14.3); nothing is written.

start_room_recording async

start_room_recording(room_id, recorders, *, organization_id=None)

Start recorders on an existing room, all or nothing, and announce each.

The room is read under its lock, scoped to organization_id (RFC §17.2). ON_RECORDING_STARTED fires for each recording, under the lock, before it joins the room's media: it is told the room's tracks, then filed, so media already flowing reaches it after its consent point and in the format its track declares (RFC §12.11, §17.6). It captures the room's declared tracks: a session that joined while the room recorded nothing declared none, and is recorded once it joins again. A recording resumed after a restart is started here.

Raises:

Type Description
RoomNotFoundError

the room is missing, or another organization's.

RoomClosedError

the room's status refuses new events (RFC §5.1).

Exception

a recorder refused to start; the ones already started for this call are stopped.

room_recordings async

room_recordings(room_id, *, organization_id=None)

The recordings room_id runs, in the order they started; empty when none.

The room is read scoped to organization_id, as a stop reads it (RFC §12.11): a room whose row is gone is listed while it still records.

Raises:

Type Description
RoomNotFoundError

the room is another organization's, or it is missing and records nothing.

add_room_recording_track async

add_room_recording_track(room_id, track, *, organization_id=None)

Declare track to the room's recordings; the feed its media goes through.

For a source the framework does not wire itself (a channel that joins the room while it records wires its own). The track describes the media it will carry (RFC §12.11): the feed hands it as declared, and a recording started later is told it before any of its media. The room is read scoped to organization_id, as a stop reads it. None when the room records nothing.

Raises:

Type Description
RoomNotFoundError

the room is another organization's, or it is missing and records nothing.

stop_room_recording async

stop_room_recording(room_id, *, organization_id=None)

Stop the room's recordings, each announced with its result (RFC §12.11).

The room is read under its lock, scoped to organization_id: a call refused for another organization stops nothing. A room whose row is gone still has its recordings stopped: they run in memory, and a file nothing stops is never finalized; with no room left to read a context from, their end is logged rather than announced. Returns the results of the recordings that stopped; empty when the room recorded nothing.

Raises:

Type Description
RoomNotFoundError

the room is another organization's, or it is missing and records nothing, as one would be told not found.

regenerate_response async

regenerate_response(room_id, *, trigger_id=None, organization_id=None)

Re-run the room's intelligence channel on the last inbound message.

Produces a fresh response to the most recent transport (human) message without ingesting a new inbound event — the triggering message keeps its identity, index, and timestamp. The re-broadcast runs in the room's delivery lane, off the room lock and unbounded, as an inbound event's broadcast does (RFC §13.5, §13.6): a strategy that takes the agent's turn (a Loop, a Supervisor's delegation) goes to its end, and the room takes messages meanwhile. The new response re-enters like a first-time turn's (RFC §10.1 step 14): its BEFORE_BROADCAST hooks run, its source's right to write is checked, it counts against the reentry budget, it is persisted, streamed, and runs its AFTER_BROADCAST hooks, and it comes back in response_events. The trigger message's own hooks are not re-run, nor its delivery report or event_processed.

Replacement semantics are the caller's concern: any responses already present after the last inbound message should be removed before calling this (the method only generates — it does not delete the prior answer). :meth:regenerate_target names the message this call would re-run on, so the caller can key that removal on it.

trigger_id makes the call a compare-and-regenerate. The target is read outside the room lock, so a message can land between that read and this call: the pipeline has answered it already, and a regenerate that re-selects under the lock would answer it a second time, with the earlier answer gone. Naming the trigger closes that window: when the selection under the lock is no longer that event — another message moved in, or nothing qualifies any more — the call returns InboundResult(blocked=True, reason="trigger_moved") without running the agent and without writing anything. None (the default) regenerates whatever the selection is. A closed room is refused first: room_closed wins over trigger_moved. The compare is on the trigger, not on the answers that follow it: two concurrent calls naming the same trigger both pass it, and an answer landing between them does not move a transport selection.

Returns the :class:InboundResult for the regenerated turn, or None when there is no inbound message to regenerate (no transport message, or its source binding can no longer write) — with trigger_id set, that same state is a moved trigger and comes back blocked instead of None. process_timeout bounds only the wait for the room lock and the choice of the trigger: past it, the call returns InboundResult(blocked=True, reason="process_timeout") without running the agent. The call waits behind the deliveries already in the room's lane; called from inside that lane or under the room lock, it returns at once and the regeneration follows in lane order. A caller cancelled cuts the regenerated turn. A room whose status refuses new events (RFC §5.1), at the call or while the regeneration waits in the lane, is refused before the agent runs, with InboundResult(blocked=True, reason="room_closed") and a room_refused_event framework event — exactly as :meth:process_inbound refuses — rather than after a generation whose answer nothing could commit.

The re-broadcast is scoped to visibility="intelligence" so only the agent reacts — transports never receive the user message again (no duplicate bubble, no echo to other participants). Targets the single intelligence-channel path; orchestrated rooms (routing installed as BEFORE_BROADCAST hooks) are not re-routed here.

In a room a discussion holds (RFC §19.7.5 rule 7), each agent that answered the trigger (when no answer is left, each agent the trigger asked for) is queued at the front for a turn of its own, and the call returns once they are queued, with no answer in its result: the answers come in those turns. A discussion that is over refuses it, InboundResult(blocked=True, reason="discussion_over").

Made from the body of an ASYNC hook a cascade fires once an event's delivery set has run, the call draws one of that cascade's hook calls as it starts (RFC §9.5.1); the regeneration's cascade draws on the budget of the room's work the call is made in, one of its own outside it, so a hook that regenerates after every answer stops at the cap.

organization_id is the organization the caller acts for (RFC §17.2): another organization's room is refused before any turn is planned or queued, and before the call draws on any budget.

Raises:

Type Description
RoomNotFoundError

organization_id is set and the room is missing or another organization's; nothing is run or written.

ReentryLoopCapError

made from an ASYNC hook's body past the budget that body runs on; nothing is run or written.

regenerate_target async

regenerate_target(room_id, *, organization_id=None)

The event :meth:regenerate_response would re-run the agent on.

The primitive's own choice, from the primitive's own read: the newest message a transport binding wrote and the room accepted (a message a hook blocked is never replayed), in the history window the room's channels derive, whose source binding can still write. A host that must act on the trigger before regenerating — delete the answer the new one replaces, refuse a trigger it recognises as a runner's prompt rather than a person's question — asks here instead of re-implementing the selection off a window of its own.

Returns None when a regenerate would do nothing: no transport message in the window, or its source binding can no longer write.

Raises :class:RoomClosedError when the room's status refuses new events (RFC §5.1): :meth:regenerate_response would refuse, and an accessor that returns an event has no way to hand back that refusal — the same reasoning as :meth:send_event. Raises :class:RoomNotFoundError for an unknown room.

A read, taken outside the room lock, so the answer can be stale by the time a regenerate acts on it — the caveat of any answer taken before the lock (RFC §10.1 step 6): the regenerating call re-selects under the lock, and a message that lands in between becomes the trigger there. A host that must not answer that message twice hands this event's id back as regenerate_response(trigger_id=...), which refuses a selection that moved instead of regenerating it.

organization_id is the organization the caller acts for (RFC §17.2): another organization's room raises :class:RoomNotFoundError before anything of it is read.

ensure_participant async

ensure_participant(room_id, channel_id, participant_id, display_name=None, *, organization_id=None)

Get an existing participant or create one.

A participant is one record per (room, id), so channel_id names the channel a record being created is primarily reached on — it is not a filter. A participant the room already has is returned as they stand, primary channel included, even when that channel is not the one asked for: the same person reached by SMS and then by email is one participant, not two (RFC §5.5). The channel asked for is recorded in connected_via, and a channel that is not the record's primary one is logged, because nothing in the returned record would otherwise say so — a caller keeping a lifecycle or a status on it is keeping it on a record another channel also drives. Use :meth:add_member for a deliberate join.

Bookkeeping only: no PARTICIPANT_UPDATED event, no ON_PARTICIPANT_UPDATED hook. Runs under the room lock — recording a channel is a read-modify-write, and add_member / remove_member hold that lock while they write the same record.

resolve_participant async

resolve_participant(room_id, participant_id, identity_id, resolved_by='manual', *, organization_id=None)

Resolve a pending participant to a known identity (RFC 7.4).

Called by an advisor or automated process when a pending/ambiguous participant has been identified.

request_verification async

request_verification(identity_id, *, room_id, channel_id, method=METHOD_LINK, window_start=None, organization_id=None)

Open a verification request for an identity; return it and its secret.

The secret is returned once and never stored: put it in the link to your page, or send it as a code (method="code": digits the person replies with). Opening a request cancels the identity's earlier open one. An identity that is not verified becomes PENDING; one already verified stays so until this request completes or its verification ends. window_start is when the message that called for it was received (now by default): the held messages released on completion are those from then on (RFC §11.7.6).

The request is scoped to the room's organization, the one whose messages it verifies. organization_id is the organization the caller acts for (RFC §17.2): a room of another raises :class:RoomNotFoundError.

complete_verification async

complete_verification(request_id, secret, *, method=None, organization_id=None)

Complete a request once your own check passed; return the verification.

Raises :class:VerificationRefusedError when the request is unknown (or another organization's than organization_id, when given), no longer open, expired, or the secret does not match (a mismatch counts as an attempt; the last one fails it). method records how the person proved it, the request's by default.

record_failed_attempt async

record_failed_attempt(request_id, *, organization_id=None)

Count a failed check of your own method against a request; return it.

Your page's wrong PIN or refused login is an attempt like a wrong secret: the request's bound applies to it, so a PIN cannot be guessed through your page. The request comes back OPEN with one attempt more, or FAILED when that was the last one (which ends it as a wrong secret does, a verification in force included). Raises :class:VerificationRefusedError when the request is unknown (or another organization's than organization_id, when given), no longer open, or expired.

revoke_verification async

revoke_verification(identity_id, *, reason='revoked', organization_id=None)

End an identity's verification before its time; None if none was in force.

Its open request is cancelled in every case, verified or still pending: a link sent before the revocation can never verify the person after it (RFC §11.7.7).

verification_of async

verification_of(identity_id, *, organization_id=None)

The identity's verification as it stands now: UNVERIFIED when it has none.

A verification whose time has passed reads EXPIRED, and an open request past its expiry reads as ended (no request_id, a PENDING identity back to UNVERIFIED), whether or not the end has been recorded yet.

sender_verification async

sender_verification(event, context)

The verification of event's sender, in its room's organization.

None when the pipeline did not label the event (its sender is not identified, or the kit has no verification policy). What an ON_VERIFICATION_REQUIRED hook reads before opening a request: whose verification it is (identity_id) and whether a request is open already (request_id). The sender's participant may not be in context yet on their first message; this reads it all the same.

check_verifications async

check_verifications()

End the verifications whose time passed; arm the timers of the others.

A verification ends when its time runs out (RFC §11.7.5), by a timer this process arms when it completes. Call this when the process starts (async with RoomKit(...) does): it ends what expired while nothing was running and re-arms the rest. Returns the ones it ended.

connect_websocket async

connect_websocket(channel_id, connection_id, send_fn, *, room_id, stream_send_fn=None, organization_id=None)

Register a WebSocket connection for a room and emit framework event.

room_id says which conversation this socket belongs to. It is required because one channel instance can serve several rooms, and a connection the channel cannot place would otherwise have to receive every room's events. Add more rooms to the same socket with :meth:subscribe_websocket.

organization_id is the organization the caller acts for (RFC §17.2): the room is read with it before the socket is registered, and another organization's room raises :class:RoomNotFoundError with no connection registered and no event emitted; the connection is registered for the organization, as :meth:WebSocketChannel.register_connection registers one, and receives no room of another. Unset, no room is read, as before.

Raises:

Type Description
RoomNotFoundError

organization_id is set and the room is missing or another organization's.

ValueError

organization_id is set and connection_id is registered for another organization, or unscoped.

subscribe_websocket

subscribe_websocket(channel_id, connection_id, room_id, *, organization_id=None)

Also deliver room_id to an already-connected socket.

organization_id is the organization the caller acts for (RFC §17.2): the call reads no room, and only a connection registered for it is subscribed; a room of another organization, or of none, delivers nothing to a connection registered for one (:meth:WebSocketChannel.subscribe).

Raises:

Type Description
ValueError

organization_id is set and the connection is not registered for it; nothing changes.

unsubscribe_websocket

unsubscribe_websocket(channel_id, connection_id, room_id, *, organization_id=None)

Stop delivering room_id to a connected socket; with organization_id (RFC §17.2), only a connection registered for it, ValueError otherwise (:meth:WebSocketChannel.unsubscribe).

disconnect_websocket async

disconnect_websocket(channel_id, connection_id, *, organization_id=None)

Unregister a WebSocket connection and emit framework event.

organization_id is the organization the caller acts for (RFC §17.2): only a connection registered for it is unregistered (:meth:WebSocketChannel.unregister_connection).

Raises:

Type Description
ValueError

organization_id is set and the connection is not registered for it; nothing changes and no event is emitted.

mark_read async

mark_read(room_id, channel_id, event_id, *, organization_id=None)

Mark an event as read for a channel.

mark_all_read async

mark_all_read(room_id, channel_id, *, organization_id=None)

Mark all events as read for a channel.

publish_typing async

publish_typing(room_id, user_id, is_typing=True, data=None, *, organization_id=None)

Publish a typing indicator for a user in a room.

Parameters:

Name Type Description Default
room_id str

The room to publish the typing event in.

required
user_id str

The user who is typing.

required
is_typing bool

True for typing_start, False for typing_stop.

True
data dict[str, Any] | None

Optional additional data (e.g., {"name": "User Name"}).

None
organization_id str | None

The organization the caller acts for (RFC §17.2).

None

publish_presence async

publish_presence(room_id, user_id, status, *, organization_id=None)

Publish a presence update for a user in a room.

Parameters:

Name Type Description Default
room_id str

The room to publish the presence event in.

required
user_id str

The user whose presence changed.

required
status str

One of "online", "away", or "offline".

required
organization_id str | None

The organization the caller acts for (RFC §17.2).

None

publish_read_receipt async

publish_read_receipt(room_id, user_id, event_id, *, organization_id=None)

Publish a read receipt for a user in a room.

Parameters:

Name Type Description Default
room_id str

The room to publish the read receipt in.

required
user_id str

The user who read the message.

required
event_id str

The ID of the event that was read.

required
organization_id str | None

The organization the caller acts for (RFC §17.2).

None

subscribe_room async

subscribe_room(room_id, callback, *, organization_id=None)

Subscribe to ephemeral events for a room.

Parameters:

Name Type Description Default
room_id str

The room to subscribe to.

required
callback EphemeralCallback

Async callback invoked for each ephemeral event.

required
organization_id str | None

The organization the caller acts for (RFC §17.2).

None

Returns:

Type Description
str

A subscription ID that can be used to unsubscribe.

unsubscribe_room async

unsubscribe_room(subscription_id)

Unsubscribe from ephemeral events.

Parameters:

Name Type Description Default
subscription_id str

The subscription ID returned by subscribe_room.

required

Returns:

Type Description
bool

True if the subscription existed and was removed.

hook

hook(trigger, execution=SYNC, priority=0, name='', timeout=30.0, channel_types=None, channel_ids=None, directions=None, event_types=None, fail_closed=False, needs_lock=True)

Decorator to register a global hook.

A filtered-out hook is not called at all — neither its body nor its timeout budget. A trigger that fires for every event a turn produces (BEFORE_BROADCAST runs once per text segment and once per tool-call event) is where event_types pays: a hook that only shapes tool calls declares it instead of guarding on event.type and being invoked on every segment of every turn.

Parameters:

Name Type Description Default
trigger HookTrigger

When the hook fires (BEFORE_BROADCAST, AFTER_BROADCAST, etc.)

required
execution HookExecution

SYNC (can block/modify) or ASYNC (fire-and-forget)

SYNC
priority int

Lower numbers run first (default: 0)

0
name str

Optional name for logging and removal

''
timeout float

Max execution time in seconds (default: 30.0)

30.0
channel_types set[ChannelType] | None

Only run for events from these channel types (None = all)

None
channel_ids set[str] | None

Only run for events from these channel IDs (None = all)

None
directions set[EventDirection] | None

Only run for events with these directions (None = all)

None
event_types set[EventType] | None

Only run for events of these types (None = all)

None
fail_closed bool

SYNC only (ValueError on an ASYNC hook, which cannot block) — a timeout, an exception or an unusable result blocks the payload instead of letting it through, with reason="hook_timeout:<name>" / hook_error:<name> / hook_invalid_result:<name> (RFC §9.3). For content checks.

False
needs_lock bool

SYNC BEFORE_BROADCAST only — False runs the hook before the room lock is taken, so its I/O does not hold the room; arrival order is kept by a per-room admission ticket (RFC §9.5.1). Only for a hook that reads the event, not the room's state. Raises ValueError on another trigger, or when a locked hook would be ordered before it by priority.

True

A hook on a trigger a turn fires (ON_TOOL_CALL, BEFORE_TOOL_USE..., RFC §10.6.6) is the kit's own executor's: it fires for the agents the kit runs. One that a channel the kit holds by its declaration alone could fire (its turns run on another executor) raises ValueError: register it on that executor, executor.hook(...), or leave the channel out of channel_ids.

on

on(event_type)

Decorator to register a framework event handler filtered by type.

identity_hook

identity_hook(trigger, channel_types=None, channel_ids=None, directions=None)

Decorator to register an identity-resolution hook.

The decorated function receives (event, context, id_result) and returns an IdentityHookResult or None.

Parameters:

Name Type Description Default
trigger HookTrigger

When the hook fires (ON_IDENTITY_AMBIGUOUS, ON_IDENTITY_UNKNOWN).

required
channel_types set[ChannelType] | None

Only run for events from these channel types (None = all).

None
channel_ids set[str] | None

Only run for events from these channel IDs (None = all).

None
directions set[EventDirection] | None

Only run for events with these directions (None = all).

None

add_room_hook async

add_room_hook(room_id, trigger, execution, fn, priority=0, name='', *, fail_closed=False, needs_lock=True, organization_id=None)

Add a hook for a specific room; the registration held.

fail_closed and needs_lock have the meaning they have on :meth:hook. A hook on a trigger a turn fires (RFC §10.6.6) is the kit's own executor's for the room; while the kit holds a channel by its declaration alone it raises ValueError: define it by name on the executors, executor.room_hook(name, trigger)(fn), and enable the name for the room with :meth:enable_room_hook.

name is unique within the room's hooks (RFC §9.1): one a hook of the room holds, a name the room enables on the executors (:meth:enable_room_hook) included, or a value the framework writes in blocked_by, raises ValueError. Left empty, the hook is named after fn, made unique; the registration returned holds that name.

organization_id is the organization the caller acts for (RFC §17.2): the room is read with it first, and another organization's room raises :class:RoomNotFoundError with no hook registered. Unset, no room is read, and a room id the store does not hold takes the hook as before. :meth:HookEngine.add_room_hook is the synchronous engine call, which reads no room.

remove_room_hook async

remove_room_hook(room_id, name, *, organization_id=None)

Remove a room hook the kit registered, by name; one defined by name on the executors is disabled for the room with :meth:disable_room_hook.

organization_id is the organization the caller acts for (RFC §17.2): another organization's room raises :class:RoomNotFoundError with no hook removed.

enable_room_hook async

enable_room_hook(room_id, name, *, organization_id=None)

Run the room hook name the executors define on a trigger a turn fires (executor.room_hook(name, trigger)(fn)) for room_id's turns (RFC §10.6.6): the turns' requests name it, and only an executor that defines it takes them (RFC §10.6.7).

The name joins the room's hooks, where a name is unique (RFC §9.1): a room hook the kit registered for room_id under name raises ValueError, and so does registering one under a name the room enables. Enabling a name the room enables already changes nothing.

organization_id is the organization the caller acts for (RFC §17.2): another organization's room raises :class:RoomNotFoundError with nothing enabled.

disable_room_hook async

disable_room_hook(room_id, name, *, organization_id=None)

Stop running the room hook name for room_id's turns; whether it ran. organization_id is the organization the caller acts for (RFC §17.2): another organization's room raises :class:RoomNotFoundError with nothing disabled.

Exceptions

RoomNotFoundError

Bases: RoomKitError

Room does not exist.

ChannelNotFoundError

Bases: RoomKitError

Channel binding not found in room.

ChannelNotRegisteredError

Bases: RoomKitError

Channel type not registered.

Infrastructure

RoomLockManager

Bases: ABC

Abstract base for per-room locking.

Implement this to plug in any locking backend (Redis, Postgres advisory locks, etc.). The library ships with InMemoryLockManager for single-process deployments.

Implementations should be reentrant within the same execution context (including child tasks spawned by asyncio.gather): if a coroutine already holds the lock for a room and awaits code that tries to acquire the same room lock, the inner acquisition must succeed without deadlocking. This is required because tool handlers (e.g. handoff) may update room state while the inbound pipeline already holds the room lock.

locked abstractmethod async

locked(room_id)

Acquire an exclusive lock for room_id.

Acquisition MUST be cancellation-safe: the inbound pipeline bounds the wait with process_timeout (RFC §13.6), so a caller that gives up queueing is cancelled here. An implementation that leaves the lock taken, or a reference held, on cancellation strands the room — every later event for it queues behind a lock nobody owns.

close async

close()

Release any resources held by the lock manager (e.g. a connection pool). Called by RoomKit.close(). Default is a no-op; overrides MUST be idempotent.

InMemoryLockManager

InMemoryLockManager(max_locks=1024)

Bases: RoomLockManager

In-process per-room asyncio locks with LRU eviction.

Reentrant within the same execution context: if the current context already holds the lock for a given room (including child tasks spawned by asyncio.gather), locked() yields immediately instead of deadlocking.

Suitable for single-process deployments. For multi-process or distributed setups, provide a custom RoomLockManager backed by Redis, Postgres advisory locks, or similar.

size property

size

Return the number of locks currently held.

locked async

locked(room_id)

Acquire the lock for a room (reentrant via ContextVar).

AuthCallback module-attribute

AuthCallback = Callable[[Any], Awaitable[dict[str, Any] | None]]

Async callback for transport authentication.

Receives the connection context (e.g. WebSocket, HTTP request) and returns a metadata dict on success or None to reject the connection.