Gateway runtime
The gateway runtime is the long-lived service for chat channels, remote prompts, and web requests. It starts shared process services, keeps conversation sessions across messages, runs accepted work through one turn service, and reports health and readiness to its callers. The service entrypoints page explains how the process starts; this page describes the hosted services after startup begins.
Runtime composition
The gateway joins process setup, credential loading, session-aware chat handling, remote prompt intake, optional scheduled work, chat transports, workspace knowledge services, and the web surface. These parts share lifecycle state and shutdown control, but each surface keeps its own inbound contract.
Startup lifecycle
GatewayController is the process composition root. The production entry provides the ports needed by hosted chat turns and starts the controller, which creates the shared turn service before it starts the web and chat surfaces.
The controller follows one startup sequence:
- Configure logging and load gateway credentials.
- Start credential refresh when the integration secret can change.
- Apply the shared gateway process profile. This loads the common process setup and the capability registrations needed by gateway work.
- Create one shared chat turn handler with capacity and admission rules.
- Start the web service, remote prompt worker, and configured chat transports.
- Host the scheduler when this process owns scheduled work.
- Start workspace knowledge services and web-app loop synchronization when supported.
- Publish component state and mark the process ready.
Missing credentials disable only the related transport. A startup or readiness error marks that component as failed while other components continue when possible. The scheduler can run in a dedicated service instead of inside the gateway process.
References: gateway/…/controller.py• L121-157 gateway/…/controller.py• L179-207 gateway/…/boot.py• L1-40 gateway/startup.py• L77-115
Credential hydration
Credential hydration loads one organization's integration store before the gateway serves traffic. It validates the service identity and selects the configured integration source so chat, prompt, scheduler, and knowledge work use the same organization data.
The gateway treats absent hydration settings as local mode. Partial hosted settings are rejected instead of allowing an unclear organization or credential path. A source change rebuilds the local store and wakes services that depend on current integrations.
References: gateway/…/credential_hydration.py• L1-24 gateway/…/credential_hydration.py• L59-114 gateway/…/credential_hydration.py• L117-203 gateway/…/credential_hydration.py• L215-301
Service state
The runtime keeps an opaque StartedGateway handle for the web server, remote prompt worker, and started chat workers. Each component reports its own state, so one unavailable channel does not hide the state of the others.
Readiness is separate from liveness and component status. The process becomes ready only after required boot work and surface startup complete. Shutdown stops background services and each started surface within a shared time budget, denies work that can no longer receive input, and records whether the stop completed cleanly.
References: gateway/startup.py• L50-74 gateway/…/controller.py• L209-273 gateway/…/controller.py• L334-420 gateway/…/shutdown_budget.py• L17-65 gateway/…/shutdown_record.py• L33-84 gateway/…/readiness.py• L1-21 gateway/…/component_status.py• L18-41 gateway/…/startup.py• L100-117
Scheduled work hosting
The gateway may host the process-wide scheduler beside chat, prompt, web, and knowledge work. The scheduler is a hosted platform service rather than a chat transport. Scheduled agent runs use the same process capacity boundary as other gateway work, while command-line and shell surfaces remain responsible for changing loop data and requesting reloads.
Hosted organizations also use loop synchronization to notice web-app changes without waiting for the normal poll. The web app sends a nudge, and the gateway reads current task data from the control plane. A dedicated scheduler service can own this work instead of the gateway.
References: gateway/…/controller.py• L179-207 gateway/…/controller.py• L305-384 gateway/…/controller.py• L458-487 gateway/…/AGENTS.md• L51-66
Workspace knowledge services
Workspace knowledge services keep connected-integration knowledge current and can mirror it to the web app. They run in the background, so an initial scan does not delay gateway readiness.
The controller starts these services when the gateway hosts the scheduler. A credential reload wakes the scan service so new integrations can be scanned without a process restart. Both services stop with the gateway.
References: gateway/…/controller.py• L386-420 gateway/…/controller.py• L422-451
Runtime flow
This diagram shows how one process start becomes shared turn handling plus web, chat, prompt, scheduled-work, and knowledge services.
flowchart TD
entry[Gateway composition root] --> setup[Credentials and process setup]
setup --> turn[Shared chat turn service]
turn --> surfaces[Web and chat surfaces]
surfaces --> web[HTTP web surface]
web --> prompts[Remote prompt queue and worker]
surfaces --> transports[Chat transport registry]
transports --> channels[Telegram, Slack, Discord, and Buzz]
setup --> scheduler[Optional scheduler host]
scheduler --> knowledge[Workspace knowledge services]
web --> sync[Loop synchronization nudge]
sync --> scheduler
web --> ready[Published state and readiness]
transports --> ready
scheduler --> ready
knowledge --> ready
References: gateway/…/controller.py• L121-157 gateway/…/controller.py• L179-207 gateway/…/controller.py• L386-420 gateway/startup.py• L77-115 gateway/…/startup.py• L64-117
Chat session service
The chat session service turns messages from different platforms into one conversation model. Transport adapters own platform rules and delivery; session resolution and turn execution stay shared so a conversation keeps its state across messages.
Conversation sessions
SessionResolver maps a platform conversation key to a persisted agent session. It applies the organization and actor scope before it creates, restores, rotates, or flushes that session.
Each transport supplies a platform conversation key and actor identity. A new-session request rotates the binding and applies the configured memory policy. Later messages resolve the new binding and continue from its stored history.
References: gateway/…/resolver.py• L1-7 gateway/…/resolver.py• L106-148 gateway/…/resolver.py• L160-193 gateway/…/gateway_chat_context.py• L20-28
Chat turn handling
TurnRunner is the shared chat turn service. A transport gives it text, a resolved session, a platform output channel, and a logger. The runner applies capacity and admission checks, reuses the agent for that logical session, binds the current output, runs the turn, and finalizes the result.
The session-agent pool keeps turns for one session serialized while different sessions can run together up to the process limit. This preserves conversation context and prevents one turn from sending output to another message. Transport output remains platform-specific: Slack, Telegram, Discord, and Buzz format progress, approvals, errors, and final replies for their own platforms.
References: infrastructure/…/turn_runner.py• L1-19 infrastructure/…/turn_runner.py• L59-70 infrastructure/…/turn_runner.py• L122-162 infrastructure/…/session_agents.py• L124-338 infrastructure/…/bindable_output.py• L18-127
Credit admission
Chat turns can require a credit decision after they receive a process capacity slot. Each transport binds the organization, the turn reason, and a stable delivery identifier before it calls the shared turn service.
Hosted LLM routes already meter usage by token, so the gateway does not add a second per-turn charge in that mode. In self-hosted mode metering is disabled. In hosted mode an explicit credit shortfall denies the turn, while an unavailable or incomplete ledger decision does not allow unmetered work.
The delivery identifier makes retries safe at the ledger boundary:
- Telegram uses the update identifier.
- Slack uses the team, channel, and event timestamp.
- Discord uses the message identifier.
- Buzz uses the event identifier.
References: gateway/…/turn_metering.py• L14-85 gateway/…/credits_client.py• L71-101 gateway/…/dispatcher.py• L401-425 gateway/…/inbound_handler.py• L158-181 gateway/…/dispatcher.py• L312-330 gateway/…/inbound_handler.py• L163-187
Inbound controls
Before a chat turn runs, the adapter decides whether the message addresses the bot and resolves the caller's organization and actor scope. Shared middleware then applies authorization, session decisions, conversation locking, approval handling, and cooperative cancellation.
Stop requests bypass the conversation lock so they can reach active or queued work. Timeout and stop paths set a cancellation signal, and a terminal-outcome arbiter ensures that only one of success, failure, timeout, stop, or credit denial updates the external reply.
References: gateway/…/inbound_decision.py• L54-108 gateway/…/attention.py• L89-149 gateway/…/approvals.py• L47-137 gateway/…/active_turns.py• L33-107 gateway/…/terminal_outcome.py• L10-49
Capacity coordination
Chat turns, synchronous web work, remote prompts, scheduled runs, and other gateway agent work share one process capacity gate. Immediate callers reject work when the gate is full; queued background work waits after it has been accepted.
The process gate is separate from a transport's worker pool. A transport pool limits inbound work before the shared turn service, while the process gate limits agent work across the whole gateway.
References: gateway/…/controller.py• L132-144 infrastructure/…/turn_runner.py• L136-147 gateway/…/webapp.py• L53-61 gateway/…/AGENTS.md• L15-24
Remote prompt service
The remote prompt service lets an authorized web caller submit one prompt and retrieve its result later. It uses the shared turn service but collects output for polling instead of sending it to a chat platform.
Prompt request lifecycle
The web API accepts a bounded prompt, caller context, and actor data. It authenticates the request, places the job in a finite queue, and returns a prompt identifier. A later status request exposes a small public state contract:
| State | Meaning |
|---|---|
queued | Accepted and waiting to run. |
running | A worker is processing the prompt. |
done | The worker produced an answer. |
needs_input | The agent needs a user choice. |
failed | The gateway could not admit or complete the turn. |
When a job needs input, the caller submits an answer. The gateway creates a follow-up job on the same session, so the answer continues the earlier exchange. Results remain available for a retention window, and errors use stable public codes.
References: gateway/…/prompt_routes.py• L1-9 gateway/…/prompt_routes.py• L43-100 gateway/…/jobs.py• L33-100 gateway/…/jobs.py• L103-169
Prompt execution
The prompt worker runs each accepted job through the shared turn service. A worker thread holds one prompt at a time, while the queue prevents two prompts for the same conversation from running together. A separate heartbeat keeps unsettled jobs visible while turns run.
For a new prompt, the worker binds organization and actor scope before it opens the session. It then carries that scope into usage attribution, credit admission, integration selection, progress, and collected output. Follow-ups resume the same session and carry forward the question, one-time approval grants, and the full known request-and-answer chain when stored history is not available.
If the agent asks a question or needs approval, the worker exposes needs_input and waits for a later answer. An approval grant applies to one exact tool call and is cleared if its answer is cancelled. Invalid answers reopen the question. A cancelled answer also reopens the question it answered. The worker reports failed integrations separately from turn failure and stops after its current job when shutdown begins.
References: gateway/…/worker.py• L100-204 gateway/…/worker.py• L206-301 gateway/…/worker.py• L303-422 gateway/…/worker.py• L424-475 gateway/…/worker.py• L502-527 gateway/…/output.py• L15-65
Prompt hosting boundary
The prompt queue exists only when full gateway startup attaches it to the web application. A standalone web process can serve health and readiness routes, but it reports prompt intake as unavailable because no gateway worker owns the queue.
References: gateway/startup.py• L77-133 gateway/…/prompt_routes.py• L43-108 gateway/…/webapp.py• L53-61
Transport adapters
The transport layer adapts platform events to the shared chat contract. Each adapter authenticates and filters inbound events, resolves a session, creates platform output, binds usage and credit data, and invokes the injected turn handler.
Transport registry
gateway/…/startup.py is the registry for chat transports. It starts each configured platform and retains a worker handle for each one that starts. Missing credentials disable only that platform; startup or readiness failures mark only that platform as failed.
The registry serves four chat transports:
| Transport | Inbound model | Runtime role |
|---|---|---|
| Telegram | Long polling | Receives bot updates and sends chat replies. |
| Slack | Socket Mode or signed Events API HTTP | Receives events and replies in threads. |
| Discord | Gateway connection | Receives events and sends channel replies. |
| Buzz | Mention polling | Receives mentions and sends channel replies. |
Web runs beside this registry. It is not a chat transport because its requests do not use a platform conversation or platform output channel.
References: gateway/…/names.py• L1-15 gateway/…/startup.py• L20-40 gateway/…/startup.py• L64-117
Platform adapters
The four adapters keep connection, security, session, and output rules local to each platform. They all call the same transport-neutral turn handler, so a platform-specific change does not create another agent execution path.
Slack uses thread-scoped sessions for channel mentions and one session for a whole direct message conversation. It filters bot and bookkeeping events, accepts file-share input, and uses an attention gate for untagged thread replies. It marks work in the triggering thread and reports a final result through Slack's message and status controls.
Discord requires a ready gateway connection. It can seed a session from recent thread history and adds attachment context when present. It reports work with reactions, edits its status output during the turn, and splits long final answers into platform-sized messages.
Telegram and Buzz use detached polling dispatch so the poll loop stays responsive to later updates and approval callbacks. They protect inbound messages with platform identity rules, use edit-in-place output, and run turn work in an executor. Telegram drains active turns during shutdown and denies approvals that can no longer receive a callback. Buzz resolves the sender's public-key scope before it opens a session.
All adapters use a bounded turn timeout and cooperative cancellation. The timeout or a user stop prevents a late duplicate result, but it does not forcibly kill an in-flight provider request.
References: gateway/…/events.py• L35-125 gateway/…/dispatcher.py• L119-225 gateway/…/dispatcher.py• L264-461 gateway/…/dispatcher.py• L86-145 gateway/…/dispatcher.py• L181-366 gateway/…/background.py• L66-176 gateway/…/inbound_handler.py• L41-227 gateway/…/inbound_handler.py• L38-236
Message lifecycle
When a platform event arrives, the adapter follows the same broad path:
- Filter duplicates, unaddressed messages, and unauthorized input.
- Resolve the organization and actor scope.
- Resolve or rotate the conversation session.
- Build platform output and approval controls.
- Bind usage and credit admission data with a stable delivery identifier.
- Run the shared turn handler with timeout and cancellation support.
- Publish one final answer or safe error through the platform.
Slack acknowledges accepted events before work waits on a busy conversation and keeps direct-message continuity across message boundaries. Telegram and Buzz detach turn work from polling, while Discord and Slack run their dispatchers behind platform worker boundaries. The terminal-outcome rule keeps timeout, stop, denial, error, and success from producing competing final replies.
References: gateway/…/events.py• L72-125 gateway/…/dispatcher.py• L119-164 gateway/…/dispatcher.py• L264-461 gateway/…/dispatcher.py• L86-145 gateway/…/dispatcher.py• L181-366 gateway/…/inbound_handler.py• L62-227 gateway/…/inbound_handler.py• L71-236
Web request handling
The web surface is one FastAPI application that can run as a standalone ASGI service or inside the gateway. It serves health, liveness, readiness, alert intake, remote prompt, and loop synchronization requests. It does not act as a chat transport.
Health and alert requests
Health routes report process version and environment, key configuration presence, persisted state counts, and the previous shutdown result. The readiness route reports gateway lifecycle state separately, so a live HTTP process can be distinguished from one that has not completed required startup.
POST /alerts accepts a bounded and authorized JSON alert and places it in the process-wide alert inbox. The user surfaces page covers the related interactive shell path.
References: gateway/…/webapp.py• L18-32 gateway/…/webapp.py• L37-61 gateway/…/webapp.py• L64-101 gateway/…/state_counts.py• L18-65 gateway/…/shutdown_record.py• L70-84 infrastructure/alert_intake.py• L50-69 infrastructure/alert_intake.py• L72-126
Remote prompt requests
POST /v1/prompt accepts an authenticated prompt and returns a job identifier. GET /v1/prompt/{id} returns its state and any answer, question, progress, or stable failure code. POST /v1/prompt/{id}/answer accepts a response to a pending question and returns a follow-up job identifier.
These routes use the same local-or-token authorization boundary and bound request fields before work enters the queue. They are web control requests rather than chat messages, so the prompt worker owns session creation and returns collected output through the polling record.
References: gateway/…/prompt_routes.py• L43-79 gateway/…/prompt_routes.py• L82-169 gateway/…/jobs.py• L78-100
Loop synchronization requests
POST /v1/loops/sync is an authenticated control request from the web app. It wakes the gateway's loop synchronization service without carrying loop data, so repeated requests are safe. A gateway without that hosted service reports the feature as unavailable.
References: gateway/…/loop_routes.py• L1-35 gateway/…/webapp.py• L26-30 gateway/…/controller.py• L334-384
Web hosting
Gateway startup binds the web application on the configured service port and returns a stoppable server handle. A bind failure is recorded as a web component failure rather than preventing chat startup.
The same application can run in web-only mode or as an embedded gateway service. Web startup applies the web process profile so both modes receive the shared process setup. Full gateway startup attaches the prompt queue and loop-sync callback; standalone web hosting has neither gateway-owned service unless another host supplies it.
References: gateway/…/web_server.py• L1-22 gateway/…/startup.py• L16-43 gateway/…/webapp.py• L1-9 gateway/startup.py• L91-100 gateway/…/AGENTS.md• L15-24
Change checklist
When these files or sections are changed, remember to consider these:
- When changing a transport callback or input model, review the composition root, registry, dispatcher, output binding, session key, and stable delivery identifier together.
- When changing conversation keys or identity scope, review principal resolution, binding lookup, session rotation, and legacy binding adoption together.
- When changing turn admission or credit outcomes, review hosted-route metering, organization binding, every transport's delivery identifier, admission order, and denial output together.
- When changing stop or timeout behavior, keep active-turn registration, cooperative cancellation, terminal-outcome arbitration, output cleanup, and executor or worker shutdown aligned.
- When changing Slack event handling, preserve direct-message continuity, channel-thread attention, duplicate filtering, file input, and the reply target.
- When changing Telegram or Buzz polling, preserve detached dispatch, callback responsiveness, identity checks, update or event based metering, and shutdown drain behavior.
- When changing readiness or component status, keep health output,
/readyz, startup state, partial transport startup, and shutdown records aligned. - When changing web hosting, preserve both embedded and standalone startup and the gateway-only ownership of prompt intake and loop synchronization.
- When changing process boot or capability registration, keep the gateway and web process profiles aligned with the shared registration set and safe to run in the same process.
- When changing prompt states or follow-ups, review all prompt routes, queue state, session linkage, public errors, and worker settlement as one contract.
- When changing prompt worker execution, preserve per-conversation queueing, pre-session storage binding, follow-up history seeding, one-time approval grants, cancellation reopening, heartbeat updates, and bounded shutdown.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Partial hosted credential setup | The gateway could use the wrong organization or no integration store | Credential hydration rejects incomplete settings before surfaces start |
| Missing credentials for one chat platform | That platform is unavailable while other surfaces can run | The transport registry records the platform as not configured and continues |
| A transport fails readiness | One platform is unavailable while the gateway can keep serving other surfaces | Component failure is isolated in the registry |
| Gateway or web process boot uses a different capability registration set | A hosted surface can start without a required adapter or delivery path | Both profiles use the registrations owned by gateway/…/boot.py |
| The web port cannot bind | Web health, prompt, alert, and loop routes are unavailable | Web startup records a component failure without stopping chat startup |
| The prompt queue is not attached | Prompt routes cannot accept jobs even when health routes work | Full gateway startup attaches the queue and worker |
| A credit ledger is unavailable in hosted mode | The turn does not run without a trusted admission decision | Metering fails closed for unavailable or incomplete hosted configuration |
| A delivery identifier changes across retries | A replay can consume credit more than once | Each adapter binds a stable platform delivery identifier |
| A session receives overlapping turns | Output or session state can cross between messages | Session-level locking serializes each logical conversation |
| A pending approval outlives its transport | A turn can wait for input that cannot arrive | Transport shutdown closes or denies pending approvals |
| A timeout races with success or stop | Users can receive competing final results | The terminal-outcome arbiter allows one terminal path to publish |
| A Telegram or Buzz polling task runs inline with polling | Later updates and approval callbacks become unresponsive | Turn work is detached from the poll loop |
| Slack uses a new key for each direct message | Follow-up messages lose conversation context | Direct messages share one conversation binding |
| A Discord answer exceeds message limits | The answer can be truncated or fail to deliver | Output splits long answers into platform-sized messages |
| A prompt session opens before its organization scope is bound | The transcript can be written to the host scope and fail to survive the turn | The worker binds storage scope before session creation |
| Two prompts for one conversation run together | Session history or collected output can cross between jobs | The prompt queue holds one running job per conversation |
| A cancelled approval answer keeps its grant | A later turn can run a tool without a new approval | Cancellation clears the session's pending grant |
| A follow-up resumes without stored transcript | The agent receives an answer without the request and earlier exchange | The worker seeds the known prompt chain when the store has no history |
| The gateway stops before active work drains | Executor work or approvals can remain stranded | Shutdown denies impossible approvals, waits within a bound, and signals cancellation |
Key files
| File | Why to read it |
|---|---|
| gateway/…/controller.py | Startup order, scheduler ownership, readiness, status, and shutdown |
| gateway/…/boot.py | Shared gateway process setup and capability registration |
| gateway/…/credential_hydration.py | Organization credential loading and refresh |
| gateway/startup.py | Web, prompt, chat, and loop-sync surface composition |
| gateway/…/resolver.py | Platform conversation bindings and session lifecycle |
| infrastructure/…/turn_runner.py | Shared turn contract, capacity, admission, and finalization |
| infrastructure/…/session_agents.py | Session agent reuse and per-session serialization |
| gateway/…/turn_metering.py | Credit admission attached to each turn |
| gateway/…/startup.py | Chat transport registry and partial startup |
| gateway/…/dispatcher.py | Slack inbound admission, continuity, metering, cancellation, and output |
| gateway/…/inbound_handler.py | Telegram session handling, metering, executor dispatch, and cancellation |
| gateway/…/background.py | Telegram polling, callback responsiveness, and shutdown drain |
| gateway/…/dispatcher.py | Discord attention, thread context, metering, and output |
| gateway/…/inbound_handler.py | Buzz security, session handling, metering, and cancellation |
| gateway/…/webapp.py | FastAPI application and shared web route wiring |
| gateway/…/prompt_routes.py | Remote prompt submission, follow-up, and polling contract |
| gateway/…/loop_routes.py | Authenticated web-app scheduler nudge |
| gateway/…/web_server.py | Embedded and standalone web hosting boundary |