Étape 9 sur 13 - Environ 45 min
Lab 08 - Gateway and channels
Time: about 45 minutes. You will: put one gateway in front of the assistant, so the terminal, a browser, and (next lab) a scheduler can all talk to the same Steward without stepping on each other.
Why
Until now, the terminal called the assistant directly. Add a second way in - a web page on your phone or laptop - and three problems appear at once:
- Two messages at the same time. You type in the terminal while a reminder fires. Both turns read the same history and both append to it: the log interleaves two conversations. (The Messages API keeps no state: each request carries the whole history, so the order in the log is the order the model sees.)
- Who is speaking? A web endpoint that runs tools must not answer just anyone.
- Which conversation? Is the web chat the same conversation as the terminal, or a new one?
Concepts
Everything is an event
Source du diagramme
flowchart LR
T[Terminal] -->|message| G
W[Web chat] -->|message| G
S[Scheduler, lab 09] -->|job| G
G[Gateway: owner check, session key] --> Q1[queue steward:main]
G --> Q2[queue steward:cron:daily-review]
Q1 --> A[Assistant]
Q2 --> A
A -->|deliver| O[(outbox)] --> T
O --> WChannels and the scheduler never call the assistant. They hand the gateway an event; the gateway decides who it is from, which session it belongs to, and when it runs.
One queue per session
src/gateway/queue.ts keeps a promise "tail" per session key. A new task waits for the tail, then
becomes the new tail. Result: turns for one session run strictly one after another; turns for
different sessions (your chat and a scheduled job) run in parallel. A failed task does not block
the next one.
Owner only, with identity links
The config lists who the owner is, as <channel>:<sender>:
"owner": { "identities": ["terminal:owner", "web:owner"] }Anything else gets NotOwnerError. Listing the same person on several channels links those
identities: with the default scope main, the terminal and the web chat share one conversation,
steward:main. With "gateway": { "scope": "per-channel" } each channel gets its own.
Delivery: the assistant can speak first
gateway.deliver() writes a message to <dataDir>/outbox.jsonl and hands it to every channel
adapter. A channel that is down misses the live push but finds the message in the outbox later
(the web page loads it on start). This is how scheduled jobs reach you in lab 09.
The web channel, locked down
src/channels/web.ts is a small Hono app:
| Route | What it does |
|---|---|
GET / |
The chat page |
GET /health |
Status for monitoring (lab 12) |
POST /api/chat |
Runs a turn, streamed as server-sent events |
POST /api/new |
Starts a new conversation for the web chat |
POST /api/approvals/:id |
Answers an approval request, streams the resumed turn |
GET /api/pending |
Waiting approval requests across all sessions |
GET /api/history |
Recent messages and outbox |
GET /api/events |
Server-sent events for messages Steward starts itself |
A web endpoint that can run tools is a serious door, so:
- it listens on 127.0.0.1 only;
- every
/apicall needsAuthorization: Bearer <token>, compared in constant time; - the Host header must be the local address: a web page you visit cannot use DNS rebinding to reach it;
- the token is not a cookie, so other sites cannot send requests with it (no CSRF).
The page reads the event stream with fetch() rather than EventSource, because EventSource
cannot send an Authorization header. The text events carry the model's answer as it
streams in from the API; an error, for example an
API error the SDK could not retry, arrives as an error event.
Build
src/gateway/queue.ts-KeyedQueue.run(),depth,idle().src/gateway/gateway.ts-handleMessage(),runInSession(),answerApproval()(finds the request in any session),deliver(),outbox(),close().src/channels/web.tsandsrc/channels/web-page.ts- the API and the page.src/channels/terminal.ts-TerminalAdapterprints delivered messages above the prompt.src/cli.ts-run()wires the gateway, the channels, and the scheduler for bothsteward chatandsteward serve.
Run
pnpm steward serveThe output shows the web address and a token for this run (set STEWARD_WEB_TOKEN to keep one).
Open http://127.0.0.1:8787, paste the token, and chat. In the same terminal you can keep
typing: both channels are one conversation. Ask something in the browser, then ask the terminal
"what did I just ask?".
Try the guards with curl. Copy the token from the serve output first:
export TOKEN=<the token printed by steward serve>curl -s http://127.0.0.1:8787/health
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8787/api/pending # 401
curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8787/api/pending # []
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: evil.example:8787' http://127.0.0.1:8787/ # 403Break it
- Interleaving without the queue. In
Gateway.enqueue(), run the task right away instead of through the queue: replacereturn this.queue.run(key, async () => { ... });withreturn (async () => { ... })();. Runpnpm lab 08: "two messages at once are processed one after the other" fails, because the second request no longer contains the first turn. Put it back. - Two processes. Start
pnpm steward serve, thenpnpm steward chatin another terminal. The second refuses to start: one process owns the data folder (lab 12 explains the lock).
Check
pnpm lab 08The checkpoint proves: one key runs in order and different keys in parallel; a failure does not
block the queue; strangers are refused; identities are linked in main scope and separated in
per-channel scope; simultaneous messages are serialized; an approval asked in one channel can be
answered in another; delivery survives a broken channel; the web API needs the token, refuses a
foreign Host, streams turns as server-sent events, and shows history without turn-context
blocks.
Exercises
- Write a Slack or Discord adapter: map its user id to an
owner.identitiesentry, callgateway.handleMessage(), and implementdeliver(). The core does not change. - Add a "typing" event to the web stream when a tool starts, and show it on the page.
- Add rate limiting to
/api/chat(for example 10 messages per minute). Where does it belong: the channel or the gateway?
Claude API docs
- Using the Messages API - the API is stateless: every request sends the whole conversation
- Streaming Messages - the events behind the web chat's live text
- Errors - what a turn can fail with, shown as an
errorevent - Rate limits - the API's own limits, which several channels share
- Mitigate jailbreaks and prompt injections - why only the owner may reach a door that runs tools
Exam connection
CCA-F - Agentic Architecture & Orchestration: routing events to agents, concurrency and ordering, and keeping state consistent across entry points. Practice this domain on CertLabPro.
Previous: Lab 07 - Next: Lab 09 - Scheduler