CONCEPTS.md 15 KB

Concepts

How the plugin works where the reasoning is not obvious from the code. The README describes what the plugin does; AGENTS.md states the rules a change has to honour. This file explains why a few of those rules look the way they do, for a reader who wants to understand the design before changing it.

Thread sessions and the frontier

The problem

A Chatto thread gets its own Hermes session, and that session starts empty. Meanwhile two kinds of message never become a turn of their own:

  • The bot's own messages. Chatto echoes a posted message back over the realtime connection, and the adapter drops it as a self-event — correctly, since the gateway is already running the turn that produced it.
  • Anything the gateway did not dispatch, chiefly a message that arrived while the gateway was down. A reconnect inside a running process resumes from the last applied event cursor, but a restart forgets it and leaves a gap (README documents the boundary).

So a thread can contain messages that no session holds. The reported case: a cron job posts a build report into a channel, its echo is filtered, and an hour later someone replies to it. The thread it roots is new, its session is empty, and the agent would answer a message it cannot read.

The fix is to hand the thread's earlier messages to the session — but only the ones it has not seen. Re-delivering the whole thread on every turn would fill the context with a conversation the session already holds.

The frontier

That "only what it has not seen" boundary is a cursor: one opaque message ID per thread, meaning the session holds this thread's history up to here. Two facts about it drive everything else:

  1. It has to advance past the turn's own trigger, not just past the block that was delivered. The trigger is the message text of the turn, so the session holds it; a cursor left behind it hands the next turn the previous question a second time, as an [Earlier in this thread] line beside a conversation that already contains it.
  2. The fetch is anchored at the cursor, which is what makes a cursor usable rather than merely informative. An unanchored page returns the newest messages in the thread; an anchored one (after=<cursor>) returns the oldest messages past the cursor, walking forward. So the window and the thing being delivered are the same window, and a thread that outgrew THREAD_CONTEXT_MESSAGE_LIMIT keeps answering — where an unanchored page put the cursor outside the window, left no tail to find inside it, and muted the thread for good.

Two consequences ride along. The root is not part of an anchored page (the server sets IncludeRoot false whenever after is set), and it is not needed either — everything up to the cursor is already in the session — so the extra root fetch is skipped: one RPC fewer per turn. And a backlog bigger than the window drains over turns instead of arriving at once: each turn takes the next slice and stops there, so nothing is skipped and nothing repeats.

Why the frontier is stored, not derived

The cursor lives twice: in _seeded_threads for the running process, and on the session (chatto.thread_seed_cursor) so it survives a restart.

An earlier version of this code did not persist it, on the grounds that set_session_metadata rewrites the whole routing index per call. Instead it rebuilt the partition from the fetch the turn makes anyway:

the newest message that is not ours is the last one the session certainly holds, because every other person's message arrives as its own turn

That premise is false, and the fetch it reasons over is the shape a thread reply always produces: the window ends with the turn's own trigger — a person's message that became this turn seconds ago. So the rebuilt partition lands on the trigger, the tail comes out empty, and every bot message before it is skipped. After a restart the agent stops seeing its own output in a thread, which is the one thing the whole feature exists to prevent.

Excluding the trigger does not rescue it. The previous turn's trigger is just as much a person's message that became a turn, so the next restart skips again. A session's frontier is not a function of the message list at all: every candidate message is either a turn the session holds (person) or one it does not (bot), and the list alone cannot tell a past trigger from a bot message — only the stored frontier can.

When the write happens

Persisting costs a full routing-index rewrite, so the write is spent only where it buys something — which is not every turn:

  • A turn that delivered the bot's own output. That is the one thing no later turn can recover from the message list, so it is the one cursor that has to outlive the process. A turn that carried only the trigger writes nothing: its frontier is "the newest message that is not ours", which a restart can work out for itself.
  • The turn after a first turn whose cursor found no session to land on. A thread's first turn has no session yet, so the write is refused; that refusal is remembered in _unpersisted_threads and retried, because a cursor that never lands is exactly the cursor a restart needs.

The blind pass

One case has no cursor anywhere. A thread's first turn seeded nothing — a reply that opens a fresh thread has no earlier messages — so there was nothing to write; there was no session to write it to either; and the process restarted before the second turn. The thread is blind exactly once.

The blind pass re-delivers the bot's own messages, leaves people's messages to their own turns, and records the frontier so no later process is guessing. It can duplicate one block, in the rarer variant where that first seed did carry own output. Losing the output instead is the common case and permanent, so the bounded duplicate is the cheaper error.

What the cursor is looked up with

The adapter derives session keys of its own — to find the cursor, to find the turn an edit should cancel — and a derived key is worthless unless it is byte-identical to the one the gateway built. So it delegates to _source_session_key instead of calling build_session_key itself. That matters more than it looks: ingress runs before the runner stamps the profile onto the event, so a key built without the profile namespace puts every bot of a multiplexed gateway into agent:main: and names a session nobody is running.

What this costs

  • One extra RPC per turn that delivers something: get_thread_events, capped at 20 messages. Quiet threads skip it — the cursor means there is nothing to fetch. It used to be two: the unanchored page omits the thread root, so the root was fetched separately on top.
  • One session-metadata write per turn that delivered own output, plus one retry after a thread's first turn. Not per turn.
  • [Earlier in this thread] is reference text, not trusted input: only the trigger passes the auth gate.

Realtime resume

The gap

A realtime connection can drop while the gateway keeps running. The server offers two ways to continue: resume after a cursor, or start at the live boundary. Starting at the boundary is silent data loss — events posted during the drop are never delivered, and nothing in the log says so.

