Expand description
Domain model and ports (traits) of okbot; the SDK for third-party adapters.
okbot follows a ports-and-adapters architecture (ADR 0001). This crate holds the types every other crate speaks and the traits adapters implement. It performs no I/O.
| Port | Implemented by | Used by |
|---|---|---|
Channel | one crate per chat platform | the runtime |
InboundSink | the runtime | channels, to deliver events |
AgentBackend | agent CLIs, fallback chains | the runtime |
ConversationStore | SQLite store | the runtime |
KnowledgeProvider | okbase integration | the runtime |
MemoryStore | okbase integration | the runtime (chat commands) |
TaskStore | okbase integration | the runtime (chat commands, scheduler) |
Renderer | Markdown dialect renderer | the runtime |
Clock | SystemClock, test clocks | everything that reads time |
§Writing a channel
A platform adapter implements Channel: receive events and hand them to the InboundSink,
send rendered replies. Everything else (policy, agents, knowledge) is the runtime’s job.
use std::sync::Arc;
use okbot_core::{
async_trait, CancellationToken, Channel, ChannelCaps, ChannelError, ChannelId, InboundSink,
MessageId, RenderedMessage, ReplyTarget, SentRef,
};
struct EchoChannel { id: ChannelId, caps: ChannelCaps }
#[async_trait]
impl Channel for EchoChannel {
fn id(&self) -> &ChannelId { &self.id }
fn caps(&self) -> &ChannelCaps { &self.caps }
async fn run(&self, _sink: Arc<dyn InboundSink>, shutdown: CancellationToken)
-> Result<(), ChannelError> {
// Connect to the platform and call `sink.deliver(event)` for each message.
shutdown.cancelled().await;
Ok(())
}
async fn send(&self, to: &ReplyTarget, message: &RenderedMessage)
-> Result<SentRef, ChannelError> {
println!("{}", message.text);
Ok(SentRef { target: to.clone(), message_id: MessageId::new("1") })
}
}
let channel = EchoChannel { id: "echo:demo".parse().unwrap(), caps: ChannelCaps::basic() };
assert_eq!(channel.id().to_string(), "echo:demo");Structs§
- Agent
Caps - What an agent backend can do natively. Missing capabilities are emulated or the backend is skipped.
- Agent
Reply - The result of a successful turn.
- Agent
RunRecord - One agent run, for the audit table.
- Agent
Turn - One agent turn.
- Cancellation
Token - Re-exported so adapters use the same cancellation type as the runtime. A token which can be used to signal a cancellation request to one or more tasks.
- Channel
Caps - What a channel can do. The runtime adapts its behaviour to these values.
- Channel
Id - One configured instance of a chat platform, written
platform:instance(zalo:shop). - Command
Info - A command for the platform’s command menu (
/on Discord and Telegram). - Command
Param - A parameter of a
CommandInfo. - Conversation
Key - Identifies one conversation. Messages with the same key are handled in order and share history.
- Fire
- One firing of a task: the task id and its planned time identify it.
- Form
- A small form (a Discord modal: up to five text fields).
- Form
Field - One text field of a
Form. - Inbound
Event - A message received from a platform, normalized by its channel adapter.
- Knowledge
Context - Knowledge placed in the system prompt.
- McpServer
- An MCP server the agent may call during a run.
- Memory
Entry - A stored note.
- Memory
Note - A note to save.
- Message
Id - A message id as the platform reports it.
- NewMessage
- A message to store.
- NewTask
- A task to create.
- Outbound
Message - A reply in canonical Markdown, before rendering for a platform.
- Person
- Several platform accounts of one human, linked by the operator.
- Progress
Fn - Receives
AgentProgress; called from the backend’s output reader, so keep it quick. - Prompt
- A message with buttons, shown in one conversation.
- Prompt
Answer - Someone pressed a button (and filled in its form).
- Prompt
Button - A button under the prompt message. With a
Form, pressing it opens the form and the answer carries the values. - Redactor
- Replaces known secret values in text (log lines, error messages) with
[REDACTED]. - Rendered
Message - One platform message, already in the platform’s dialect and within its length limit.
- Reply
Target - Where a reply goes.
- Requester
- Who is asking, which decides what knowledge and memory is visible.
- Resume
- A native session to continue.
- Role
Grant - A role given to an account for a limited time (
okbot role grant,/grant). - RunGrant
- Access to knowledge tools for one agent run. Dropping it revokes the access.
- RunId
- The id of one agent run, used in logs and the audit table.
- RunInfo
- What a run needs from the knowledge tools.
- Secret
- A secret value that never shows up in
Debugoutput or logs. - SentRef
- A message the bot sent, for later edits.
- Sink
Closed - The runtime stopped accepting events (it is shutting down).
- Stored
Message - A stored message.
- System
Clock - The system clock.
- Task
- A stored task.
- Task
Change - Changes to a task;
Noneleaves a field as it is. - Token
Usage - Token accounting, when the backend reports it.
- Tool
Call Record - One call of an
[[mcp]]tool, by an agent or a chat command. Arguments and results are not kept: they may hold secrets. - Usage
- What one person used over a period.
- UserId
- A user id as the platform reports it, unique within one
ChannelId. - UserRef
- Who wrote a message.
- Webhook
Request - An HTTP request delivered to a webhook.
- Webhook
Response - The response to a webhook request.
Enums§
- Agent
Error - Why a turn failed.
- Agent
Progress - Progress while an agent works.
- Attachment
- Media attached to a message. Platforms that deliver media do so by URL.
- Button
Style - What a button looks like.
- Channel
Error - An error from a channel adapter.
- Field
Style - How much text a form field takes.
- Fire
State - Where one firing of a task is (design §5.6).
- IdError
- An invalid identifier.
- Knowledge
Error - A knowledge failure.
- Length
Unit - How a platform counts message length.
- Markdown
Dialect - The Markdown flavour a platform displays.
- Memory
Error - A memory operation failed.
- Memory
Scope - Who a note is for.
- Message
Role - Who wrote a stored message.
- Notify
To - One destination of a
[[notify]]target, written as text inokbot.toml. - Repeat
- When a task fires again, written
daily 08:00,weekdays 08:00,weekly mon,fri 09:00,monthly 1 09:00orevery 3h. - Store
Error - A storage failure.
- Task
Error - A task operation failed.
- Task
Kind - What a task does when it fires.
- Task
Status - Where a task is in its life.
- Tool
Decision - What happened to a tool call (ADR 0011).
- Tool
Policy - Which tools an agent may use in a room (design §4.4). No policy grants a shell or file access.
Constants§
- MAX_
BUTTONS - Limits every channel can honour (Discord’s are the tightest).
- MAX_
FIELDS - Fields per form.
- PAIRING_
MAX_ FAILURES - Wrong pairing codes tolerated before pending codes are cancelled.
Traits§
- Agent
Backend - Runs agent turns (design §4.1).
- Channel
- A chat platform adapter (design §3.2).
- Clock
- A source of the current time, replaceable in tests.
- Conversation
Store - Stores conversations, deduplication marks and the audit trail (design §6.1).
- Inbound
Sink - Receives normalized events from channels. Implemented by the runtime.
- Knowledge
Provider - The bot’s knowledge and memory (design §5).
- Memory
Store - Saves, lists and forgets notes, always within the requester’s visibility.
- Renderer
- Turns canonical Markdown into platform messages: the platform’s dialect, each part within its length limit.
- Task
Store - Creates, lists and changes tasks, always within the requester’s visibility.
- Webhook
Handler - Receives webhook requests for one channel.
Functions§
- format_
time - Formats
tsas an RFC 3339 instant with the offset oftz(2026-10-14T08:00:00+07:00). - parse_
time - Reads a time written by a user or an agent: an RFC 3339 instant (
2026-10-14T08:00:00+07:00), a local date-time intz(2026-10-14T08:00,2026-10-14 08:00) or a local date (09:00). - person_
key - The key a person’s usage and audit entries are stored under:
person:<id>for linked accounts ([people], or the owner of a personal bot), else the accountplatform:instance/user-id. - sort_
tasks - Sorts tasks for display: active first, then by the earliest of next firing and due time, then by creation.
Type Aliases§
- BoxError
- A boxed error from an adapter, kept as the
sourceof port errors.
Attribute Macros§
- async_
trait - Re-exported so adapters implement the async traits with the same macro version.