Gateway inbound and turn routing
The gateway turns messages from many chat systems into safe, session-bound agent turns. It identifies the receiving profile, checks access, handles control traffic, prepares text and media, runs the agent, and schedules later work without losing message order or reply context. This page extends gateway service and relates to gateway session lifecycle and gateway platform delivery.
Inbound message flow
An inbound event moves through one shared path before it can start agent work. The path keeps transport identity, user permission, session choice, and turn execution separate so a rejected event cannot create session or agent state.
This diagram shows the main route from a platform event to an agent result or a controlled reply.
flowchart TD
A[Platform event] --> B[Normalize event and source]
B --> C[Resolve profile and transport identity]
C --> D{Ingress checks}
D -->|Rejected| E[Drop or send access reply]
D -->|Admitted| F[Pause and pending-reply checks]
F --> G{Session busy?}
G -->|Yes| H[Control, steer, interrupt, or queue]
G -->|No| I[Command dispatch]
I -->|Handled| J[Command reply]
I -->|Agent work| K[Resolve session and prepare input]
H -->|Next turn| K
K --> L[Run agent turn]
L --> M[Persist and deliver result]
M --> N[Drain follow-up or schedule internal work]
Event normalization
The platform adapters produce a common MessageEvent with text, media paths, reply data, message identity, control permission, and an internal flag. Its SessionSource describes where the message came from and supplies the stable facts used for authorization, session routing, and reply delivery. References: gateway/…/event.py• L24-103, gateway/session.py• L65-100
The gateway canonicalizes routing identity before it derives a session key. In a multi-profile gateway, the identity records both the profile that received the event and the profile where the turn runs. An explicit route to an unserved profile fails closed instead of falling back to the default profile. References: gateway/run_adapters.py• L1683-1702, gateway/run_inbound.py• L186-197
Admission gates
Admission decides whether an event may affect the gateway. It drops ignored channels and messages held during startup restore before they reach pairing or session state. It then runs the pre-dispatch hook, checks user or chat authorization, and admits bot-originated traffic only when the loop guard allows it. References: gateway/run_inbound.py• L167-261
Unauthorized direct messages have a deliberate split between access and disclosure. Pairing mode can issue a rate-limited code. Decline mode sends a limited refusal. Ignore mode gives no reply to the sender and sends the owner a bounded diagnostic when a home channel exists. References: gateway/run_inbound.py• L110-165, gateway/run_inbound_unauthorized.py• L4-11, gateway/run_inbound_unauthorized.py• L75-113
Control boundaries
The gateway checks the emergency pause after authorization, so unauthorized users cannot learn its state. Recognized commands and replies that belong to active work can still pass through because they control or settle that work rather than start a new agent turn. References: gateway/run_inbound.py• L263-314
Pending update, clarify, and confirmation prompts consume matching replies before ordinary command or agent routing. They remain pending when the message is a command or an invalid choice that should be handled elsewhere. References: gateway/run_inbound.py• L1219-1231, gateway/run_inbound.py• L330-499
Command routing
Commands are a separate control lane from conversational input. The gateway resolves a command to its canonical name, checks per-source command access, runs hooks, and then dispatches the command or rewrites it into an agent prompt.
Idle command dispatch
When no agent owns the session, the gateway checks built-in commands first. It then checks configured quick commands, plugin commands, and skill or bundle commands. Unknown slash commands receive a clear reply instead of being sent to the model as user prose. Some commands acknowledge the user and rewrite the event so the resulting agent turn keeps normal transcript and role boundaries. References: gateway/run_inbound.py• L811-855, gateway/run_inbound.py• L1047-1105, gateway/run_inbound.py• L1158-1217, gateway/run_inbound.py• L1233-1250
Busy command dispatch
While an agent is running, control commands bypass normal busy input handling. Access checks apply again on this path so an active session cannot become a command privilege bypass. Approval replies and stop or reset actions stay inline because routing them through a later background task could race the live session. References: gateway/run_inbound.py• L592-622, gateway/run_inbound.py• L693-745, gateway/run_busy.py• L807-905, gateway/run_busy.py• L1117-1138
Media and text preparation
Preparation converts platform-specific content into one model-facing message while preserving the original event for routing and delivery. It runs under the destination profile scope, which keeps media files, model choice, secrets, and tools aligned with the profile that owns the turn.
Attachment preparation
The gateway classifies each attachment by its own MIME type before using the message-level type. Images go to native vision input when the model supports it, or to a short vision description otherwise. Voice input goes through speech-to-text, while audio files, video, and documents get notes that point the agent to their local paths. References: gateway/run_inbound.py• L1447-1467, gateway/run_inbound.py• L1469-1503, gateway/run_inbound.py• L1541-1591
Inbound media is first moved into the active profile cache when the receiving adapter cached it under the launch profile. This keeps the file visible to the routed agent and prevents a valid attachment from pointing at an empty cache in a different profile. References: gateway/run_inbound_media.py• L15-51
Voice and reply context
Voice transcripts can be echoed to the user once so the user can check recognition quality. Failed or empty recognition becomes a neutral message note rather than an invented request. Reply text and reply identity are added after context-reference expansion, so quoted content cannot trigger a local file read on behalf of the replier. References: gateway/run_inbound.py• L1505-1529, gateway/run_inbound.py• L1901-1942, gateway/run_inbound.py• L1678-1740
Model-facing message
The final input can include sender attribution for shared chats, channel context, media notes, expanded references, and reply pointers. These additions are model context; the original authored text remains available for titles and durable transcript records. References: gateway/run_inbound.py• L1426-1445, gateway/run_inbound.py• L1709-1752, gateway/run_turn.py• L2035-2142
Session and turn admission
After controls and preparation gates pass, the gateway binds the event to a session. The session key is a stable lane for a platform chat, thread, participant, and profile. The session entry then maps that lane to durable conversation state and the adapter that may answer it.
Session key routing
Session keys separate profiles and apply platform-specific chat rules. Direct messages normally isolate by chat or sender. Groups and threads can be shared or per-user based on policy. Slack workspace scope and platform-specific identity aliases prevent unrelated conversations from sharing one lane. References: gateway/session.py• L653-723
The session store creates or recovers one durable session for the key. It preserves the session origin for later delivery, handles reset and ended-session recovery, and serializes overlapping lookups so concurrent inbound events do not create competing session rows. References: gateway/session.py• L481-618, gateway/session.py• L764-803, gateway/session.py• L891-974
Turn ownership
The gateway claims the session before its long asynchronous setup begins. A pending sentinel marks the lane as busy immediately, and a turn lease protects the durable transcript when more than one routing key can reach the same session. A durable active-turn marker also gives startup recovery an exact session to resume after an unclean exit. References: gateway/run_inbound.py• L1340-1360, gateway/run_turn.py• L605-624, gateway/run_inbound.py• L1768-1809
Turn preparation
Turn preparation opens or resets the session, builds the pinned session context, loads transcript history, applies hygiene checks, and prepares the model-facing event. It stages per-turn notes only after early rejection points and marks the turn durable only after it owns the lease. References: gateway/run_turn.py• L2047-2142
Agent turn execution
The admitted event becomes an agent turn only after routing and preparation succeed. The turn runner connects the session history and model-facing input to model calls, tool progress, streaming, transcript persistence, and final delivery.
Agent execution boundary
The runner emits an agent-start event, verifies that the turn still owns the session, and runs the agent with the resolved source, session, reply anchor, inbound message identity, and persistence data. It shapes the result, records the transcript, and sends the response through the adapter chosen for that source. References: gateway/run_turn.py• L2144-2213, gateway/run_turn.py• L2235-2269
The turn context carries the values shared by the agent worker and gateway loop. It keeps reply expectations, progress state, stream consumers, session identity, inbound identity, and delivery metadata tied to one turn. References: gateway/turn_context.py• L14-102
Agent delivery
Delivery can include streamed text, progress or status updates, generated media, and the final response. The final response is linked to the inbound message identity for delivery deduplication, while the reply anchor remains the platform-specific target for the reply. References: gateway/run_turn.py• L3811-3889, gateway/…/base.py• L4526-4647
Busy input and follow-up routing
Messages that arrive during an active turn do not all have the same meaning. The gateway treats control traffic as immediate, supports steer or interrupt modes for corrections, and stores ordinary follow-ups for later turns when immediate handling is unsafe or not requested.
Busy input modes
The effective busy mode chooses among queue, steer, redirect, and interrupt behavior. Text can steer or redirect a live agent when supported. Voice and other media are prepared before steering or interruption. Active subagents and in-flight compression demote interruption to queue so the follow-up cannot break work that must finish as a unit. References: gateway/run_inbound.py• L652-745, gateway/run_busy.py• L583-635
Follow-up queue
Queued messages use one pending slot plus a FIFO overflow list. Photo bursts may merge because they describe one media burst. Text, voice, audio, video, and document messages keep their turn boundaries, so separate user messages do not become one ambiguous request. The queue has a cap and preserves security metadata when events merge. References: gateway/run_busy.py• L100-139, gateway/run_busy.py• L368-425
Follow-up drain
After a turn completes, the gateway hands the next event to a fresh task instead of recursing or starting a second owner in parallel. The follow-up is prepared through the same profile-scoped path as the first event, and the first response is delivered before the next turn continues when needed. References: gateway/…/base.py• L4638-4685, gateway/…/base.py• L4722-4747, gateway/run_turn.py• L3811-3889
Queued platform messages still receive processing lifecycle hooks. Synthetic events without a real platform message stay silent, while real queued messages retain the adapter's start and completion behavior. References: gateway/run_turn_followup_ack.py• L1-60
Internal work scheduling
The gateway uses the same turn route for work created by the gateway itself, but marks that work as internal so it does not pretend to be a human message. This lets background results, goals, and heartbeats reuse session context and delivery rules without passing through user authorization.
Background notifications
Process completion and delegation notifications become synthetic events with explicit machine provenance. They target the stored session route, preserve profile and thread data, and enter the turn only after durable delivery claims and admission checks succeed. References: gateway/run_notifications.py• L75-111, gateway/run_notifications.py• L125-176
Goal and heartbeat work
Goals and heartbeats resolve the session that owns the watch, then inject a prompt when the lane is available. Busy sessions leave the tick unclaimed so the work can try again later. Internal events do not update the user activity clock, and scheduled heartbeat turns keep routine progress quiet. References: gateway/run_goals.py• L48-110, gateway/run_goals.py• L123-140, gateway/turn_context.py• L17-21, gateway/run_turn.py• L4290-4302
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to
SessionSource, routing identity, or session-key fields must preserve the match between profile namespace, durable origin, authorization scope, and delivery adapter. - Changes to admission order must keep ignored-channel and authorization gates before session creation, and must keep busy-path authorization equivalent to the idle path.
- Changes to
MessageEventmedia or control fields must update both normal inbound preparation and queued follow-up preparation. - Changes to busy queue behavior must preserve FIFO boundaries, photo-burst merging, queue caps, and security metadata separation.
- Changes to follow-up draining must keep one owner per session and must keep the follow-up's inbound identity separate from its reply anchor.
- Changes to synthetic notification or heartbeat routing must preserve internal provenance and the rule that internal work does not count as user activity.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| An event derives a key before profile identity is canonical | Traffic can enter the wrong profile session or fall into the default lane | Canonicalize at adapter and runner ingress before key derivation |
| A secondary profile's media stays in the launch cache | The agent receives a path that is not visible in its profile sandbox | Re-home inbound media inside the routed profile scope |
| Busy text messages overwrite one pending slot | Separate user requests arrive as one merged turn or one request is lost | FIFO overflow with merge limited to photo bursts |
| A queued event starts through a second owner task | The same session can load and write its transcript concurrently | Keep the session guard live and hand off to a fresh drain owner |
| A busy-path control command enters ordinary interrupt handling | An approval or stop reply may fail to settle the live work | Inline command bypasses before steer, interrupt, or queue routing |
| A stale follow-up is replayed after a failed drain | The gateway can hot-loop on one event or send a duplicate final | Identity-aware requeue backoff and one-shot delivery ledger keys |
| A background notification looks like human text | The agent may reply to an old message or count machine work as user activity | Internal event marker, notification footer, and muted routine delivery |
Key files
| File | Why to read it |
|---|---|
| gateway/…/event.py | Defines the normalized inbound event and control fields |
| gateway/session.py | Defines source identity, session keys, durable routing entries, and session recovery |
| gateway/run_adapters.py | Shows profile-scoped message and busy handlers and identity setup |
| gateway/run_inbound.py | Shows the shared admission order, commands, media preparation, and turn claim |
| gateway/run_inbound_unauthorized.py | Shows pairing, decline, and owner-side behavior for unauthorized senders |
| gateway/run_inbound_media.py | Shows profile-aware attachment re-homing |
| gateway/run_busy.py | Shows busy input modes, FIFO queueing, and command access checks |
| gateway/run_turn.py | Shows session preparation, agent execution, delivery, and queued follow-up turns |
| gateway/…/base.py | Shows adapter guards, background processing, and follow-up ownership handoff |
| gateway/run_notifications.py and gateway/run_goals.py | Show how background completions, goals, and heartbeats become internal work |