chattolib exposes the cursor as RealtimeEvent.cursor, and its docstring defines when a value is safe to retain: after that event has been fully applied, and never when the field is None (the event cannot be replayed). The adapter therefore advances _realtime_cursor only after the handler returns, and only when the event carried one. Two behaviours follow from that placement rather than from extra code: a handler that raises leaves the old cursor in place, so the event is redelivered, and an unreplayable event cannot wipe a good position.

Why a restart still leaves a gap

Persisting the cursor would extend the resume across process restarts, and the piece is cheap — one value. What is not cheap is the decision around it: a cursor restored from disk may be older than the server's retention, in which case the subscription falls back (initialize-from-snapshot or live-only) and the "backfill" silently becomes the same gap it was meant to close. That is a product decision about how much history to replay and what to tell the user when it cannot be, not a detail to smuggle in with a file write. Until it is made explicitly, the promise stops at the process boundary, and README says so.

Configuration resolution

AGENTS.md owns the rules here — one field, three coordinated names, every path parses by kind. What is not obvious from them is which configuration a tool call sees.

The gateway multiplexes several serving profiles through one process, so a process-wide cache would hand one profile another profile's credentials. Cached configurations are keyed by the profile scope Hermes itself uses, and secrets come from the scope the gateway installed rather than from os.environ — under multiplexing the environment holds the launch profile's values, not the serving one. A tool call that resolved its config from the environment would quietly answer with the wrong bot's token, which reads as a permissions error on the server.

That is also why a configuration that resolved without a token is not cached at all. Caching it would pin "token not configured" for the life of the process, so a later call in a properly scoped context would keep being served the degraded configuration long after its scope came back — a failure that persists exactly as long as nobody restarts the gateway.

Mentions: one decision, two sources

_Mentions answers one question — did this address us, or somebody else — and both admission gates read only that. The interesting part is where the answer comes from, because the two inbound paths are not equally informed.

The posted path asks the server. Chatto resolves mentions when a message is created and reports the targets on the event (MessagePostedEvent.mentions). includes_viewer is the server's own answer to "did this target include me", fixed at post time and unaffected by membership since. Three properties make this better than anything we could compute:

  • Broadcast and role targets arrive unexpanded — one all/here/role entry, never one per recipient — so recognising them needs no room roster at all.
  • Targets that resolved to nobody are omitted rather than reported as failures. "Mentioning a user who isn't a room member leaves the @name as plain text" is therefore not a rule we implement; it is what an empty list already means.
  • Roles work, which the previous regex could not express: @moderator reaches a bot that holds the moderator role, and there is no handle to match it against.

The web frontend does the same thing in packages/chatto-client (addressedMessage: message.mentions.some(m => m.includesViewer)), so this is the platform's own answer rather than a second opinion.

The edited path reads the text. MessageEditedEvent carries only room_id and message_event_id, and the hydrated Message has no mention field — the mention resolution was deliberately kept out of the message resource. There is no payload to read, so the fallback re-derives candidates from the body with the same regex as before.

Why re-gate at all, when Chatto does not? FDR-006 decision 4 states that mentions are post-time facts and that editing never re-resolves them. The frontend honours that by treating an edit as a timeline reconciliation — store.ts refreshes the window and returns, and only messagePosted feeds addressedMessage. We deliberately do not: a user who types a message, forgets the @mention, and adds it by editing expects an answer, and that is a promise this plugin makes. Chatto's rule is uncontroversial in a client that has no turn for an edit to open.

What that costs. The fallback is a text reading, not a resolution, so it inherits the regex's blind spots: a @bob inside a URL, a blockquote, a link label or a link destination reads as a mention. The same text posted rather than edited reaches the server path and is classified correctly. Two paths that answer the same question differently is exactly the drift risk this design usually avoids; the containment is that they converge on one type, and the only place that fills it differently is the one place where no better information exists.

Per-room toolsets

Why the hook exists at all

Hermes has no per-chat tool policy of its own. The adapter hook toolsets_for_source(source) is the only door: the gateway asks the adapter, per turn, which toolsets to enable. The webhook adapter already uses it for per-route tool lists, which is the precedent this follows.

Replacement, not subtraction

The hook's contract is that a returned list replaces platform_toolsets for that turn — the gateway copies the override into the platform's entry and resolves it through the same _get_platform_tools path. Subtraction would need a second decision ("minus these, from what?"), and a room entry that removed terminal would otherwise silently keep everything else. Replacement makes the entry self-contained: what is written is what the room gets. The cost is that a user must list every toolset the room keeps, including chatto-platform if the agent should keep its Chatto tools — which is why README says so in the tool documentation and in the variable table rather than leaving it to be discovered.

An unlisted room returns None, the hook's "no opinion" answer, so a config with no entries changes nothing.

Keyed on the room, validated at startup

The entry key is chat_id, which for this adapter is the room ID the realtime event carried — not model input, so it cannot be talked around. A thread turn keeps the room as chat_id and carries the thread separately, so one entry covers a room's threads without a second lookup.

The entry syntax is validated at startup because a malformed entry would otherwise be skipped, leaving a room the operator meant to restrict on the default toolsets — the one failure direction that is invisible in logs and dangerous. The toolset names are deliberately not validated here: Hermes drops unknown ones when it resolves the list, so a typo yields fewer tools, which is the failure direction that hides nothing.

One send path, two callers

A user cannot tell whether the agent replied on its own or through a tool, so the two paths must not behave differently. Both go through _deliver_chunks, which owns the split at the 9900-character limit, the routing of a split answer as one answer (the first chunk opens or joins a thread, later chunks carry that root), and the stop-at-first-failure.

The callers differ only in what they do with the result: send() shapes it into a SendResult, _post_chunks into a refusal that names which chunk failed and lists the IDs that went out — so a retry repeats only what is missing instead of duplicating a message the room already has.