Messaging platform integration
Messaging platform integration turns Discord and Telegram messages into managed conversational turns and sends the resulting status, transcript, and control replies back to the same chat. It keeps platform rules at the boundary so the shared messaging workflow can handle commands, conversation state, Claude sessions, and voice input in one way.
Platform boundary
The platform boundary connects an external bot service to the shared messaging workflow. Each supported platform accepts events, checks that they belong to an allowed source, and converts them to the common IncomingMessage model before any conversation work starts.
Platform adapters
The Discord adapter reads messages from allowed channel IDs. It ignores bot authors and unsupported channels, and it preserves the channel, message, user, reply, and display-name data needed to manage a turn. The Telegram adapter applies an optional user allowlist and preserves chat replies and forum topic IDs so a response stays in the right thread. See src/…/discord_inbound.py and src/…/telegram_inbound.py.
Both adapters produce the same message shape even though Discord and Telegram use different event models. This gives later stages a stable identity made from the platform and chat scope plus the source message ID. The raw platform event remains available at the boundary for active handling but is not part of durable conversation state. See src/…/models.py.
References: src/…/discord_inbound.py• L16-74 src/…/telegram_inbound.py• L12-73 src/…/models.py• L8-57
Platform composition
The platform factory selects no platform, Telegram, or Discord from application settings. For an enabled platform it assembles the runtime, outbound messenger, rate control, and optional voice cancellation boundary as one MessagingPlatformComponents bundle. A missing bot token causes that platform to be skipped rather than creating a partial runtime. See src/…/factory.py.
The application gives the bundle to one MessagingWorkflow, restores saved conversation state, registers the workflow as the inbound handler, and then starts the platform runtime. This keeps platform startup separate from the work that owns conversational state. See src/…/application.py.
References: src/…/factory.py• L12-109 src/…/ports.py• L13-99 src/…/application.py• L340-434
Managed turn handoff
A managed conversational turn is an accepted user request with a source identity, a status message, a place in a conversation tree, and a claim for the work that will produce its reply. The workflow first commits the turn and its status ownership, then allows the queue processor to run it. This order prevents a stop or clear action from racing with an admission that is not yet durable.
Message classification
The workflow first separates commands and internal status text from user prompts. A command such as /stop, /clear, or /stats acts on the current platform scope instead of starting Claude work. A normal prompt can resolve a replied-to message as a parent, which lets the conversation tree continue from the selected turn. See src/…/turn_intake.py and src/…/commands.py.
For a prompt that can start work, the system sends or updates a status reply before it admits the turn. It then checks an admission token, which is a snapshot of the current stop and clear boundaries, and commits the status record with the tree change. A stale token rejects the turn and removes the temporary status. A missing parent also rejects the turn because the requested reply branch no longer exists. The child page Messaging turn workflows describes this lifecycle in detail.
References: src/…/turn_intake.py• L54-155 src/…/workflow.py• L342-427 src/…/commands.py• L29-182
Conversation ownership
The workflow owns the boundary between platform messages and durable conversation state. It uses the platform and chat as the message scope, while the tree manager owns prompt references, status references, queue state, and the active execution claim for that scope. A tree transition is saved as one unit; if storage rejects it, the in-memory tree and its reference index roll back or enter an interrupted state rather than silently diverging. The manager also protects a committed transition from caller cancellation, so cleanup can use the result that matches the durable state. See src/…/manager.py.
Reply resolution accepts either the user prompt or the managed status message as an exact reference. Reply-scoped stop cancels the owner of that reference. Reply-scoped clear removes the literal platform reply subtree and its tracked message IDs. Standalone stop and clear operate across the wider chat or runtime according to the command. These actions publish their durable boundary before cancellation effects so new admissions cannot enter state that the user has already removed.
The tree manager exposes detached transition results to the workflow. These results say which status messages need updates and which platform messages need deletion, while the workflow remains responsible for the user-visible effects. The conversation tree page Messaging conversation trees explains branches, queues, storage, and restoration in detail.
References: src/…/workflow.py• L387-565 src/…/manager.py• L165-240 src/…/manager.py• L445-631 src/…/transaction.py• L14-51 src/…/ports.py• L10-35
Turn path
The following path shows how a platform event becomes a managed turn and then a platform reply.
flowchart LR
A[Discord or Telegram event] --> B[Platform adapter]
B --> C[IncomingMessage]
C --> D{Command or prompt}
D -->|command| E[Control action and reply]
D -->|prompt| F[Status message]
F --> G[Admission boundary]
G --> H[Conversation tree claim or queue entry]
H --> I[Claude session and transcript]
I --> J[Platform rendering]
J --> K[Managed outbound delivery]
References: src/…/ports.py• L10-44 src/…/turn_intake.py• L54-155 src/…/manager.py• L165-240 src/…/node_runner.py• L164-331
Reply delivery
Reply delivery converts shared status and transcript text into platform-safe messages. It supports sends, edits, and deletes through one outbound contract, while each platform keeps its own reply syntax, size rules, and API error behavior.
Outbound messaging
Discord and Telegram expose the same delivery actions: send a message, edit a status or reply, delete managed messages, and run work without blocking the main conversation task. The shared outbox sends these actions through a rate-limited worker and compacts repeated edits for the same message, so a fast stream does not create an unbounded set of stale updates. The limiter also pauses later work when a platform rate limit outlasts the failed call's retry budget. See src/…/outbox.py and src/…/limiter.py.
The platform messengers preserve reply targets and Telegram thread targets. Telegram classifies failed calls into network loss, rate limits, formatting errors, known missing messages, and other rejection cases. It retries transient calls within one shared attempt budget, can resend without formatting when Telegram rejects markup, treats known no-op or missing-message results as delivered when safe, and passes an exhausted platform limit to the queue so later work waits. Discord retries calls lost on the network through the shared failure policy. It reuses a send nonce across retries so a lost response does not create a duplicate message. Missing messages are non-fatal for edits and deletes, while sent text is limited to Discord's message size. See src/…/telegram_io.py and src/…/discord_io.py.
The delivery failure policy is shared as platform-neutral outcomes. It lets adapters map service-specific errors to retry, plain-text retry, ignore, queue pause, or final failure without changing the outbox contract. See src/…/decision.py and src/…/queue.py.
References: src/…/ports.py• L32-63 src/…/outbox.py• L20-143 src/…/limiter.py• L18-24 src/…/limiter.py• L62-152 src/…/limiter.py• L154-209 src/…/limiter.py• L220-246 src/…/telegram_io.py• L63-173 src/…/decision.py• L6-92 src/…/queue.py• L4-16 src/…/discord_io.py• L28-50 src/…/discord_io.py• L72-182
Rendering profiles
Each platform has a rendering profile that supplies status text, markup escaping, transcript formatting, and a safe output limit. Discord uses its native text rules. Telegram uses MarkdownV2 and keeps forum replies in their message thread. The profile lets the workflow describe one status or transcript while the final reply matches the target service. See src/…/profiles.py.
Transcript assembly, streamed output, tables, and voice-specific rendering are covered by Messaging transcripts, rendering, and voice. This page only treats rendering as the contract that connects shared conversation output to each platform.
References: src/…/profiles.py• L29-53 src/…/telegram_inbound.py• L35-72 src/…/telegram_io.py• L175-222
Voice-note handoff
Voice input follows the same managed-turn path as text after transcription. The platform adapter supplies a normalized voice request with download and reply actions, while the shared voice flow owns the temporary status, transcription, cancellation, and handoff to the normal message handler.
Voice input
Discord treats an audio attachment as voice input when its metadata identifies an audio file. Telegram treats a voice update as voice input. Both paths enforce the source allowlist before they download audio. They create a status reply first, then download and transcribe the audio within a pending voice claim.
After transcription, the flow creates an IncomingMessage with the original message identity and the transcribed text. The normal handler then classifies commands, resolves replies, and admits the turn. This preserves one conversation model for typed prompts and voice prompts. See src/…/voice_flow.py.
References: src/…/discord.py• L160-189 src/…/telegram.py• L275-300 src/…/voice_flow.py• L36-58 src/…/voice_flow.py• L144-245
Voice cancellation
Pending voice work has ownership before it enters a conversation tree. Stop and clear can cancel that work by reply, chat, or whole runtime. If cancellation happens after a status reply exists, the platform edits that status to show the stopped state or removes it when the handoff never became valid. A missing transcriber, bad audio, or an over-size file produces a user-facing failure without leaving pending ownership behind. See src/…/voice_flow.py and src/…/workflow.py.
References: src/…/voice_flow.py• L116-142 src/…/voice_flow.py• L246-359 src/…/workflow.py• L432-605
Runtime lifecycle
The runtime lifecycle protects both platform connections and managed state. Startup restores saved conversations before accepting new events, and shutdown stops work before it closes outbound delivery and rate control.
Connection state
Discord starts a client and waits for its ready event. Telegram initializes the bot application and starts polling. Both runtimes expose a common start, quiesce, close, message-handler, and connection contract, so the application can manage either platform in the same sequence. See src/…/ports.py.
Quiescing first stops new inbound work and drains active handlers. Closing then cancels outstanding outbound work and releases platform resources. This ordering prevents a late event from creating a turn after the workflow has begun to shut down. See src/…/discord.py and src/…/telegram.py.
References: src/…/ports.py• L13-30 src/…/discord.py• L207-319 src/…/telegram.py• L105-239
State restoration
The workflow restores conversation trees before the platform starts and asks the tree manager to normalize saved links and indexes. Nodes that were pending or processing when the server stopped become interrupted records instead of silently resuming. When delivery becomes available, their status messages are marked as interrupted by a server restart. Invalid or duplicate saved trees are skipped so one bad record does not prevent the rest of the conversation state from loading. See src/…/workflow.py and src/…/repository.py.
The manager saves changes through a storage port and uses transaction checkpoints to restore its in-memory state after a failed write. This keeps later reply lookup and clear operations aligned with the durable snapshot. See src/…/manager.py and src/…/transaction.py.
References: src/…/workflow.py• L182-224 src/…/repository.py• L93-143 src/…/runtime.py• L510-522 src/…/transaction.py• L29-51
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to
IncomingMessageidentity, reply, or thread fields must stay aligned with both inbound adapters, reply lookup, managed-message tracking, and outbound reply targets. - Changes to command scope must preserve the distinction between reply-scoped ownership and whole-chat cleanup. The
/clearpath must still remove the message IDs tracked by the session store. - Changes to admission tokens or tree transitions must preserve the order of status tracking, durable tree commit, and processor launch. A turn must not become runnable before its state is safe to find or remove.
- Changes to prompt or status references must update graph lookup, repository indexes, exact subtree deletion, and restored snapshot validation together.
- Changes to storage commit or rollback must preserve the manager lock and the transaction checkpoint. A failed write must not leave in-memory references that are absent from the store.
- Changes to status or transcript text must update both rendering profiles and their parse-mode and size contracts. A valid shared string is not automatically valid Telegram MarkdownV2 or a Discord message.
- Changes to delivery failure classification must keep platform error mapping, retry outcomes, attempt limits, and queue-wide pause behavior aligned. A rate limit that is handled only by one call can still overload later queued calls.
- Changes to voice handoff must preserve status-message ownership across transcription, cancellation, failed cleanup, and normal turn admission.
- Changes to platform startup must keep factory wiring, handler registration, state restoration, quiescing, and outbound shutdown in the same lifecycle order.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A platform token or required SDK is missing | The selected runtime cannot start and no managed turns are accepted | Factory token checks and runtime dependency checks |
| A message comes from a disallowed Telegram user or Discord channel | The event is ignored without entering conversation state | Inbound allowlists before normalization handoff |
| Stop or clear changes the admission boundary before a prompt commits | The temporary status is removed and no tree node is created | Admission tokens checked under the workflow state lock |
| A reply parent or status reference was removed | The prompt is rejected rather than attached to a wrong branch | Scope-aware reference indexes and exact parent validation |
| Telegram reaches its retry budget during a rate limit | The current call fails and queued delivery pauses for the platform-provided delay | Shared failure decision and limiter queue pause |
| Telegram rejects formatted text | The call can fail even though the content is valid as plain text | Unparseable failure classification and plain-text retry |
| A platform rejects or limits an outbound call | A status or reply can be delayed, retried, compacted, or reported as failed | Shared rate limiter, platform failure policy, and markup fallback |
| A Discord send loses its network response | A retry could duplicate the visible reply if the first send succeeded | Network retry policy and a stable nonce for the send operation |
| A tree transition cannot be saved | The transition is rolled back or the conversation is marked interrupted for cleanup | Manager transaction checkpoints and storage-error gating |
/stop or /clear crosses a turn execution boundary | A temporary status or prompt could become an orphan unless the committed transition owns the cleanup | Detached cancellation effects, claim cancellation, and tracked-message cleanup |
| A server restart leaves queued or processing work in saved state | Users could see a stale active status for work that no longer runs | Restore reconciliation and interrupted-status repair |
| Voice download or transcription fails before handoff | The voice status could remain pending and future control commands could miss it | Pending voice ownership with cancellation and failed-work cleanup |
Key files
| File | Why to read it |
|---|---|
| src/…/application.py | Shows platform selection, workflow assembly, state restoration, startup, and shutdown order. |
| src/…/ports.py | Defines the platform-neutral runtime, outbound, voice, and composition contracts. |
| src/…/factory.py | Shows how settings become one configured platform bundle. |
| src/…/discord.py | Shows the Discord connection lifecycle and event handoff. |
| src/…/telegram.py | Shows the Telegram polling lifecycle, command entry points, and event handoff. |
| src/…/turn_intake.py | Shows how commands and prompts become status-owned admissions. |
| src/…/workflow.py | Shows the ownership boundary for admission generations, conversation state, control actions, persistence, and platform effects. |
| src/…/manager.py | Shows the public boundary for durable tree transitions, cancellation, subtree removal, queue claims, and cancellation-safe transition results. |
| src/…/runtime.py | Shows the per-conversation ownership of branches, queue state, active claims, and restored interruption state. |
| src/…/transaction.py | Shows how a tree transition becomes a durable write or rolls back. |
| src/…/ports.py | Defines the storage contract for snapshots and managed platform message IDs. |
| src/…/node_runner.py | Shows how one tree claim becomes a Claude session, transcript updates, completion, or failure status. |
| src/…/outbox.py | Shows the shared policy for queued sends, edits, deletes, and background delivery. |
| src/…/decision.py | Defines the shared outcomes for network errors, rate limits, formatting failures, and known missing messages. |
| src/…/queue.py | Defines how an exhausted platform rate limit pauses queued delivery. |
| src/…/limiter.py | Shows per-platform rate control, update compaction, queue pauses, and shutdown. |
| src/…/telegram_io.py | Shows Telegram error mapping, retry behavior, thread-aware delivery, and bulk deletion. |
| src/…/discord_io.py | Shows Discord size limits, network retry behavior, duplicate-safe sends, and missing-message handling. |
| src/…/voice_flow.py | Shows how voice input joins the normal turn path and how pending work is cancelled. |
| docs/messaging-turn-workflows.md | Detailed child page for turn admission, queue progress, and completion. |
| docs/messaging-conversation-trees.md | Detailed child page for durable conversation ownership and reply branches. |
| docs/messaging-transcripts-rendering-and-voice.md | Detailed child page for transcript assembly, platform rendering, and voice services. |