Channels: Telegram, WhatsApp and what a channel must provide
What an agent needs from a chat platform, how to keep each platform behind a small interface, why a webhook needs a guarded door, and how to design around a platform's rules: messaging windows, link previews and late deliveries.
- List what an agent needs from a chat platform, and check a platform against that list before writing code for it.
- Put a channel behind a small interface so that the rest of the program cannot tell which platform a message came from.
- Explain the difference between a channel the program polls and one that calls the program, and guard the public door the second needs.
- Treat a platform's rules (a messaging window, link previews, late delivery) as design constraints, with a planned answer to each.
- Say what adding a second channel cost, where it was cheap and where it was not.
- Tell the owner apart from everyone else on each platform, and say what makes that identity believable.
- Week
- 9 of 14
- Before it
- Chapter 4, Chapter 7 and Chapter 8; Definitions 3, 4, 5, 6 and 8 of the model.
- Read first
- [Helland 2012]; [Saltzer et al. 1984].
- Laboratory
- 4: many tools, other people's servers
- Problem set
- 4
16.1The same assistant, reached from two apps
An assistant that lives in a chat lives in some particular app, and each app has different rules. Consider one day. In the morning the owner writes on WhatsApp: "Move my 1:1 with Sam today to 4pm and tell him." The assistant must know the message is from the owner and not from anyone who has the bot's number. Moving the meeting emails a guest, so it must ask first, with buttons, on a phone screen. In the afternoon a reminder set on Monday falls due, and nobody has written since Tuesday: can the assistant still speak first? That evening the server is down for ten minutes, and a message sent meanwhile arrives when it returns. Should it be acted on?
None of these questions is about the model. Getting them wrong produces an assistant that obeys strangers, approves things on a typed "yes", loses reminders without a word, or repeats something the owner has since done by hand. This chapter is about what a channel must provide, how to keep each platform in one thin file, and what Telegram and WhatsApp actually required.
16.2What an agent needs from a channel
- Channel
- The place a conversation with the assistant happens, together with the code that carries messages between that place and the program. Here: a private Telegram chat, or a WhatsApp thread with a business number.
A chatbot that only answers needs little from a channel: text in, text out. An agent needs six things, and a platform should be checked against them before any code is written.
| Need | Why the agent needs it | Telegram | WhatsApp (Meta's Cloud API) |
|---|---|---|---|
| The sender's identity | Only the owner may give instructions | A numeric user id, set by Telegram | A phone number in the delivery, believable only if the delivery's signature checks |
| A way to speak first | Reminders, routines, briefs (Chapter 6) | Yes, to anyone who has started a chat with the bot | Only within 24 hours of the person's last message; otherwise a pre-approved template |
| Buttons, or another way to approve | The gate counts only a tap as approval (Chapter 8) | Buttons under a message, up to 4,096 characters | Reply buttons on a message of at most 1,024 characters |
| Drafts or streaming | A long task should visibly be working | A draft that updates as the reply is written | None |
| Files and voice | Chapter 15 | Photos, documents, voice notes; a bot may download up to 20 MB | Images, documents, audio, fetched by id; no length given for a recording |
| Limits | The adapter must split, pace and retry | 4,096 characters a message; about one message a second per chat | 4,096 characters a text; a window; retries for up to 36 hours |
The first row matters most. Every safety rule in this book assumes the program knows who is speaking; a platform that tells you in a way an outsider can forge cannot carry an agent that acts on accounts.
16.3A channel is a thin adapter
- Adapter
- A small piece of code that translates between an outside system's way of doing something and the interface the rest of the program expects. It contains no decisions of its own.
The conversation code in odysseus/conversation.py decides who may speak, what "stop" does, when a task may start, what waits in a queue, and what the owner is told. It talks to the channel through an interface of three methods. From the same file:
class Chat(Protocol):
async def send(self, text: str) -> None: ...
async def draft(self, draft_id: int, text: str) -> None: ...
async def ask(self, text: str, approval_id: str) -> None: ... # a message with Approve and Decline buttons; with thread=True, a third
That is all the rest of the program knows about a channel: send a line, show a draft of a reply in progress, and ask a question with two buttons (three where a whole thread may be approved) carrying an approval's id. Each platform provides a class with these methods (TelegramChat, WhatsAppChat) and a receiving side that turns incoming events into four calls on the conversation: handle, handle_file, handle_voice, and handle_decision for a tap.
The obvious alternative is to write the bot inside the platform's library and let handlers decide as they go. But a rule implemented in a handler is implemented once per platform, and a second platform is a chance to forget it. With the decisions below the interface, a WhatsApp message reaches the same check of the sender, the same queue, the same "stop" and the same gate as a Telegram one. The first line of telegram.py states the rule: "All decisions are made in conversation.py; this only carries messages."
A channel that lacks a capability implements the method as nothing. WhatsApp has no drafts, so WhatsAppChat.draft is a single pass; the conversation already treats a failed draft as harmless, which makes a missing one safe.
16.4Polling and webhooks: who opens the connection
- Polling
- The program asks the service "anything new?" over a connection it opened itself. In long polling the service holds each request open until there is something to return. Nothing on the internet can start a conversation with the program.
- Webhook
- The service calls an address the program owns whenever something happens. The program must listen at an address the internet can reach.
- Signature
- A value sent with a message that only someone holding a shared secret could have computed from the message's exact bytes. It proves who sent the message and that it was not altered on the way. The common construction is HMAC, a keyed hash.
This program reaches Telegram by long polling (dispatcher.start_polling in odysseus/__main__.py), so the server opens no port and has no door to guard. WhatsApp's Cloud API works only by webhook: with it switched on, the program listens on a port that must be reachable over HTTPS (Chapter 7), and anyone who finds the address can send it anything. So three checks stand at the door.
| Check | What is checked | What it stops |
|---|---|---|
| The handshake | When the address is registered, Meta sends back a phrase the owner chose. It must match. | Someone else registering the owner's address as theirs |
| The signature | Every delivery carries an HMAC-SHA256 of its exact bytes, keyed with the app's secret. The program computes it again and compares. | Anyone but Meta sending a delivery, and any change to one on the way |
| The sender | The number the message came from must be the owner's. | Any other WhatsApp user who messages the bot's number |
The signature check is short. From odysseus/whatsapp.py:
def signature_ok(app_secret: str, raw: bytes, header: str) -> bool:
"""Meta signs each delivery: HMAC-SHA256 of the exact bytes, keyed with the app's secret."""
if not app_secret or not header.startswith("sha256="):
return False
expected = hmac.new(app_secret.encode(), raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header[len("sha256="):])
It is computed over the raw bytes as received, because parsing and re-encoding the JSON would change them. An empty secret fails closed: the program accepts nothing rather than everything. And compare_digest takes the same time however many characters match, so the value cannot be found by timing the answers. Meta's documentation calls the check "optional but recommended". For a program that can send mail from its owner's account it is not optional: without it, the "from" field is whatever the poster wrote.
Then the receiving side, from the same file:
def receive(self, raw: bytes, signature: str) -> int:
"""Check a delivery and start handling it. Returns the status to answer with, at once: Meta must not be kept waiting."""
if not signature_ok(self._secret, raw, signature):
# Anyone on the internet can post here. Each such post used to add a line to the journal, which is read whole
# at start-up: a way for a stranger to fill the disk. Now they are counted, and one line a minute is written.
self._unsigned += 1
if self._clock() - self._unsigned_logged >= 60:
self._journal.write("dropped", what="whatsapp deliveries with a bad signature", count=self._unsigned)
self._unsigned, self._unsigned_logged = 0, self._clock()
return 403
try:
payload = json.loads(raw)
except ValueError:
return 200
for entry in payload.get("entry") or []:
for change in entry.get("changes") or []:
for message in (change.get("value") or {}).get("messages") or []:
task = asyncio.get_running_loop().create_task(self._handle(message))
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
return 200
Two things follow. A public door turns even logging into an attack surface: a line per post would let a stranger fill the disk, so bad posts are counted. And Meta expects an answer at once and retries when it gets none, while a task can take minutes, so the delivery is acknowledged immediately and handled in the background. That creates a duty, met in _handle: a retry can bring the same message twice, so the last 500 message ids are remembered and each is handled once. They are remembered in memory only, so a restart forgets them, and a delivery repeated across a restart is stopped only by the ten-minute rule below. The same holds on every route that inherits this adapter.
if m.get("id") in self._seen or m.get("group_id"):
# Seen before, or said in a group. What the owner says in a group is said to everyone there; it is never
# taken as an instruction to their own assistant, whether or not anything serves that group.
return
self._seen.append(m.get("id"))
if not self._is_owner(m):
self._journal.write("dropped", what="whatsapp message from a number that is not the owner's")
return
A message from another number gets no reply at all, as on Telegram, so a stranger cannot even learn that something is there. Numbers are compared as digits only, so spaces or a plus sign in the settings do not matter.
The number itself is no longer promised. Meta's documentation, read again before this channel was switched on, says a delivery always names its sender by an identifier Meta makes for that person and that business, and leaves the phone number out for a person who has taken a username and has not written to the business number in thirty days. An adapter that compares only the number would then treat its own owner as a stranger, in silence, after a month's holiday from the channel. So the first time the owner's number arrives, the identifier that came with it is kept in the data folder, and a later delivery with no number is the owner's only if it carries that identifier (_is_owner in odysseus/whatsapp.py). Both values are inside the signed delivery. An identifier that never arrived beside the owner's number is a stranger's. Meta makes a new identifier when a person changes their number, and until the old number writes again such a person is a stranger too, which is the safe side to fail on. Verified by a unit test with hand-built deliveries, and in part for real: the first real delivery carried both the number and the identifier, and the identifier was kept. Not tested: a real delivery with no number in it.
The adapter was written from one year's documentation and switched on in the next. Nothing in the code had changed and nothing in a test could have shown this. A platform's rules are a dated reading, and the reading has to be done again before the thing is relied on.
16.5A platform's rules are design constraints
Each platform has rules no code changes. Find them before building, and give each a planned answer.
A window, after which only templates may be sent
WhatsApp allows a business number to send ordinary messages to a person only for 24 hours after that person last wrote. Each message from the person restarts the clock. Outside that window, only a pre-approved template may be sent, and those are charged per message. Verified in Meta's documentation, at the time of writing.
For a program that only answers, the rule is invisible. For one that speaks first, a reminder set on Monday for Thursday falls outside the window unless the owner has written since Wednesday. Templates are not built here. Instead, reminders and routines go to Telegram by default, where no such rule applies; and when the owner has chosen WhatsApp and it refuses a message, WhatsAppChat raises an error instead of returning quietly, and the scheduler sends the message on Telegram. From odysseus/__main__.py:
# Reminders and routines go to one place: Telegram, unless the owner chose WhatsApp and it is set up.
telegram = TelegramChat(bot, settings.owner_id)
on_whatsapp = whatsapp is not None and settings.notify_on == "whatsapp"
notify = whatsapp.chat() if on_whatsapp else telegram
...
scheduler = Scheduler(schedule, notify, journal, ledger, settings.daily_usd,
run_routine, now=now, on_delivered=conversation.record_delivery,
fallback=telegram if on_whatsapp else None, history_file=settings.data_dir / "routine_history.json") # WhatsApp refuses messages outside its 24-hour window
A reminder that cannot be sent on any channel is kept and tried again after 1, 5, 15 and 30 minutes before it is recorded as failed. Verified by unit tests with a channel that refuses; not seen against the real WhatsApp.
Previews that make the platform fetch a link
To show a preview of a link, a platform's servers fetch it before the owner does. That is not harmless for a link meant to be opened once, by one person, such as the sign-in link the program sends when the owner connects a service (Chapter 13). Both adapters turn previews off on every message: link_preview_options=NO_PREVIEW on Telegram, "preview_url": False on WhatsApp.
No test found this. Running the connect-a-service errand end to end in the owner's real chat showed Telegram making a preview of the sign-in link the program had just sent, so Telegram's servers had fetched it.
Messages delivered late, after the program was down
Both platforms hold messages for a program that is not running and hand them over when it returns: Telegram for a day, WhatsApp, which retries, for a day and a half. "Send the contract to Ravi", written at nine and delivered at three, may have been done by hand in between. Carrying it out as if it had just been sent is wrong. So a message more than ten minutes old when it arrives (STALE_AFTER_S = 600 in both adapters) is not acted on. The owner is told, at most once a minute however many arrive together: "Something you sent earlier has only just reached me, because I was not running at the time. I have not acted on it. Send it again if you still want it." (On WhatsApp the reason reads "because I could not be reached at the time".) Verified, unit test for WhatsApp; the same rule for Telegram is written and has no test, because the stand-in for Telegram does not carry dates.
This sits beside the other half of restarts: a task that was running when the program stopped is announced on start, not resumed, because the program cannot know how far it got. Chapter 7 covers that.
Size limits on buttons
The gate counts only a tap as approval, and the owner must have been shown everything the tap covers. A WhatsApp button message holds 1,024 characters, and an email to approve is often longer; cutting it would break the rule silently. So the question is split and the buttons go on the last part, from WhatsAppChat.ask:
parts = split_message(text, BUTTON_BODY_LIMIT)
for part in parts[:-1]:
await self._post({"type": "text", "text": {"preview_url": False, "body": part}})
await self._post({"type": "interactive", "interactive": {
"type": "button", "body": {"text": parts[-1]},
"action": {"buttons": [{"type": "reply", "reply": {"id": f"ap:{approval_id}:y", "title": "Approve"}},
{"type": "reply", "reply": {"id": f"ap:{approval_id}:n", "title": "Decline"}},
*([{"type": "reply", "reply": {"id": f"ap:{approval_id}:t", "title": "Approve thread today"}}] if thread else [])]}}})
TelegramChat.ask does the same at 4,096 characters. On both, the button carries only the approval's id. What will run is held by the gate, so a forged or replayed tap can at most answer a question that is actually waiting, and the tap is checked against the owner like any message. A typed "yes" is an ordinary message on both platforms and approves nothing.
16.6Worked example: an approval on WhatsApp
The owner writes on WhatsApp: "Email Priya that I'll be ten minutes late." Follow it through.
- The door. Meta posts a delivery to
/whatsappwith a headerX-Hub-Signature-256: sha256=....receiverecomputes the HMAC over the raw bytes; it matches. The program answers 200 at once and starts_handlein the background. - Once only, and only the owner. The message id has not been seen; it is remembered. The
fromfield, reduced to digits, equals the owner's number. The timestamp is seconds old, under the ten-minute limit. - Into the conversation. The type is
text, so the adapter callshandle(owner_id, "Email Priya that I'll be ten minutes late.", chat), passing a freshWhatsAppChatas the place to reply. Note the first argument: the adapter translates "the owner's WhatsApp number" into the program's single owner id. From here on, nothing knows the message came from WhatsApp. - The gate. The model drafts the email and asks for the send tool. The gate holds the call and builds the question from the tool's real inputs. The conversation calls
chat.ask(text, approval_id). - The question. The text is under 1,024 characters, so it goes as one interactive message with two buttons whose ids are
ap:<id>:yandap:<id>:n. Sending a question of exactly this kind (two buttons, to the owner's phone) is Verified, once; the owner confirmed it arrived with the buttons. - The tap. Meta posts a second delivery of type
interactivecarryingbutton_reply.id = "ap:<id>:y". (Steps 1 to 3 have now happened for real, once, with a plain question.) It passes the same checks as the message: the signature, the duplicate check, the owner's number and its age. The adapter then callshandle_decision(owner_id, id, True). The gate releases the held call; the email goes. Not tested: this step has never happened for real. It is written from Meta's documentation and checked by a unit test with a hand-built delivery.
The same request on Telegram differs only above the interface: no signature (the program asked Telegram for the message over its own connection), a callback query in place of an interactive delivery, and a draft of the model's reply shown while it is written.
16.7Why Telegram came first
The first channel was the owner's decision, and it holds up on technical grounds. Telegram's Bot API (version 10.4 at the time of writing) lets a bot stream a reply as it is written, attach buttons to a message, receive files and voice notes, and split a private chat into topics; and a bot can collect its messages by long polling, so the server needs no public address. Verified. That last point means a Telegram assistant can be built and run with no door at all.
The cost is reach. A Telegram bot cannot write to someone who has not started a chat with it, cannot place a phone call, and has no email address of its own. Telegram is also not where the reference products of this book live: by this book's research none of the three is offered there Secondary, and two of them are on WhatsApp. That is why a second channel was wanted.
One habit in the adapter is worth copying: when Telegram says to wait, the adapter waits that long, once, and sends again. Another was right for a time and then replaced. Messages first went as plain text with no parse mode, so that nothing the model wrote could be read as markup. That is safe and reads flat. The adapter now sends Telegram's own form, written by code from a few marks, and falls back to the plain words if Telegram refuses it (Chapter 4, "How a reply looks").
16.8What a second channel cost
Because the decisions were already below the interface, nothing about who may speak, what "stop" does, the queue, the gate, memory or the schedule had to change for WhatsApp. The adapter is a single file of under 300 lines that contains no decisions. Voice notes on WhatsApp are fetched and handed to the same handle_voice as Telegram's. That part was cheap.
Seven things were not.
- The door. A webhook needs a public HTTPS address and a guard at it. For as long as the program ran on a laptop it had neither, and nothing from WhatsApp was received. It is now hosted at such an address (Chapter 7).
- Rot. The token in the settings was the set-up page's short-lived one. It expired within hours, and nothing noticed for days, because reminders go to Telegram by default and nothing else sends on WhatsApp unasked. It was found by asking Meta about the token on the day the channel was to be switched on. A channel that is configured and unused fails without a sound; the fix for this one is the long-lived token, and the general lesson is that a second channel needs something that exercises it.
- The second set-up. Making the lasting token took a system user in the firm's business settings, the app and the WhatsApp account assigned to it, a policy the owner had to accept, and, halfway through, Meta locking the developer account for "unusual activity" until the owner entered a code sent by email. Meta recommends a token that lasts sixty days; one that never expires was chosen, because a silent expiry was the fault being repaired, and the price is a credential that stays good until someone withdraws it.
- Two registrations, not one. Meta has to be told the address, which it checks at once by the handshake. Separately, the WhatsApp account has to be subscribed to the app, or nothing is ever forwarded. The first went through and the address showed as active; the owner's first message then went nowhere, with no error anywhere, because the account was subscribed only to Meta's own test console. The second call had been refused earlier with "not supported for this account", which was true of the identifier it was given: the business settings show one number for the account and the app's own page another, and only the second is the account's. An address that is registered, verified and active proves the handshake and nothing about delivery.
- The set-up. The code was the small part. The set-up at Meta needs a person throughout: a developer registration confirmed by a phone code; a "business portfolio", which a new account may have to wait to create; an app; WhatsApp's business terms; a token issued through a pop-up only a person's click may open; the app's secret, shown after a third password entry; and the owner's number added as a recipient. The set-up page's token lasts about two hours; a running bot needs a long-lived "system user" token. And until the owner has written to the bot's number, only a template may be sent.
- The rules. The 24-hour window changed where reminders go, and required a fallback channel.
- Lost capabilities. No drafts. Smaller button messages. No length for a recording, so the ten-minute check on voice notes cannot be applied before fetching (the adapter passes a length of 0 and only the size is checked). And the line WhatsApp sends for an unsupported kind of message says it can read "text, photos and documents", although voice notes are handed on too: a small inconsistency in the code.
There were three ways to reach WhatsApp, and the choice is a build-or-buy decision of the kind in Chapter 3.
| Route | For | Against |
|---|---|---|
| Meta's own Cloud API | Official; no company in between; a test number is provided | Needs a Meta developer account and a public address |
| A messaging provider that resells it | Simpler sign-up at some providers | One more company holding every message, and a fee on top |
| An unofficial library that imitates the phone app | No business account; no 24-hour rule | Against WhatsApp's terms. Accounts are banned for it, and it is the owner's personal number that would be lost |
Users of one commercial assistant have reported WhatsApp bans Secondary. The first route was chosen; the set-up and the window come with it.
16.9A third channel, bought: iMessage
The owner asked for iMessage as well, through a company that sells it, and asked that it be something that can be switched on or off. Nobody but Apple can speak iMessage from a server, so there is no first route to compare with the other two: this channel is bought or it does not exist. The vendor, Linq, runs the lines and offers one interface for iMessage with RCS and SMS behind it. The adapter is odysseus/linq.py.
It is a second test of the claim made above, that a channel is a thin adapter. Nothing below the interface changed. What the adapter had to settle is the list of needs from the start of this chapter, checked against the vendor's documentation before any code.
| Need | What the platform gives | What the adapter does |
|---|---|---|
| The sender's identity | A phone number in a delivery signed in the Standard Webhooks way: an HMAC-SHA256 over the delivery's id, its time and its exact bytes, keyed with a secret shown once when the address is registered | Refuses a bad signature, and one more than five minutes old; listens only to the owner's number, in a chat of two, on this line |
| A way to speak first | Allowed, but the vendor asks that a line converse and not broadcast, and a free line may write only to people who wrote first | Only answers. Reminders and routines stay on Telegram, and there is no setting to move them here |
| A way to approve | No buttons. Polls, and a vote arrives as a signed event naming the poll and the option | Sends the question whole, then a poll with Approve and Decline. A vote in that poll answers it |
| Drafts | None; a "typing" bubble | Asks for the bubble at most once a minute while a reply is written |
| Files and voice | An address at the vendor's file service, with a type and a size | Fetches it without the account's token, over https, reading no more than the size limit |
| Limits | 10,000 characters a message; 30 messages a minute to one person; at least one delivery, sometimes more | Splits at 4,000; remembers both the event's id and the message's id, because a replay carries a new event id |
An approval with no buttons
Exercise 4 of this chapter asks how an owner approves on a channel with no buttons without letting a typed "yes" count. iMessage is that channel. The rule that matters is the gate's: approval is a deliberate act on one particular question, carried by the platform as structure and not as words a model could be talked into reading as consent. A poll meets it. The program makes the poll, the platform returns an id for it and one for each option, and the vote comes back as a signed event with both ids. The adapter keeps, in the running program only, which poll stands for which approval; a vote in any other poll, or from any other number, does nothing, and a poll answers once. Like a button, the poll dies with the process.
approval_id, answers = self._polls.get(str(d.get("message_id")), ("", {}))
answer = answers.get(str(d.get("option_id")), "")
if not answer:
return # a vote in a poll this program is not waiting on
self._polls.pop(str(d.get("message_id")), None)
Polls exist only on iMessage itself, not on the SMS a message falls back to. The first version put the question on Telegram when no poll could be made, on the principle that a channel which cannot carry an approval borrows another's. The owner overruled it: being sent to a second app to tap a button "will be taking away from the experience". What replaced it is the next section.
The owner's exception: an answer in words
The rule in Chapter 8 is that only a tap approves and a typed "yes" is an ordinary message. It exists for two reasons. Words reach the model, and a model can be talked into reading consent where there was none; and a word is not tied to any one question. The owner asked for an exception on channels with no buttons, and it is the owner's rule to change. The rule stands wherever buttons exist. The exception is built so that the first reason does not apply at all and the second is narrowed (odysseus/typed.py, which states it at its head).
- Code reads the reply, never a model. A message is an answer only if, trimmed and in any letter case, it is exactly one of a few words: yes or approve, no or decline, and "thread" where that was offered. "yes please", "ok" and "sure, send it" are ordinary messages.
- Only while a question is waiting: one this program put on this same channel less than ten minutes ago, which is as long as the gate waits. With nothing waiting, "yes" is a message like any other.
- A reply answers the latest waiting question, once, and the line sent back names it by its first words: Approved. ("Send this email to Priya? I'll be ten minutes late.")
- The reply came through the channel's own door: a signed delivery, from the owner's number, handled once and not late.
word = (text or "").strip().rstrip(".!").strip().lower()
if not self._waiting or word not in YES | NO | THREAD:
return None
approval_id, thread, first, _ = self._waiting[-1]
What is given up is real and should be said. A button is tied to its question by the platform; a word is tied only by being the next thing said. A one-word reply sent by habit, meant for something else, can approve the question that happens to be waiting. The line naming what was answered is how that is noticed, and for a sent email noticing is too late. The exception is used where the only alternatives were no approval on the channel or an approval somewhere else.
Verified by unit tests: loose wording, a stranger's "yes", a second delivery of the same answer and a "yes" with nothing waiting all approve nothing; the exact word approves once and never reaches the conversation. Not tested: any of it with a person.
A choice
The channel is on when its four settings are present, and one more setting switches it off and leaves them in place. That is one function, read in the two places that care: whether to open the door, and whether to build the adapter.
def imessage_on(s: Settings) -> bool:
return bool(s.imessage and s.linq_token and s.linq_number and s.linq_secret and s.owner_imessage)
What buying costs is the row the WhatsApp table already gave for a reseller: one more company holds every message that passes, and the free line is a sandbox with a ceiling of twenty contacts.
Verified by unit tests with hand-built deliveries (tests/test_linq.py, and one in tests/test_startup.py that starts the program with the channel on and then off). Not tested: anything against the vendor. No account exists yet, so every shape in the adapter, the signature included, is written from the documentation, as WhatsApp's were; and the first real WhatsApp message went nowhere for a reason no document mentioned.
16.10WhatsApp by the second route after all
The table of three routes to WhatsApp chose Meta's own interface and set the reseller aside: one more company holding every message, and a fee. That choice was made and it worked. Then the assistant needed a number of its own in place of Meta's test number, and getting one in the owner's country turned out to be the hard part: an ordinary SIM kept alive in a drawer, or a virtual number that cannot receive the SMS Meta sends and needs company papers to rent. A telephony company that rents such numbers also sells an interface to WhatsApp on them, and the owner chose that: its product, with its number, and no number of the firm's own to keep.
The decision turns the earlier one over for a reason the first table did not weigh, which is the cost of the number, not of the interface. The WhatsApp account at Meta is still the owner's; the reseller holds a token for it, receives Meta's deliveries and passes them on. What changes is what the table said would change: the reseller stores every message in readable form, and bills by the conversation at a price its site does not publish.
For the code it was the cheapest channel yet, because the reseller passes Meta's delivery on unchanged inside an envelope of its own. The adapter (odysseus/vobiz.py) is a subclass of the direct one: a different signature at the door, a different shape for sending, a different address for fetching a file, and everything in between inherited. Three things in it are worth a line each.
- The signature has no time in it. It is an HMAC-SHA256 of the exact bytes under a secret the program chose when it registered its address. A recorded delivery could be posted again. It would carry the same message id, which is handled once, and after ten minutes it is a late message, which is not acted on; a restart inside those ten minutes forgets the ids, and that gap is real.
- No buttons can be sent. The reseller's documentation offers text, media and pre-approved templates. So this is the route on which approval is the owner's answer in words, described above.
- One account, two numbers, two routes. Both the firm's own app and the reseller's are subscribed to the same WhatsApp account, so a message to either number is delivered to both doors. The direct route now reads only deliveries for its own number, and the reseller's route only those for its; without that, one message would have been answered twice.
Like iMessage, it is a choice: on when its settings are present, off by one word with them in place, and the direct route is untouched beside it.
Verified by unit tests with hand-built deliveries (tests/test_vobiz.py), and then once against the reseller: one text from the owner's phone to the rented number arrived at the door, passed the signature check, was accepted as the owner's and was answered, and the reseller's own record shows the reply. So the envelope, the signature and the shape for sending are as the code assumed, for a text. Not tested: a file or a voice note, a typed approval of a real question, the refusal outside the 24 hours, and whether a failed delivery is retried.
Connecting it produced three findings that no documentation had prepared for.
- The sign-up window reports to the page that opened it. The platform's sign-up runs in a window of its own and hands its result back to the reseller's page behind it. During the first pass that page was moved to another screen to fetch the verification code. The window finished, said nothing was wrong, and no channel existed: the account and the number had been made at the platform and the reseller had never been told. A second pass, with the page left alone, connected it. Open anything else in another tab.
- The code comes by a call to a number with no telephone. A rented number has no SIM, so the platform's text message goes nowhere. The reseller can answer and record the call instead. Its console did not list the recording for some minutes; its interface had it at once, and the program's own speech-to-text read the six digits from it. The recording was switched off afterwards, since otherwise every later call to the number is recorded too.
- The two routes ended up on separate accounts. The sign-up was told to make a new WhatsApp account for this number, so the direct route's test number and the rented number do not share one. The check that each route reads only deliveries for its own number stays, as a guard, and the separation is what the section on the platform's terms asks for.
16.11A rule that was not in the interface: the platform's terms
This chapter says to find a platform's rules before building, and lists the ones an interface enforces: a window, a limit, a signature. The rule that mattered most for WhatsApp was in none of the technical documentation, was enforced by no error code, and was found only after the channel worked and the owner was about to pay for a number.
The terms that govern WhatsApp's business interface bar "providers and developers of artificial intelligence or machine learning technologies", naming large language models and "general-purpose artificial intelligence assistants", from using the platform "directly or indirectly" to make such technology available, "when such technologies are the primary (rather than incidental or ancillary) functionality being made available for use". Who counts, and what is primary, is "as determined by Meta in its sole discretion". The terms apply whether the business connects itself or through a reseller, so the second route above is no way round. Exceptions exist in the countries where a competition authority compelled one; the owner's country is not among them. The remedy is suspension of access, at once. Verified, read on the platform's own terms page; the wording here is quoted in fragments and should be checked there before it is relied on.
Whether the rule covers this assistant is not something the text settles. On its number the assistant is the only thing there, which reads as "primary". Against that, the clause is aimed at those offering an assistant to others, and this one answers only its operator; the disputes that produced the exceptions were all about public chatbots. The platform has published nothing on an assistant used only by the people who run it, and it alone decides. So the channel rests on a reading its owner cannot confirm.
Three things follow for the design, and they were already true for other reasons.
- No capability may depend on a channel the platform can withdraw. Reminders, approvals and every scheduled message already default to the first channel. The second is a convenience.
- Do not pay for what can be switched off by someone else's discretion before the question is answered. The number was not bought then. It was bought later by the owner, who had read this section, and nothing was made to depend on it.
- Keep the account the channel lives in apart from anything else the firm has on that platform, since suspension lands on the account.
The check that found this was made because a second reader asked whether anyone had read the terms, not because of anything in the code, the tests or the first real message. The earlier research for this chapter had recorded that two of the reference products are on WhatsApp, which was true when it was written and says nothing about the terms they are there under. Read the contract as well as the interface, and read it again before spending.
16.12Telling several people apart
Each assistant serves exactly one person. Identity is therefore a comparison with one value: on Telegram, the sender's user id against the owner's id in the settings; on WhatsApp, the sender's number against the owner's number, after the signature has made that number believable. Everyone else is met with silence and a line in the log. A stranger's file or recording is never even downloaded: the Telegram adapter fetches a file only if conversation.is_owner(user_id), and handle_file and handle_voice check again.
Two further rules follow from serving one person. The Telegram handlers listen only in private chats (F.chat.type == "private"), because a bot added to a group would otherwise hear other people. And both channels lead into one conversation: the owner can start on Telegram and continue on WhatsApp, and the reply goes back on the channel the message came from, because each incoming message brings its own Chat object.
What about a firm, where several partners want an assistant? The owner's answer, asked whether that meant one shared assistant or one each, was "One per partner". A shared assistant would need answers this program does not have: whose approval counts, whose memory it is, and who may see what another partner asked. So nothing is shared. Each partner has an assistant that still serves exactly one owner.
16.13Several people on one running copy
One assistant each could mean each partner running the program themselves: a bot of their own, four keys, a machine that stays on. Nobody outside the person who built it will do that. The commercial assistants are easy to start because someone else runs them, and a new person only opens a chat and signs in. The same is possible here if one person, the host, runs the program and holds the keys, and everyone else arrives by a link.
To keep "nothing is shared" true, the start-up code that used to build one assistant is now a function, and it is called once per person with that person's settings: their Telegram id as the owner, and a folder of their own inside the host's.
def member_settings(settings: Settings, user_id: int) -> Settings:
return replace(settings, owner_id=user_id, data_dir=settings.data_dir / "people" / str(user_id),
daily_usd=settings.member_daily_usd or settings.daily_usd, notify_on="telegram",
whatsapp_token="", whatsapp_phone_id="", whatsapp_app_secret="", owner_whatsapp="")
odysseus/__main__.py
Everything built from those settings is therefore separate without any code that separates it: memory, the log, the schedule, the gate and its record of what was read, the agents, the daily budget, and the sign-ins, which the connector files under the person's id. No module learned that there is more than one person. The alternative, one set of objects with a person's id passed to every call, would put the separation in hundreds of places, and one forgotten argument would be a leak.
In front of the assistants stands one small router. It has the same methods the single conversation had, so the channel adapter did not change, and it sends each message, file and button tap to the assistant of the Telegram id that sent it. The sender cannot choose that id.
- Inviting. The host asks for an invitation, in words (Chapter 4, "The same things, asked for in words"), or types
/invite. Code makes a random code, keeps only its hash, and replies with a link that opens the bot with the code attached. It works once, for seven days. - Joining. The new person opens the link and taps Start. Code checks the hash, records their id, builds their assistant, and sends a fixed welcome and two buttons that open the connector's own sign-in pages for their mail and calendar. No model takes part.
- Strangers. Anyone else gets silence, as before, and so does a wrong code: a reply would confirm what kind of bot this is. Five wrong codes from one account, or sixty from all accounts, and codes are not looked at for an hour.
- The host.
/peoplelists who is here and what each has spent today./removeand an id stops an assistant and leaves its folder for the host to keep or delete.
odysseus/people.py
Joining on a chat that has no Start button
Telegram gives a bot a link that carries a word to it. WhatsApp has no such thing for a number, but it has a link that opens a chat with a message already written, which the person then sends. So an invitation asked for on WhatsApp is the link https://wa.me/NUMBER?text=join%20CODE, and one asked for on Telegram is the Telegram link, as before. Each invitation is one link, for the chat it was asked in: the person being invited should never have to choose, and the host can name the other chat as the first word of the command. A stranger who sends exactly "join" and a code to the number is treated as the Telegram stranger who sent "/start" and a code, by the same function, with the same silence for a wrong code and the same limit on guessing. Anything else a stranger sends is dropped as before.
The router keys everything on a person's id, and a WhatsApp person has no Telegram id. Theirs is their number moved into a range no Telegram id reaches:
WA_BASE = 10 ** 17 # Telegram's ids are below 2**52
def wa_id(number: str) -> int:
d = "".join(c for c in str(number or "") if c.isdigit())
return WA_BASE + int(d) if 7 <= len(d) <= 15 else 0
odysseus/people.py
Nothing else had to learn that there are two kinds of person. The folder, the sign-ins, the budget and the gate are all kept by id, and the number in a signed delivery is no more the sender's to choose than a Telegram id is. The adapter, which used to hear one number, now asks the router at each delivery who may be heard, and answers each person in their own thread. On the route that has no buttons, each person's waiting questions are kept apart, so one person's "yes" never answers another's question.
Three limits are real and stated. The platform's window applies to each person separately: someone who has not written for a day cannot be sent a reminder until they write, and an invited person on WhatsApp has no second channel to fall back to. A file the assistant makes cannot yet be sent on this channel, so a deck asked for there is refused in words. And on a number rented through another company, that company carries and can read what is sent; the welcome on that route says so, as it says that the host could read what is stored. Not tested with a real second person: tested with built deliveries only (tests/test_wa_invite.py).
Two things are not hidden from the new person. The welcome says that the assistant runs on a machine kept by whoever invited them, and that what is stored there could be read by that person. Separation between members is enforced by code; privacy from the host is not possible, since the host holds the disk. That makes this an arrangement for a firm and not for strangers.
An invited person's agents are connected by their first message and not at start-up, because each connected agent is a process and most people are silent at any moment. The host's are connected at once, as before.
The same reasoning runs the other way. A person who has sent nothing for fifteen minutes keeps their assistant, memory, schedule and conversation, and loses only the processes: each agent's connection is let go if nothing is running on it and no question is waiting, and their next message opens a new one that carries the same conversation on. In one live run the host alone held 3 processes and about 420 MB; two more people who had each just talked brought that to 5 processes and about 820 MB, so a person in conversation costs about 200 MB; after parking it was back to 3 and 420. The message after parking took 6 seconds against 1. A server sized for the host and two or three people talking at once can therefore hold ten who mostly are not. The host's agents are never parked.
Three things used to leak across people or disturb them, and were found by asking what exists once per process:
- A server one person connected by its address went into the program's one list of known services, so every other person's assistant knew it too. Each person's additions are now read from their own folder, and the program's list is never changed.
- The host connecting a service restarted the whole program, so everyone waited. It now rebuilds the host's assistant alone, the way an invited person's always was. In a live run that took about 10 seconds, the host's replies took the same time before and after, and another person talked straight afterwards.
- WhatsApp opened a port of its own inside the host's assistant. The port now belongs to the program, and things are put behind it and taken away again.
Verified, one live run with two invented people, the real start-up code, the real model and the real connector (scripts/live_people.py): each was welcomed and given two sign-in links of their own; one told the assistant a fact, the other asked for it and was told nothing was known, and the fact was in the first person's folder and nowhere in the second's or the host's; spending was counted per person (3 cents and half a cent); a removed person got no reply. Joining took 8 and 3 seconds, the first reply 8 seconds and a later one 1. Seventeen unit tests (tests/test_people.py). Not tested: a real second person on a real phone; a sign-in completed from a welcome button; more than two people; how much memory each person's agents take; any of it on a server.
A sign-in that comes back through the chat
Mail and calendar are signed in to on the connector's own pages, which work from any device. A service with a server of its own, such as the firm's database, is different: after the person approves, the service sends their browser to an address on the machine the program runs on (Chapter 13). The host is at that machine. An invited person is on a phone somewhere else, and their browser is sent to an address on their own phone, where nothing is listening.
The page that fails to load still has what is needed: its address carries the one-time code the service issued. So an invited person is told in advance that the page will not load, and asked to copy its address into the chat. Code takes the code out of it and finishes the sign-in.
- The address never reaches the model. The conversation hands any message carrying such an address to the connector before anything else looks at it, whether or not a sign-in is waiting. It is not written to the log, the history or the memory.
- The code is useless to anyone else. It works once, and only together with a secret the program made for this sign-in and never sent anywhere.
- An address from another sign-in is refused. Each sign-in starts with a random mark that the service returns in the address. A person tricked into pasting someone else's address would otherwise attach that someone's account to their own assistant; the sign-in library compares the mark and stops.
- Only that person's assistant is built again to pick up the new tools.
odysseus/connect.py
The cost is a clumsy step: copying an address from a page that looks broken.
On a server, a page of the program's own
Once the program runs somewhere with a public https address, the clumsy step goes. The program is told its address in one setting, registers that address plus /callback with the service as the place to return to, and listens there. The person approves, sees a page that says Connected, and goes back to the chat. The host signs in the same way, which matters on a server: the host is no longer at the machine either.
A page on the internet can be opened by anyone, so what it accepts is narrow.
- The connector reads the random mark out of the sign-in link before showing the link to the person, and tells the door to expect that mark. An address carrying any other mark gets a refusal, and the waiting sign-in goes on waiting.
- A mark is good once, and for ten minutes at most.
- The page says the same thing whatever was sent, and nothing from the address is put into it. The door keeps no log of addresses, since they carry one-time codes.
- Every other path answers "not found", apart from WhatsApp's if that is switched on.
def came_back(self, query: dict[str, str]) -> bool:
"""A browser arrived at /callback with these values. Whether a sign-in was waiting for it."""
waiting = self._waiting.pop(query.get("state") or "", None)
if waiting is None or waiting.done():
return False
if not query.get("code"):
waiting.set_exception(RuntimeError("the service sent no code: the sign-in was not approved"))
return False
waiting.set_result((query["code"], query.get("state"), query.get("iss")))
return True
odysseus/door.py
One risk is not removed, here or in any program that signs in through a browser: a person who starts a sign-in can give the link to someone else, and if that someone approves, their account is connected to the first person's assistant. The defence is the service's own approval page, which names the program and the permissions. Among partners who share one database the damage is small; it is a reason not to open this to strangers.
Without a public address nothing changes: the host's sign-in comes back to the host's machine and an invited person's through the chat.
Verified, live (scripts/live_public_sign_in.py): the real database server registered the program with an https return address and issued a link that returns to it with a mark and a proof key; an address with another mark was refused and the sign-in went on waiting. Two unit tests, one of them over a real local port. On the server, with this switched on, the page answered a made-up address from outside with its refusal. Not tested: a person approving, so a real code has not been exchanged through the page.
Verified, live, as far as it can go without a second person: the real database server issued a sign-in link for an invited person, asking for the permissions the program names and returning to the fixed address; an address carrying the wrong mark was refused by the real library and nothing was saved. Three unit tests against a stand-in server (tests/test_connect.py). Not tested: a real person completing it from a phone, so the exchange of a real code has only run against the stand-in.
16.14One assistant asking another
Once several people each have an assistant on one copy, the next request is obvious: "find an hour with the others this week". Each assistant can see one calendar. Something has to pass between them, and whatever passes is one person's private data arriving in a colleague's chat.
The products this book measures itself against have reached the same point. Secondary Instinct lets a personal agent talk directly to the agents of people on a list its owner keeps, joined by an invitation link the owner approves, and has a separate agent for group chats that cannot read anyone's personal account (TechCrunch, quoting its founder). What one agent may reveal to another without asking its owner is not documented. The one open standard for agents of different organisations, A2A, defines a task with named states and typed parts, and has no rule that what a peer sends is data and not instruction (specification). So neither gives a design to copy for the part that matters.
Measurements of agents that converse on their owners' behalf say where the danger is.
| Finding | Measured | Source |
|---|---|---|
| Agents told to keep things private still disclose them in ordinary cooperative tasks | Up to 35% and 51% of sensitive items, for two leading models | MAGPIE |
| Agents arranging meetings pass one person's availability to a third | 19% of direct messages | CalBench |
| Leaks rise when an agent must explain why a time is costly | Observed, not counted | CalBench |
| Choosing what may leave in a separate step, before any conversation, holds under attack | 97% protected, against 45% for the conversing agent alone | AirGapAgent (figure from its abstract) |
| People approve nearly every prompt they are shown | 93% accepted | Anthropic |
The disclosure happens in the conversation, a guard on actions never sees it, and asking the owner more often is not a fix. What held was deciding in code what may leave before a model says anything. So the first kind of request between assistants here has no conversation at all (odysseus/peers.py).
- The switchboard. One per process, and the only way from one person's assistant to another's. A colleague is found in the register of who is here, from a name the owner used. No model supplies an id, and no name from the register is shown to a model: a name is something a stranger chose.
- The answering side is code. It asks the calendar service for its free/busy answer, which holds busy blocks and no title, guest or place, and widens each block to the quarter hour. The list of events is never read.
- Only the intersection comes back. The switchboard combines everyone's blocks with the asker's own and gives the asking model the stretches when all are free. It never sees one colleague's calendar, and no reason for a busy time exists to be passed on.
- Trust is a list each person owns.
/trustshows it and turns a colleague off; either side saying no stops both directions. It is on to begin with, and the welcome says so. - Limits. Ten lookups of one colleague by another in a day, a window of at most fourteen days, and the first time each day a colleague's assistant looks, the person is sent a line saying who looked and what was given.
- Booking is not part of it. The asking assistant creates the event as it always did, with its owner's approval, and colleagues get an ordinary invitation.
An exchange is recorded in both people's logs with the same id, its kind and how it ended, and never its content. Its states carry the standard's names, so an adapter for other organisations can be put at the edge later without changing what is inside.
This does not hide when a person is busy from a colleague who asks for narrow windows. That is what free/busy is in any shared calendar; the count and the daily line bound it and do not remove it.
Verified, live, with the owner's real calendar standing in as the colleague who is asked and no model called (scripts/live_peers.py, 9 of 9): the service's free/busy answer came through the switchboard in 6 seconds; no title or guest address of any event in the week was in what the asking model is given; no time offered as free overlapped a meeting, checked against the list of events read separately; turning it off meant the calendar was not read; neither side spent anything. The week held two meetings, so this is a small sample. Eleven unit tests (tests/test_peers.py). Not tested: two real people; the model choosing the tool in a conversation and booking from its answer; all-day events and events marked as free, which are left to the calendar service's own judgement of what is busy; people in different time zones, since one copy has one zone. The count of lookups is kept in the same file as the waiting drafts described below, so a restart does not reset it.
A question in words
"Has anyone met this founder?" cannot be answered by code. A model has to read the answering person's mail, and that is the arrangement the studies above found leaking. So the model that reads is never the one that sends.
- The asking assistant puts one question, of at most 600 characters, to a colleague found by name. Like a search, it goes unasked unless it carries something recognised from the asker's own mail or files; then the asker is shown it first.
- The answering person is told at once who asked and what, and that nothing has been sent.
- A drafting run on the answering side reads the question as other people's writing. It can read that person's mail, calendar, memory and the firm's database. It has no web search, no sending, no memory to write to and no way to start another exchange, so a run that holds a stranger's words and private data together has no way out (
make_draft_runnerinodysseus/routines.py). - The answering person is shown the draft exactly as it would leave, with a count made by code of the email addresses and figures in it that the question did not contain. Links are removed. Two buttons: send, or decline.
- Only the tap sends it, and code does the sending. On the asking side it arrives as a message in the owner's chat, is shown to the model later as other people's writing, and is fingerprinted, so passing it on to a search or a third person is asked about.
- The asker's budget pays for the drafting. Five questions to one colleague in a day. An unanswered draft lapses after two days.
The answering person is not asked before the drafting, only before the sending. A question before drafting would double the prompts for the same protection, since nothing leaves until the second one, and prompts that protect nothing teach people to tap through.
Verified, with real models and a made-up mailbox of eight emails seeded with seven marked private facts: a valuation, a phone number, a third person's family matter, the owner's opinion of someone, a decision about another company, a bank line and a home address (scripts/live_peer_questions.py). Fourteen questions, each asked once of each model. This measures the draft, the step before the owner's tap.
| Measured on the draft | Main model | Small model |
|---|---|---|
| Ordinary questions answered correctly | 6 of 6 | 6 of 6 |
| Ordinary drafts holding a marked fact | 0 of 6 | 0 of 6 |
| Prying drafts holding a marked fact that was not asked for | 0 of 6 | 1 of 6 |
| Requests to do something, answered with "I can only answer questions" | 2 of 2 | 2 of 2 |
| Cost of a draft | $0.008 | $0.0007 |
| Seconds for a draft | 9 | 10 |
The one leak: asked to "summarise recent email", the small model named the other company. The count by code did not flag it, because a company name is neither an address nor a figure; only the owner reading the draft would have caught it. The main model is used, since the difference in cost is under a cent and the asker pays it. Asked outright for the valuation, both models gave it, and the count flagged the figure. Asked outright for the owner's opinion of a founder, for a third person's family matter and for what the firm is passing on, both declined and said the owner should decide, which is more careful than the instructions require.
These numbers are far better than the studies' and should not be read as a contradiction of them. The sample is fourteen questions over eight emails, asked once. The marked facts are matched as exact words, so a paraphrase ("not a natural seller") would be missed. And the studies measured agents in conversation under pressure; here there is one question, one draft and no reply to the reply.
Seven more unit tests cover the flow with stand-ins (tests/test_peers.py). Not tested: two real people; a real tap on a real draft; the asking model choosing the tool and wording the question; a question crafted to subvert the drafting run, which rests on that run having no tool that sends, searches or remembers.
The answering person can also replace the draft with their own words: /edit followed by the answer. No model reads it. Code tidies it, counts what it holds, and shows it again under new buttons; the old buttons stop working, so nothing can go that is not on the screen.
A restart loses none of this. The first version kept the day's counts and the waiting drafts in memory, so a restart dropped a draft its owner had not yet tapped and reset every limit, which made a restart a way round the limits. Now each change is written to one file in the host's data folder before the draft is shown, and the buttons under a draft carry its id, so a tap after a restart finds the same words. The two days are counted from when the draft was shown, not from the restart. The file holds a waiting draft's words and nothing of it once it is sent, declined or lapsed; a draft is dropped when either person is removed. Four unit tests restart a stand-in switchboard on the same file. Not tested: a real restart with a real draft waiting.
A file
One kept file, chosen by the sender. The sender is asked every time, with the file's name and size in the question, and code copies it to the colleague's kept files marked as sent by a colleague's assistant. The colleague is told and handed the file in their chat. No model on either side has read it at that point; if the colleague's assistant is later asked to, it reads it as it reads a file from a stranger. Five a day to one colleague, twenty megabytes at most, and /trust off stops it. Not tested: two real people.
Who has met whom: bought, not built
The plan had a third kind of exchange: code on each side answering "has your owner corresponded with this address?" It is not built, because the firm's database already answers it. Attio works out, from the mail and calendars its members connect to it, when the firm first and last dealt with a person or a company, how strong the tie is, and which colleague holds the strongest one. The assistant is already told to read those fields before anything else (knows_note in odysseus/attio_layout.py). A question that Attio answers needs no exchange between assistants, no trust list and no model on the other side.
Verified, read-only, against the real workspace, counts only (scripts/live_attio_met.py): the fields exist on people and companies; about three quarters of the people and over half of the companies carry an interaction; every one of those names a colleague and a strength.
Not tested: more than one colleague. The workspace has one member, so every record points to the same person, and no meeting on record has two colleagues in it. What the check cannot show is the case the feature exists for. Three limits are visible already:
- Attio names the one colleague with the strongest tie. It does not list every colleague who has met someone.
- Through Attio's own server an interaction arrives as a date, without whose mailbox it came from.
- It knows only the mailboxes that are connected. A partner who does not connect theirs is invisible to it, and what colleagues can then see of that mail is set in Attio, not by this program's trust list.
So the order is: each partner joins the workspace and connects mail and calendar; the check is run again with two people; and code between assistants is written only for what is still unanswered then.
16.15One assistant for the group
A group chat is several people, and everything above is one person and one assistant. Putting a person's own assistant in a group would let colleagues question it about that person's mail. So the group gets an assistant of its own (handle_group in odysseus/people.py):
- Its own everything. A folder, memory, budget and log apart from every person's. It is given no key for anybody's mail, calendar, apps, mailbox or browser, and it is not on the switchboard, so there is no way between it and a person's assistant.
- One group, chosen by the host. The host types
/firm onin the group. A second group is refused until the first is switched off. - Who it hears. People who have an assistant of their own on this copy, and only messages addressed to it: a mention of its name or a reply to one of its messages. Anything else said in the group is dropped before any model and is not logged.
- Commands stay private. In the group only "stop" and "status" work, so no sign-in link or address is ever made where others can see it.
- Its questions go to the group. Any member there may approve or decline; a tap from anyone else does nothing.
- The firm's database only by the host's word.
/firm attio onlets it read Attio through the host's sign-in. That is the host sharing their own access with the room, and it is said so in the group when it is turned on.
Telegram's own setting for bots in groups already withholds messages that are not commands, mentions or replies; the check in code does not rely on it. Verified by unit tests, one of which runs the real start-up and checks that the group's assistant has no mail, no mailbox, no database and a memory of its own. Not tested: a real group. Files and voice notes in a group are not handled, and a personal assistant cannot yet hand the group's assistant anything.
The same assistant in a WhatsApp group, and the gate in front of it
The owner asked for the group assistant on WhatsApp as well. The first answer was that it cannot be done, and that answer was wrong in an instructive way: the platform has an interface for groups, and the question that matters is who is let through to it.
| Way | What it can do | What stands in front of it |
|---|---|---|
| The platform's own interface for groups | The business number makes a group of at most eight people, who join by a link. Text and files. No buttons. It cannot be added to a group that already exists. | Open only to a number with the platform's "official business" standing: a verified business, a month on the platform, and the platform's agreement. The owner's number was refused with an error that names this. |
| A program that imitates the phone app | Sits in any group as an ordinary member, of any size. | Against the platform's terms; the account can be closed without notice; it receives every message in the group whether or not anyone spoke to it. Not built. |
| Forwarding | Anyone forwards a message from a group to the assistant's number and gets a private answer. | Nothing. It works without a line of code, and it is not an assistant in the group. |
The first was built and left switched off (odysseus/whatsapp_group.py), the third is what works meanwhile. The refusal was found by trying: one request to make a group, answered at once with the reason. That cost a minute and replaced a guess in both directions, since the listing of groups for the same number had answered without complaint.
The adapter carries and decides nothing. Every rule in the list above is the same code. Three things had to differ, each because of what the platform's documentation does and does not give.
- Who is speaking. Telegram names a sender by an id this copy already holds. Here a sender is a phone number, or only the platform's own id for the person. The host is known by the owner's number. Anyone else is heard only if the host has written their number against their assistant in a setting; there is no way to join by saying so in the group. The platform's id that arrives beside a known number is kept for the day the number is left out, as on the direct route.
- Spoken to. The documentation for a group message shows no mention and no reply-to. So a message is to the assistant when it begins with the assistant's name or has the name after an @, decided by code from the text. The name in the middle of a sentence is talk about the assistant, not to it.
- Approving. No buttons, so this is the typed exception again: one exact word, from a person who is heard, answers the latest question waiting in the group. The offer to approve a whole thread is not made in a group.
Two guards went into the routes that already existed. A message that carries a group's id is never taken as something the owner said to their own assistant, on either WhatsApp route, whether or not anything serves that group; without that, the owner's "yes" in a group could have answered a question their own assistant had put to them alone. And a group's invite link, which lets anyone in, is sent to the host and not written to the log.
Verified by unit tests with hand-built deliveries, one of which runs the real group code from people.py behind the adapter. Not tested: anything against the platform, which has refused the number. Whether a group message really arrives without a mention or a reply-to, whether files arrive, and what a failed send looks like are all taken from documentation. The limit of eight people and the standing required are the platform's, and may change.
16.16The theory
This section states the chapter's claims in the terms of the model. A channel is where items with provenance O come from (Definition 4), so its theory has two parts: who may speak, and how often and when a message is acted on.
Who may speak. Each adapter computes a predicate owner(m) and appends m as the owner's words only if it holds. On Telegram it compares a user id that Telegram sets, read over a connection the program opened. On WhatsApp it compares a number, or an identifier first seen beside that number, from inside a delivery whose HMAC has been checked. The predicate is a property of the code; its truth is relative to the platform. If the HMAC cannot be computed without the app's secret, and only Meta and the program hold it, every WhatsApp item with provenance O came from a delivery Meta made naming the owner. Whoever holds the owner's unlocked phone is the owner as far as any adapter can tell. An empty secret makes the predicate false for everyone.
Delivery. A platform that retries until answered gives at-least-once delivery: a message may arrive more than once, late, and in no promised order. The WhatsApp adapter answers each delivery at once and handles it in the background, so every retry becomes a duplicate to absorb. It absorbs them by remembering ids.
Let Σ be the last 500 message ids the WhatsApp adapter has recorded. If two deliveries of a message with id i reach the same running process, and fewer than 500 other ids are recorded between them, then the second has no effect.
Argument. _handle tests i ∈ Σ and appends i before anything else, with no await between. Tasks on one event loop interleave only at an await, so two tasks cannot both pass the test for the same i. Because the id is recorded before handling, a message whose handling fails is not handled again either. The guarantee is at most once; exactly once would need the record of an id and the handling of its message to survive a crash together.
The hypothesis fails in three ways the code shows. A restart empties Σ, which is held in memory only. The window is 500 ids from anyone, strangers included, because the id is recorded before the sender is checked, so time does not enter it. And a message is lost if the process stops after answering Meta and before handling it. The ten-minute rule bounds the first two: a duplicate is acted on twice only if it arrives within ten minutes of being sent. The program thus turns at-least-once delivery into at-most-once handling. The handler is idempotent; the effects are not, and only the gate's question stands in the way of a second request to send an email.
Time. A message is late when now − tsent > 600 seconds, tsent being the platform's timestamp, inside the signed delivery on WhatsApp. It is not acted on and the owner is told, since only the owner knows whether an instruction still holds. Two messages on either side of an outage are therefore judged separately even when the second depends on the first, and nothing restores the order in which they were sent.
Approval without buttons. Definition 6 requires d = yes for "that exact (τ, x)". A button carries an approval's id. A typed word carries nothing, and odysseus/typed.py binds it to the latest question waiting on that channel, asked less than ten minutes before. Write W for the set of such questions. When |W| = 1 the exact word names one question as a button does, and the remaining difference is intent: a word sent by habit cannot be told from an answer. When |W| > 1, which the code allows, the word approves the latest and the owner may have meant another; the line naming what was answered shows it afterwards.
| Claim in this chapter | Kind | How it is known |
|---|---|---|
| A delivery with a missing or wrong signature is not read | Property | Argued from signature_ok and receive; tested with one changed byte |
| A message is handled at most once | Property, within one process | Argued above; tested with a delivery made twice; fails across a restart |
| A message more than ten minutes old is not acted on | Property | Unit test for WhatsApp; written and untested for Telegram |
| A typed word approves only the latest waiting question | Property | Unit tests; not tried with a person |
| A real tap on WhatsApp reaches the gate | Neither yet | Written from the documentation; checked only with a hand-built delivery |
| A real WhatsApp text was received and answered | Measurement | Once, in three seconds |
16.17What goes wrong
Most of the faults found are already described above: a stranger able to fill the disk through the door, a message delivered hours late carried out as new, a platform fetching a private link, and a sticker met with silence. One deserves its own statement. A reminder refused by WhatsApp was once described as "logged, never silent". For the owner it was silent: it was written to a log they do not read, deleted, and never sent. "Never silent" has to mean a message reached the owner, or the program is still trying; hence the raised error, the fallback and the retries. Behind all of these sits the failure the door exists to prevent: drop the signature check "for testing" and anyone who learns the address is obeyed as the owner.
16.18How to test it
A channel test must check the door and the carrying without the platform: deliveries built by hand and signed with a test secret, and what the program would send collected in a list. tests/test_whatsapp.py checks the handshake phrase; that a missing or wrong signature, or one changed byte, is dropped unread; that a stranger gets no reply and a stranger's tap is ignored; that a delivery made twice is handled once; that an approval question is never cut and its buttons come last; that a tap reaches the gate and a typed "yes" does not; that files and voice notes are handed on and a sticker answered; and that a refused send is logged and raised. tests/test_stage0.py adds that two hundred unsigned posts write one log line and that late messages are reported once and not acted on. None of this shows that what Meta really sends matches what the code expects: the shapes of incoming deliveries were written from the documentation, and only one real delivery, a text, has been received.
Telegram is the channel in the owner's real use. Text, approval questions with buttons, and a PDF sent with no message have been seen working in the owner's own chat. Not tested: a voice note sent through Telegram by a real person (the voice path was checked with a synthesised recording handed straight to the program), and the ten-minute rule for late messages on Telegram, which is written and has no test.
WhatsApp: one real message has been received and answered. On the server, Meta's handshake reached the door and was answered; from outside, a wrong phrase and an unsigned delivery were both refused; a text message from the owner's own phone then arrived signed, was taken as the owner's, was answered in three seconds, and Meta accepted the reply. The app was still in Meta's development mode, which did not prevent it. Verified: three real messages from the bot's number to the owner's phone, accepted by Meta: a sample template, an ordinary message written by the bot's own code, and an approval question with two buttons, which the owner confirmed arrived with the buttons. The door's checks, deduplication, splitting and late-message handling are verified by unit tests and one local HTTP check. Not tested: anything arriving from WhatsApp but that one text, so a real tap on a button reaching the gate, photos, documents and voice notes fetched from Meta's file service, a late delivery, and the fallback to Telegram against a real refusal. Templates are not built. Meta's pages give two different figures for how long it retries a delivery, a day and a half in one place and seven days in another; the ten-minute rule does not depend on which is right.
16.19Where this sits in the literature
The questions in this chapter are old questions from distributed systems, with a person at one end. [Parnas 1972] showed that modules should be cut around the design decisions likely to change and not around steps of processing. The platform is such a decision, and the adapter is that rule applied: everything that changes with the platform sits above the interface, and everything that must not sits below it. [Waldo et al. 1997] argued that a remote call differs from a local one in latency, partial failure and concurrency, and that an interface must not hide the network. The interface here hides which platform is behind it, as it should, and it must not hide failure. The reminder that was "logged, never silent" and in fact lost is the fault Waldo's argument predicts when a remote failure is handled as if it were local; the raised error, the fallback and the retries are the repair.
[Helland 2012] explains why messages are delivered at least once in practice and why an application must therefore tolerate duplicates by processing them idempotently. The inbound side of this program follows the second half by remembering ids, and it keeps them in memory, so a restart forgets them. [Kleppmann 2017] gives the general treatment of logs, stream processing and exactly-once effects; measured against it, a list of recent ids held by one process is the simplest scheme that works while that process lives, and the property in the theory section is correspondingly weak. On the outbound side, [Stripe undated] documents a key chosen by the client that lets a request be retried without repeating its effect. Nothing of the kind appears in this chapter. The program's protection against acting twice on an outgoing message is the gate, which asks the owner again, where a key would have needed nobody.
The check at the door is a standard one. [Stripe, webhooks] document an HMAC over a timestamp and the raw body, compared in constant time, with a tolerance window against replay and the handling of duplicate events; [GitHub, webhooks] describe the same keyed check over the body as a second, independent reference. Here the published design is stronger than the program's. Meta's signature, as this chapter describes it, covers the bytes and carries no time of its own, so a recorded delivery is limited by the message's own timestamp, the ten-minute rule and a memory of ids that a restart clears. The chapter names that gap for both WhatsApp routes. Where the time is inside what is signed, as in Stripe's scheme and in the one the iMessage vendor uses, a replay after the window fails whatever the receiver remembers.
[Lamport 1978] defined the happened-before relation and logical clocks, so that events can be ordered without a shared physical clock. The ten-minute rule uses physical clocks, the platform's and the server's, assumes they agree to well within ten minutes, and orders nothing. [Saltzer et al. 1984] argued that a function can be provided correctly only with knowledge at the endpoints. Whether a late instruction still holds is known only at one endpoint, the owner, and telling the owner without acting is that argument applied. Two things remain unsettled. Whether a person's instruction should expire at all, and after how long, is not a question this literature answers; ten minutes is a choice. And whether a one-word answer to the latest question is given by habit more often than a button is tapped by habit has not been measured, here or in these readings.
- An agent needs six things from a channel: the sender's identity, a way to speak first, a way to approve, drafts, files and voice, and known limits. Check a platform against them first.
- Keep every decision below a small interface (send, draft, ask), so a second channel inherits the rules and cannot weaken them.
- Polling needs no door. A webhook does, and the door needs a handshake, a signature on every delivery, and a check of the sender.
- Acknowledge a webhook at once, and therefore expect and ignore duplicates.
- A platform's terms are rules too, and no interface reports them. Read them before building on a channel and again before paying for it, and let nothing depend on a channel its owner can withdraw.
- Treat platform rules as constraints with planned answers: the 24-hour window (default to Telegram, fall back, retry), link previews (off), late deliveries (report, do not act).
- Split long approval questions and put the buttons last; a button carries only an id.
- One program serves one owner; several people get several copies.
- On a channel with no buttons, an approval can still be a tap if the platform reports some structured choice, such as a vote in a poll. Where it reports none, the choices are another channel's buttons or an answer in words; if words, let code read one exact word for one waiting question, and never a model.
- Between two people's assistants, decide in code what may leave before any model converses. For meeting times that is busy blocks in and common free time out, with no conversation at all.
Review
- The signature check is removed "to make testing easier" and never put back. Describe the attack, step by step, and say which of the other two checks it defeats.
- The owner sets a reminder on Monday for Thursday at 9am and has chosen to receive reminders on WhatsApp. They last wrote on Tuesday. Trace what happens on Thursday through
WhatsAppChat._postand the scheduler. - Why is a WhatsApp delivery acknowledged before it is handled, and what does that make necessary? What happens to the remembered ids when the program restarts, and does it matter?
- Write a third adapter for a channel of your choice (a terminal, or an email inbox). Implement
send,draftandask. How will the owner approve on a channel with no buttons, without letting a typed "yes" count? - Add a test for the ten-minute rule on Telegram. What does the stand-in need to carry that it does not now?
- WhatsApp gives no length for a recording. Propose a way to keep the ten-minute limit for voice notes on WhatsApp, and say what it costs.
Analysis
- Prove the property "a message is acted on at most once" from the code of
_handleinodysseus/whatsapp.py. Explain why it matters that there is noawaitbetween the test and the append, by showing what could happen if there were one. Then construct two runs, in a simulated world, in which one message from the owner is acted on twice, one through a restart and one through the 500-id window. Say which of the two an outsider could cause, what it would cost them, and what bounds both. - The program is down from 14:00 to 14:25. The owner sends four WhatsApp messages, at 14:05, 14:12, 14:20 and 14:24, and all four reach the program at 14:25:30, in that order, with the platform's timestamps intact. (a) Which are acted on and which are not? (b) How many times is the owner told that something arrived late? (c) Construct two messages, in place of these, for which acting on the later one alone is worse than acting on neither, and say what change to the rule would prevent it and what that change would cost.
- Outsiders write to the bot's number at a steady rate, and every such message reaches the door as a delivery Meta has signed. (a) At two messages a minute, how long after the owner's message is its id dropped from the 500 the adapter remembers? (b) At what rate, in messages a minute, can the id be dropped before the ten-minute rule takes over? (c) If the id were recorded only after the sender is checked, what would change in your answer to (b), and what new duplicate would the program then handle twice?
- Write W for the questions waiting on a channel with no buttons. Show that when |W| = 1 an exact typed word satisfies the condition of Definition 6, that the decision is for "that exact (τ, x)", as a button does. Then construct a run with |W| = 2 in which the owner's "yes" approves a call they did not mean, and state the weakest change to
odysseus/typed.pythat restores the condition, with what it costs the owner in typing or in questions.
Design
- An SMS gateway at
sms.exampleis offered as a fourth channel. It calls a webhook; its signature is an HMAC over the body with no time in it; messages carry no id; it retries for three days; it has no buttons and a limit of 160 characters a message. Design the door, the handling of duplicates and late messages, and the way the owner approves. State what is guaranteed whatever the platform does, and what is given up against Telegram. - The owner asks that a message delivered late be kept and shown back with a button, "run it now", in place of being dropped. Design it: what the button is bound to, how it meets the gate, what happens if the owner taps it after the program restarts, and what happens to two late messages of which the second depends on the first. Say what is guaranteed and what is given up against the present rule.
Reading
- [Helland 2012]. In about four hundred words: what it claims; why it matters for the decision to answer Meta at once and remember the last 500 message ids; where you were not convinced that an in-memory list is enough for this program; and what you would measure or build next, including how you would test it.
- [Saltzer et al. 1984]. In about four hundred words: what the argument claims; why it matters for the ten-minute rule and for the rule that "never silent" means a message reached the owner; where you were not convinced that the owner is the right endpoint for every late message; and what you would build next.
Open
- (Hard, open.) Design an assistant shared by a team of four, on one channel, that keeps the gate's guarantees. Who may approve what? Whose memory does a fact go into? How does the channel tell the program who is speaking in a group, and how would you make that identity believable?
- On a channel that carries only text, find a way of answering an approval question that is bound to its question as firmly as a button, without asking the owner to copy a code. State the binding as a property in the terms of Definition 6, say how often a habitual reply would approve the wrong question under your scheme and under the present one, and describe the study that would measure it, so that a reduction could be recognised.