loopzero-gateway 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1074 -0
- package/LICENSE +201 -0
- package/README.md +803 -2
- package/dist/index.cjs +2976 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2875 -0
- package/dist/index.d.ts +2875 -0
- package/dist/index.js +2919 -0
- package/dist/index.js.map +1 -0
- package/package.json +72 -3
package/README.md
CHANGED
|
@@ -1,3 +1,804 @@
|
|
|
1
|
-
#
|
|
1
|
+
# loopzero-gateway
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Multi-platform messaging gateway for `loopzero-sdk`. Transport-agnostic primitives — adapters live in separate peer-dep packages.
|
|
4
|
+
|
|
5
|
+
> **Status: 0.x, pre-1.0.** Breaking changes allowed within the `0.x` line per semver.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add loopzero-gateway loopzero-sdk
|
|
11
|
+
# Plus one or more transport adapters:
|
|
12
|
+
pnpm add loopzero-gateway-telegram grammy
|
|
13
|
+
pnpm add loopzero-gateway-discord discord.js
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
## How each adapter treats `OutboundMessage.format`
|
|
18
|
+
|
|
19
|
+
**Every adapter honours it** — each reads the field and lets it decide what the platform receives. What they can DO with it differs by platform, and a consumer should not have
|
|
20
|
+
to read every package to learn which — so the classes are stated here.
|
|
21
|
+
|
|
22
|
+
| Platform | What it does with `format` |
|
|
23
|
+
|---|---|
|
|
24
|
+
| telegram | sets `parse_mode` |
|
|
25
|
+
| slack | sets `mrkdwn` |
|
|
26
|
+
| matrix | `html` only: sends `formatted_body` + `format: org.matrix.custom.html`, retrying as plain text if the homeserver refuses it. **`markdown` is dropped with a warning** — `formatted_body` promises HTML, and putting markdown there renders literal asterisks AND silently eats any `<tag>` in the text |
|
|
27
|
+
| teams | sets `textFormat` on the activity |
|
|
28
|
+
| email | sends an `html` part **alongside** `text`, never instead of it. `html` passes through verbatim (the caller owns that trust boundary); `markdown` is HTML-escaped into a `<pre>` block, so it is preserved and readable, not parsed |
|
|
29
|
+
| discord, mattermost | markdown is native, so `markdown` needs no flag; **`plain` escapes** `*_\`~` so a user's literal asterisks stay literal |
|
|
30
|
+
| line, sms, whatsapp | the platform carries no formatting on this message type — the adapter logs once that the declared format was dropped, rather than discarding it in silence |
|
|
31
|
+
|
|
32
|
+
**What none of them does is convert markdown to a platform's dialect.** `format` states the
|
|
33
|
+
caller's INTENT and lets the transport act on it; translating `**bold**` into WhatsApp's
|
|
34
|
+
`*bold*` is a presentation concern, and `channelRendering` (below) is where it happens.
|
|
35
|
+
|
|
36
|
+
Measured 2026-08-30: before this, two of ten read the field. An agent answered
|
|
37
|
+
`**Bom Sucesso (MG)**` and LINE and WhatsApp delivered literal asterisks, which is what a
|
|
38
|
+
declared-and-ignored field costs at the far end.
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
## Sending an agent's reply
|
|
42
|
+
|
|
43
|
+
`loopzero-presenter`'s `ChatPresenter` turns one agent turn into one chat message: it keeps the
|
|
44
|
+
answer's text, drops the model's reasoning and the tool events, and emits once, on `finish`.
|
|
45
|
+
`channelRendering(platform)` gives it the two things it needs to know about the destination, as
|
|
46
|
+
`{ translate, format }`.
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import { channelRendering, type MessageEvent } from "loopzero-gateway";
|
|
50
|
+
import { type AgentOutputEvent, ChatPresenter } from "loopzero-presenter";
|
|
51
|
+
import type { TelegramAdapter } from "loopzero-gateway-telegram";
|
|
52
|
+
|
|
53
|
+
async function reply(
|
|
54
|
+
adapter: TelegramAdapter,
|
|
55
|
+
event: MessageEvent,
|
|
56
|
+
turn: AsyncIterable<AgentOutputEvent>,
|
|
57
|
+
): Promise<void> {
|
|
58
|
+
const presenter = new ChatPresenter({
|
|
59
|
+
channel: event.channel,
|
|
60
|
+
...channelRendering(event.platform),
|
|
61
|
+
});
|
|
62
|
+
for await (const output of turn) {
|
|
63
|
+
for (const message of presenter.present(output)) await adapter.sendMessage(message);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
A hand-written loop that concatenates every event carrying `text` sends the reasoning too: one
|
|
69
|
+
reply reached a phone as `"TheHi! 👋"`, `"The"` being the start of the model's thinking. Build one
|
|
70
|
+
presenter per turn; it keeps state between `present()` calls.
|
|
71
|
+
|
|
72
|
+
| Platform | `translate` | `format` |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| whatsapp | `**b**` to `*b*`, `*i*` or `_i_` to `_i_`, `~~s~~` to `~s~`, `` `c` `` to ` ```c``` ` | `plain` |
|
|
75
|
+
| slack | `**b**` to `*b*`, `*i*` or `_i_` to `_i_`, `~~s~~` to `~s~`, `` `c` `` kept | `markdown` |
|
|
76
|
+
| discord, mattermost, teams, signal, nextcloud_talk | unchanged | `markdown` |
|
|
77
|
+
| telegram, matrix, email, line, sms, imessage, google_chat, irc, nostr, feishu_lark, synology_chat, tlon_urbit, twitch | the markers removed, their content kept | `plain` |
|
|
78
|
+
|
|
79
|
+
- Only the four inline markers are translated: bold, italic, strikethrough and inline code.
|
|
80
|
+
Headings, links, lists and block quotes reach every platform unchanged.
|
|
81
|
+
- **Fenced code blocks are not handled yet, and they come out wrong.** The inline-code rule
|
|
82
|
+
rewrites a fence's backticks: a three-backtick fence becomes one backtick on the plain
|
|
83
|
+
platforms and seven on whatsapp. Do not send a fenced block to a platform that does not render
|
|
84
|
+
markdown.
|
|
85
|
+
- Telegram gets plain text on purpose. Its adapter maps `markdown` to legacy Markdown, which
|
|
86
|
+
refuses a reply with an unpaired `_` or `*`, and the send fails with no retry.
|
|
87
|
+
- These renderings are inferred from each platform's documented syntax and from what each adapter
|
|
88
|
+
does with `format`; none was observed on a real client.
|
|
89
|
+
- The presenter never splits. Each adapter's `sendMessage` splits a long message at its own
|
|
90
|
+
platform's limit, as it always has.
|
|
91
|
+
- `splitKeepingRows(text, partLimit, { unit })` cuts at grapheme boundaries and keeps table rows
|
|
92
|
+
whole. `partLimit` counts UTF-16 units by default; `unit: "codepoint"` counts code points (it
|
|
93
|
+
needs a positive integer, and throws `RangeError` for a single grapheme longer than the limit).
|
|
94
|
+
Any other `unit` throws `RangeError`.
|
|
95
|
+
- `channelRendering` throws a `RangeError` for a platform it does not know, rather than letting
|
|
96
|
+
the presenter fall back to markdown.
|
|
97
|
+
- `loopzero-presenter` is your dependency, not this package's: `loopzero-gateway` does not depend
|
|
98
|
+
on it.
|
|
99
|
+
|
|
100
|
+
## Receiving an image
|
|
101
|
+
|
|
102
|
+
An inbound event may carry `images`, a list of `InboundImage`: `mediaType`, optional `size` and
|
|
103
|
+
`filename`, and `read()`, which fetches the bytes on its first call and returns the same bytes
|
|
104
|
+
after. Nothing is downloaded until a hook or the handler calls `read()`, so a `pre_inbound` hook
|
|
105
|
+
that refuses a sender costs no request. `read()` rejects when the platform cannot deliver the
|
|
106
|
+
bytes, with a message that is safe to log. The Mattermost adapter fills `images`; an adapter that
|
|
107
|
+
does not read images leaves the field out.
|
|
108
|
+
|
|
109
|
+
## Sending an image
|
|
110
|
+
|
|
111
|
+
`ctx.reply` takes an optional `attachments` list of images, each an `OutboundAttachment`: its
|
|
112
|
+
bytes (`data`, a `Uint8Array`), their `mediaType`, and an optional `filename`. The runner carries
|
|
113
|
+
the list to the adapter's `sendMessage` as `OutboundMessage.attachments`, by reference, and leaves
|
|
114
|
+
an empty list out. `post_outbound` hooks see the same outbound, image bytes included. Do not change
|
|
115
|
+
the bytes or the list until the reply's promise settles: Telegram reads each image only when its
|
|
116
|
+
turn comes. `DeliveryRouter.send` takes the same `attachments` field for a scheduled delivery.
|
|
117
|
+
|
|
118
|
+
Telegram and Mattermost send attachments today, images and audio both; `adapter.capabilities.attachments`
|
|
119
|
+
lists the kinds. Code that holds the adapter reads `supportsAttachments` before
|
|
120
|
+
attaching: every other adapter reports `false` and refuses an outbound carrying attachments with
|
|
121
|
+
`attachments_unsupported`, making no platform call, so an image is never dropped in silence. An
|
|
122
|
+
edit carrying attachments is refused the same way on every adapter, those two included.
|
|
123
|
+
`BasePlatformAdapter`, `OutboundAttachment` and `SendResult` come from `loopzero-gateway`.
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
async function sendChart(
|
|
127
|
+
adapter: BasePlatformAdapter,
|
|
128
|
+
channel: OutboundMessage["channel"],
|
|
129
|
+
chart: OutboundAttachment,
|
|
130
|
+
): Promise<SendResult> {
|
|
131
|
+
// No image send on this platform: say so in text instead.
|
|
132
|
+
if (!adapter.supportsAttachments) {
|
|
133
|
+
const text = "The chart is ready, but this chat cannot show images.";
|
|
134
|
+
return adapter.sendMessage({ channel, text });
|
|
135
|
+
}
|
|
136
|
+
return adapter.sendMessage({ channel, text: "Here is the chart.", attachments: [chart] });
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The runner and the router answer `attachments_unsupported` themselves, with no `sendMessage` call,
|
|
141
|
+
when the adapter does not declare `supportsAttachments`, so an adapter that ignores the field
|
|
142
|
+
cannot drop the image and report success. A handler, which receives no adapter, branches on that
|
|
143
|
+
code:
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
const sent = await ctx.reply("Here is the chart.", { attachments: [chart] });
|
|
147
|
+
if (sent.error?.code === "attachments_unsupported") {
|
|
148
|
+
await ctx.reply("The chart is ready, but this chat cannot show images.");
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
| Code | When |
|
|
153
|
+
|---|---|
|
|
154
|
+
| `attachments_unsupported` | the adapter cannot send attachments, the outbound is an edit, or (Telegram) an attachment's `kind` is neither `image` nor `audio` |
|
|
155
|
+
| `invalid_attachment` | Telegram only: `attachments` is not a list, holds more than 10 attachments, an entry has no bytes, an image is over 10 MiB, or an audio clip is over 50 MiB or its `mediaType` is not `audio/*` |
|
|
156
|
+
|
|
157
|
+
An adapter that is called directly (not through `GatewayRunner` or `DeliveryRouter`) refuses attachments it cannot send with `this.refuseAttachments(out)`, a protected helper on `BasePlatformAdapter` that returns `attachments_unsupported` or `undefined`. The function behind it, `refuseUnsupportedAttachments(adapter, out)`, is exported from `loopzero-gateway`.
|
|
158
|
+
|
|
159
|
+
## Voice notes and spoken replies
|
|
160
|
+
|
|
161
|
+
An inbound event may carry `audio`, an `InboundAudio`: `read()`, which returns the voice note's
|
|
162
|
+
bytes as a `Uint8Array`, `size` (the length in bytes the platform reported, absent when it
|
|
163
|
+
reported none), `mediaType` (such as `audio/ogg`) and `durationSeconds`, a whole number the
|
|
164
|
+
platform reported (0 when it reported none). The bytes are fetched on the first `read()` and
|
|
165
|
+
cached, so a `pre_inbound` hook that refuses a sender causes no download. `read()` rejects when
|
|
166
|
+
the bytes cannot be fetched; the message never carries a credential. The field is optional and
|
|
167
|
+
absent on every message without a voice note. Only the Telegram adapter fills it today, and only
|
|
168
|
+
for updates it polls: a voice arriving through a webhook is not read. Migrating from `audio.data`:
|
|
169
|
+
`const data = await event.audio.read()`.
|
|
170
|
+
|
|
171
|
+
To answer with speech, attach an audio clip: `{ kind: "audio", mediaType: "audio/ogg", data }`.
|
|
172
|
+
`OutboundAttachment` is a union of the image and the audio member, told apart by `kind`; code
|
|
173
|
+
that switches on `kind` exhaustively gains a case. Every adapter but Telegram refuses an audio
|
|
174
|
+
attachment as it refuses an image, with `attachments_unsupported` and no platform call.
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
const runner = new GatewayRunner({
|
|
178
|
+
adapters: [adapter],
|
|
179
|
+
handler: async (event, ctx) => {
|
|
180
|
+
if (event.audio === undefined) return;
|
|
181
|
+
const text = await transcribe(await event.audio.read(), event.audio.mediaType);
|
|
182
|
+
const speech = await synthesize(await answer(text));
|
|
183
|
+
await ctx.reply(text, { attachments: [{ kind: "audio", mediaType: "audio/ogg", data: speech }] });
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
### Folding a transcript into the turn text
|
|
189
|
+
|
|
190
|
+
A voice note's `text` is empty, so the agent would see nothing. `withMediaUnderstanding` wraps a
|
|
191
|
+
handler and appends one line per item to `text`: `[Audio transcript: ...]`, or
|
|
192
|
+
`[Attachment of type audio/ogg could not be understood]` when the function throws, or its `read()` rejects, or the payload (`size`, or the bytes read) exceeds `maxBytes` (default 20 MiB), or `[Attachment of type audio/ogg not understood]` when no
|
|
193
|
+
function is configured; the audio is read only when a function is configured. The media type is sanitized to `[\w/.+-]`, the event keeps `audio`, and
|
|
194
|
+
the handler always runs once. `write` receives one line per failure with the type and error name
|
|
195
|
+
only. The gateway makes no network call; pass plugin-voice's `transcribe`:
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
import { GatewayRunner, withMediaUnderstanding } from "loopzero-gateway";
|
|
199
|
+
import { transcribe } from "loopzero-plugin-voice";
|
|
200
|
+
|
|
201
|
+
const runner = new GatewayRunner({
|
|
202
|
+
adapters: [adapter],
|
|
203
|
+
handler: withMediaUnderstanding(answer, {
|
|
204
|
+
transcribe: (audio) => transcribe(audio, voiceConfig),
|
|
205
|
+
}),
|
|
206
|
+
});
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
`describeImage` is accepted for when events carry image bytes; no adapter fills them today.
|
|
210
|
+
|
|
211
|
+
## Editing a sent message
|
|
212
|
+
|
|
213
|
+
Six adapters can replace the text of a message they sent, keeping its id: Telegram, Discord,
|
|
214
|
+
Slack, Mattermost, Matrix and Teams. E-mail, SMS, LINE and WhatsApp cannot, because their
|
|
215
|
+
platforms have no edit call. A caller that wants a reply to appear as a preview and then become
|
|
216
|
+
the final text reads `supportsEdit` before it starts, and falls back to `sendMessage` whenever an
|
|
217
|
+
edit is refused. `BasePlatformAdapter`, `OutboundMessage` and `SendResult` come from
|
|
218
|
+
`loopzero-gateway`.
|
|
219
|
+
|
|
220
|
+
```typescript
|
|
221
|
+
async function sendWithPreview(
|
|
222
|
+
adapter: BasePlatformAdapter,
|
|
223
|
+
out: OutboundMessage,
|
|
224
|
+
preview: string,
|
|
225
|
+
): Promise<SendResult> {
|
|
226
|
+
// No edit call on this platform: send the final text once.
|
|
227
|
+
if (!adapter.supportsEdit) return adapter.sendMessage(out);
|
|
228
|
+
const sent = await adapter.sendMessage({ ...out, text: preview });
|
|
229
|
+
if (!sent.ok || sent.messageId === undefined) return adapter.sendMessage(out);
|
|
230
|
+
// The preview must fit one message; edit_too_long and every other refusal fall back to a send.
|
|
231
|
+
const edited = await adapter.editMessage(sent.messageId, out);
|
|
232
|
+
return edited.ok ? edited : adapter.sendMessage(out);
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
`supportsEdit` is set at construction and does not change with `connect()`. `editMessage` never
|
|
237
|
+
throws on a platform error; it answers with a `SendResult`, and these refusals make no edit
|
|
238
|
+
request:
|
|
239
|
+
|
|
240
|
+
| Code | When |
|
|
241
|
+
|---|---|
|
|
242
|
+
| `edit_unsupported` | the adapter cannot edit (the four above), or a Matrix client injected without `sendMessage` |
|
|
243
|
+
| `edit_too_long` | the text would need more than one platform message, counted after a `plain` text is escaped as a send escapes it; an edit replaces one message and is never split. Matrix has no length check |
|
|
244
|
+
| `invalid_message_id` | the id is empty, or on Telegram not a positive integer |
|
|
245
|
+
| `empty_text` | the text is empty, or on Teams only whitespace |
|
|
246
|
+
| `not_connected` | the adapter is not connected, where its `sendMessage` checks that too (all but Telegram and Discord) |
|
|
247
|
+
| `invalid_channel` | Telegram only: the channel id is not numeric, as on a send |
|
|
248
|
+
| `encrypted_room_unsupported` | Matrix only: the room is encrypted, as on a send |
|
|
249
|
+
|
|
250
|
+
Any other refusal comes from the platform, mapped as `sendMessage` maps it. Keep the preview
|
|
251
|
+
within one message, and edit only a message this adapter sent: on Matrix an edit is an
|
|
252
|
+
`m.replace` event, and clients apply it only to an event from the same sender. An edit whose
|
|
253
|
+
markup the platform refuses is not retried as plain text. When an edit is refused, the sample
|
|
254
|
+
sends the final text as a new message, so the preview stays above it.
|
|
255
|
+
|
|
256
|
+
`supportsEdit` says that the adapter has an edit call, not that every edit is accepted. Treat
|
|
257
|
+
`edit_unsupported` from an adapter that reports `true` as "stop previewing", like any other
|
|
258
|
+
refusal. Where an adapter checks the connection, `not_connected` is answered before
|
|
259
|
+
`invalid_message_id`.
|
|
260
|
+
|
|
261
|
+
The adapters do not order edits. Two edits of the same message that are in flight at once can
|
|
262
|
+
reach the platform in either order, and the one that lands last stays on screen; on Matrix each
|
|
263
|
+
edit is a separate event and clients show the newest. Await each edit before sending the next,
|
|
264
|
+
or keep one in flight and send only the latest text when it settles.
|
|
265
|
+
|
|
266
|
+
## Adapter capabilities
|
|
267
|
+
|
|
268
|
+
Every adapter has a `capabilities` getter, so an app reads what a channel can do instead of
|
|
269
|
+
keeping a table of platform names:
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
const { edit, attachments, typing, reactions, threads, maxMessageChars } = adapter.capabilities;
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
- `edit` is `supportsEdit`.
|
|
276
|
+
- `attachments` lists the kinds the adapter sends (`"image"`, `"audio"`); `[]` when none. An
|
|
277
|
+
adapter that sets only `supportsAttachments = true` reports `["image"]`; one that sends more
|
|
278
|
+
sets the protected `attachmentKinds`.
|
|
279
|
+
- `typing` and `reactions` are `true` when the adapter overrides `startTyping` and `react`.
|
|
280
|
+
- `threads` is `false` and `maxMessageChars` is `undefined` unless an adapter overrides the
|
|
281
|
+
getter; no adapter sets them yet.
|
|
282
|
+
|
|
283
|
+
The type is exported as `AdapterCapabilities`.
|
|
284
|
+
|
|
285
|
+
## Send error codes
|
|
286
|
+
|
|
287
|
+
A failed `SendResult` carries `error: { code, message, retryAfterMs?, platformCode? }`. `code` is a
|
|
288
|
+
`SendErrorCode`, or a platform-specific string an adapter has not mapped yet.
|
|
289
|
+
|
|
290
|
+
| Code | Used when |
|
|
291
|
+
| --- | --- |
|
|
292
|
+
| `empty_text` | core: the message has no text |
|
|
293
|
+
| `not_connected` | core: the adapter is not connected |
|
|
294
|
+
| `invalid_channel` | core: the channel is not valid for the adapter |
|
|
295
|
+
| `attachments_unsupported` | core: attachments sent to an adapter that cannot send them |
|
|
296
|
+
| `rate_limit` | the platform throttled the send (HTTP 429); `retryAfterMs` holds the wait |
|
|
297
|
+
| `permission_denied` | the credential may not post here (HTTP 403) |
|
|
298
|
+
| `auth_failed` | the credential was rejected (HTTP 401) |
|
|
299
|
+
| `timeout` | the request timed out (HTTP 408) |
|
|
300
|
+
| `server_error` | the platform failed (HTTP 5xx) |
|
|
301
|
+
| `network_error` | the request got no answer |
|
|
302
|
+
| `platform_error` | any other platform refusal |
|
|
303
|
+
|
|
304
|
+
`sendErrorFromHttp(status, message, { retryAfter, platformCode, now })` builds the `SendResult`
|
|
305
|
+
for an HTTP status; `retryAfter` is a `Retry-After` value in seconds or an HTTP date. It throws
|
|
306
|
+
`RangeError` when `status` is not an integer in 100..599. Adapters still return their own codes
|
|
307
|
+
today (`rate_limited`, `no_permission`, `<platform>_http_error`); moving them onto the shared
|
|
308
|
+
codes is follow-up work.
|
|
309
|
+
|
|
310
|
+
## Chat commands
|
|
311
|
+
|
|
312
|
+
`commandHook` is one `pre_inbound` hook for many commands. It recognises a command behind one leading mention (`<@U123> /help`, `@bot /help`) and with Telegram's `@bot` suffix (`/help@my_bot`), matches the name exactly (`/new chat` is `/new` with arg `chat`; `/newer` passes through), and answers `/help` with `helpText(commands)`.
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
import { commandHook } from "loopzero-gateway";
|
|
316
|
+
|
|
317
|
+
const hook = commandHook([
|
|
318
|
+
{ name: "new", description: "Start a new chat", arg: "none", run: () => ({ block: true, message: "Reset." }) },
|
|
319
|
+
{ name: "think", description: "Set thinking", usage: "/think off|low|medium|high", run: (_e, arg) => ({ block: true, message: `think=${arg}` }) },
|
|
320
|
+
]);
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
A command declared `arg: "none"` given an argument (or `"required"` given none) replies with its usage line instead of running. Two commands with the same name throw `GatewayConfigurationError` with code `duplicate_command`. `parseChatCommand(text, { prefixes })` is exported for apps that parse on their own.
|
|
324
|
+
|
|
325
|
+
## Access policy and pairing
|
|
326
|
+
|
|
327
|
+
`createAccessPolicyHook` decides who may talk to the agent. Owners (`<platform>:<senderId>` keys),
|
|
328
|
+
allowlisted and paired senders pass, only on platforms where `isAuthenticated` is true; an owner or
|
|
329
|
+
allowlist key on any other platform makes the constructor throw `unauthenticated_owner`. A DM from
|
|
330
|
+
anyone else follows `dm`: `open` passes, `disabled` is silent, `allowlist` answers `refusalText`,
|
|
331
|
+
`pairing` answers a 6-digit code and tells the sender to ask the owner for `/approve <code>`. A
|
|
332
|
+
refused sender is answered at most once per `refusalIntervalMs` (default one hour). An
|
|
333
|
+
unauthenticated sender is never answered. In a group a stranger gets no reply unless `groups: "open"`.
|
|
334
|
+
The owner's `/approve <code>` is answered "Paired." and never reaches the agent. A failure inside
|
|
335
|
+
the hook is logged (redacted) and becomes a silent block.
|
|
336
|
+
|
|
337
|
+
`messages` overrides the replies the hook sends; each omitted key keeps its default:
|
|
338
|
+
|
|
339
|
+
| Key | Type | Default |
|
|
340
|
+
| ------------- | ------------------------ | ------------------------------------------------------------------------ |
|
|
341
|
+
| `pairingCode` | `(code: string) => string` | ``Your pairing code is ${code}. Ask the owner to send /approve ${code}.`` |
|
|
342
|
+
| `invalidCode` | `string` | `Unknown or expired code.` |
|
|
343
|
+
| `failedSave` | `string` | `Saving the pairing failed. Check the storage and send the code again.` |
|
|
344
|
+
| `paired` | `string` | `Paired.` |
|
|
345
|
+
| `pairingOff` | `string` | `Pairing is not enabled.` |
|
|
346
|
+
|
|
347
|
+
```typescript
|
|
348
|
+
import { createAccessPolicyHook, createFilePairingStore } from "loopzero-gateway";
|
|
349
|
+
|
|
350
|
+
const hook = createAccessPolicyHook({
|
|
351
|
+
owners: new Set(["telegram:12345"]),
|
|
352
|
+
dm: "pairing",
|
|
353
|
+
isAuthenticated: (p) => p === "telegram",
|
|
354
|
+
pairing: createFilePairingStore({ dir: "./state" }),
|
|
355
|
+
});
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
`createFilePairingStore` keeps paired senders in `pairing.json` (mode 0600, written through a temp
|
|
359
|
+
file and a rename) and pending codes in memory for one hour. A missing file is an empty store; an
|
|
360
|
+
unreadable or malformed one throws `pairing_store_unreadable`. `senderKey(platform, id)` builds the
|
|
361
|
+
key; email ids compare case-insensitively.
|
|
362
|
+
|
|
363
|
+
## Agent bindings
|
|
364
|
+
|
|
365
|
+
When one gateway serves several agents, `createAgentBindings` picks the agent per message. A rule names an `agent` and any of `platform`, `account` and `peer` (the sender id in a DM, the channel id otherwise). A rule matches when every field it sets equals the message's. The most specific match wins (peer 4, account 2, platform 1), ties go to the earlier rule, and no match gives `defaultAgent`.
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
import { bindingStrategy, createAgentBindings, defaultStrategy, SessionRouter } from "loopzero-gateway";
|
|
369
|
+
|
|
370
|
+
const bindings = createAgentBindings({
|
|
371
|
+
defaultAgent: "personal",
|
|
372
|
+
agents: ["personal", "support"],
|
|
373
|
+
rules: [{ agent: "support", platform: "slack" }],
|
|
374
|
+
});
|
|
375
|
+
const router = new SessionRouter(bindingStrategy(bindings, defaultStrategy));
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
`accountOf(event)` says which bot account received the event when the app runs several. Creation throws `GatewayConfigurationError` with code `unknown_agent` for a default or rule naming an agent not in `agents`, and `empty_binding_rule` for a rule with no `platform`, `account` or `peer`. `bindingStrategy` prefixes the inner key with the escaped agent name, so two agents never share a session.
|
|
379
|
+
|
|
380
|
+
## Session scopes
|
|
381
|
+
|
|
382
|
+
`scopedStrategy` builds a `SessionRouter` strategy with a DM scope. Every segment is escaped with the shared injective `sanitize` (`_` to `__`, `-` to `_d`) and joined with `-`, so distinct inputs never share a key. `dm` is always the second key segment, so a DM key never equals a group or thread key.
|
|
383
|
+
|
|
384
|
+
| `dmScope` | DM key |
|
|
385
|
+
| --- | --- |
|
|
386
|
+
| `main` | `_m-dm` (every DM is one conversation) |
|
|
387
|
+
| `per-peer` | `_p-dm-<peer>` for a sender in `peerLinks` (`"<platform>:<senderId>"` to a peer name, shared across platforms); an unlinked sender gets the `per-channel-peer` key |
|
|
388
|
+
| `per-channel-peer` | `<platform>-dm-<sender>` |
|
|
389
|
+
| `per-account-channel-peer` | `<platform>-dm-<accountLabel>-<sender>` (needs `accountLabel`) |
|
|
390
|
+
|
|
391
|
+
Groups ignore `dmScope`: `<platform>-grp-<channel>`, or `<platform>-grp-<channel>-<sender>` with `groupScope: "channel-sender"`. A thread with a topic is `<platform>-tpc-<channel>-<topic>`.
|
|
392
|
+
|
|
393
|
+
```ts
|
|
394
|
+
import { scopedStrategy, SessionRouter } from "loopzero-gateway";
|
|
395
|
+
|
|
396
|
+
const router = new SessionRouter(
|
|
397
|
+
scopedStrategy({ dmScope: "per-peer", peerLinks: new Map([["telegram:42", "ana"], ["slack:U1", "ana"]]) }),
|
|
398
|
+
);
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
### Adopting the strategy with stored sessions
|
|
402
|
+
|
|
403
|
+
An app that already stored sessions under its own keys can keep them with `keys`, which replaces the `main` key and the linked-peer key. `peer` gets the raw peer name. Match your existing encoding exactly, and keep the keys distinct from every other key the strategy produces, or conversations will merge. Unlinked senders, groups and threads keep the default keys.
|
|
404
|
+
|
|
405
|
+
```ts
|
|
406
|
+
scopedStrategy({
|
|
407
|
+
dmScope: "per-peer",
|
|
408
|
+
peerLinks,
|
|
409
|
+
keys: { main: "main", peer: (name) => `peer-${name}` },
|
|
410
|
+
});
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
Creation throws `GatewayConfigurationError` with code `invalid_session_scope` for `per-account-channel-peer` without a non-empty `accountLabel`, or for an empty peer name. It never throws per event.
|
|
414
|
+
|
|
415
|
+
## Keeping a credential across restarts
|
|
416
|
+
|
|
417
|
+
`CredentialStore` is a `get(key)` / `set(key, value)` interface. `createFileCredentialStore(dir)`
|
|
418
|
+
keeps one file per key under `dir` (mode 0600, written to a temp file and renamed). Keys match
|
|
419
|
+
`[A-Za-z0-9._:-]+`, otherwise `set` and `get` throw `GatewayConfigurationError` with code
|
|
420
|
+
`invalid_credential_key`. `get` returns `undefined` for a missing key; any other read error throws
|
|
421
|
+
code `credential_store_unreadable`. `loopzero-gateway-x` uses it to keep a rotated refresh token.
|
|
422
|
+
|
|
423
|
+
## Caching an expiring access token
|
|
424
|
+
|
|
425
|
+
`createTokenCache({ fetchToken })` holds one access token. `get()` returns the cached token, or
|
|
426
|
+
runs `fetchToken` once and gives the same result to every concurrent caller. A token is refreshed
|
|
427
|
+
`marginMs` (default 60 000) before it expires; its lifetime is `expiresInS` from `fetchToken`, or
|
|
428
|
+
`defaultTtlS` (default 7200) when that is absent or not positive. `get({ force: true })` skips the
|
|
429
|
+
cache but still joins a fetch already in flight. `clear()` forgets the token, and a fetch that was
|
|
430
|
+
running at that moment does not store its result. A failed fetch rejects every waiting caller and
|
|
431
|
+
is not cached. The signal passed to `get` reaches `fetchToken` only for the caller that starts the
|
|
432
|
+
fetch. `now` replaces the clock in tests.
|
|
433
|
+
|
|
434
|
+
## Talking JSON-RPC to a child process
|
|
435
|
+
|
|
436
|
+
`JsonRpcLineClient` speaks line-framed JSON-RPC 2.0 over a child's stdio. `request(method, params, timeoutMs)` always resolves an `RpcOutcome` (`result`, `error` with `code`, `message` and optional `data`, `timeout`, or `disconnected`) and never rejects. Messages with a method and no id go to `onNotification`; non-JSON and non-object lines are skipped. When the child closes or errors, every pending request settles as `disconnected` and `onClosed` fires once. `close(reason)` does the same without killing the child.
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
const rpc = new JsonRpcLineClient(child, "my-adapter", onNotification, onClosed);
|
|
440
|
+
const outcome = await rpc.request("version", {}, 5_000);
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
## Architecture (5 pieces)
|
|
444
|
+
|
|
445
|
+
| Module | Responsibility |
|
|
446
|
+
|---|---|
|
|
447
|
+
| `BasePlatformAdapter` | Contract every adapter implements: `connect`, `disconnect`, `sendMessage`, `onInbound` |
|
|
448
|
+
| `GatewayRunner` | Orchestrator: holds adapters, dispatches inbound events to your handler |
|
|
449
|
+
| `SessionRouter` | Pure function: `MessageEvent → agentId` (composes `Agent.resume`, ADR D174) |
|
|
450
|
+
| `DeliveryRouter` | Dispatch outbound messages (composes `Cron`, ADR D175) |
|
|
451
|
+
| `HookExecutor` | `pre_inbound` / `post_outbound` / `on_error` hooks (own contract, ADR D176) |
|
|
452
|
+
|
|
453
|
+
## Minimal example
|
|
454
|
+
|
|
455
|
+
```typescript
|
|
456
|
+
import { Agent } from "loopzero-sdk";
|
|
457
|
+
import { GatewayRunner, SessionRouter } from "loopzero-gateway";
|
|
458
|
+
import { TelegramAdapter } from "loopzero-gateway-telegram";
|
|
459
|
+
|
|
460
|
+
const router = new SessionRouter();
|
|
461
|
+
const adapter = new TelegramAdapter({ token: process.env.TELEGRAM_BOT_TOKEN! });
|
|
462
|
+
|
|
463
|
+
const runner = new GatewayRunner({
|
|
464
|
+
adapters: [adapter],
|
|
465
|
+
handler: async (event, ctx) => {
|
|
466
|
+
const agent = await Agent.resume(router.resolveAgentId(event), {
|
|
467
|
+
apiKey: process.env.OPENROUTER_API_KEY!,
|
|
468
|
+
model: { id: "openai/gpt-4o-mini" },
|
|
469
|
+
});
|
|
470
|
+
const run = await agent.send(event.text);
|
|
471
|
+
const result = await run.wait();
|
|
472
|
+
await ctx.reply(result.result ?? "no reply");
|
|
473
|
+
await agent.dispose();
|
|
474
|
+
},
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
await runner.start();
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
## Wiring channels from descriptors
|
|
481
|
+
|
|
482
|
+
Each platform package that has one exports a descriptor: a static object listing the channel's
|
|
483
|
+
config fields (`required`, `secret`), how to build its adapter (`create`), and, for a channel that
|
|
484
|
+
receives webhooks, how to verify and ingest a request (`webhook`). `createChannels` builds every
|
|
485
|
+
channel from its descriptor without connecting anything, and `connectFailure: "isolate"` keeps the
|
|
486
|
+
channels that connect when another one cannot.
|
|
487
|
+
|
|
488
|
+
```typescript
|
|
489
|
+
import { createChannels, GatewayRunner } from "loopzero-gateway";
|
|
490
|
+
import { lineChannel } from "loopzero-gateway-line";
|
|
491
|
+
import { telegramChannel } from "loopzero-gateway-telegram";
|
|
492
|
+
|
|
493
|
+
const { adapters, rejected } = createChannels([
|
|
494
|
+
{ descriptor: telegramChannel, config: { token: process.env.TELEGRAM_BOT_TOKEN } },
|
|
495
|
+
{
|
|
496
|
+
descriptor: lineChannel,
|
|
497
|
+
config: {
|
|
498
|
+
channelSecret: process.env.LINE_CHANNEL_SECRET,
|
|
499
|
+
channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN,
|
|
500
|
+
},
|
|
501
|
+
},
|
|
502
|
+
]);
|
|
503
|
+
for (const { platform, error } of rejected) console.error(`${platform}: ${error.message}`);
|
|
504
|
+
// A rejection names each missing field's environment variable when the descriptor declares `env`.
|
|
505
|
+
// Pass `envPrefix` (the prefix you give `configFromEnv`) on an entry for the full variable name.
|
|
506
|
+
|
|
507
|
+
const runner = new GatewayRunner({
|
|
508
|
+
adapters,
|
|
509
|
+
connectFailure: "isolate",
|
|
510
|
+
handler: async (event, ctx) => {
|
|
511
|
+
await ctx.reply(`got: ${event.text}`);
|
|
512
|
+
},
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
const { connected, failed } = await runner.start();
|
|
516
|
+
if (connected.length === 0) throw new Error("no channel connected");
|
|
517
|
+
for (const { platform, reason } of failed) console.error(`${platform} did not connect: ${reason}`);
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
To build channels from environment variables, give each descriptor field an `env` name and read it
|
|
521
|
+
with `configFromEnv`. It trims values, treats empty or whitespace as unset, lists unset required
|
|
522
|
+
variables by full name in `missing`, and returns secret values in `secrets` for a log mask.
|
|
523
|
+
`selectVariant` picks one of a descriptor's `variants` (for example a WhatsApp backend).
|
|
524
|
+
|
|
525
|
+
```typescript
|
|
526
|
+
import { configFromEnv, createChannels, selectVariant } from "loopzero-gateway";
|
|
527
|
+
|
|
528
|
+
const descriptor = selectVariant(whatsappChannel, process.env.APP_WHATSAPP_BACKEND);
|
|
529
|
+
const { config, missing, secrets } = configFromEnv(descriptor, process.env, "APP_");
|
|
530
|
+
if (missing.length > 0) console.error(`skipped: set ${missing.join(", ")}`);
|
|
531
|
+
else {
|
|
532
|
+
const { adapters } = createChannels([{ descriptor, config, envPrefix: "APP_" }]);
|
|
533
|
+
// pass `secrets` to your log mask
|
|
534
|
+
}
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
- `createChannels` rejects an entry whose required field is absent, `null` or `""` with a
|
|
538
|
+
`GatewayConfigurationError` coded `missing_required_config` that names the missing variables (`envPrefix` + the field's `env`, or the config key when the field has no `env`), and reports a
|
|
539
|
+
configuration error thrown by `create` the same way. Any other error propagates. It performs no
|
|
540
|
+
network call.
|
|
541
|
+
- `createChannels` also returns `channels`: each built adapter paired with the descriptor that built it, in the order of `adapters`.
|
|
542
|
+
- `reconnect: { initialDelayMs, maxDelayMs, factor, maxAttempts }` retries an adapter whose
|
|
543
|
+
`connect()` threw a transient error (refused connection, DNS, 5xx) with exponential backoff and a
|
|
544
|
+
stderr line per attempt. It is off unless set, and takes effect only with
|
|
545
|
+
`connectFailure: "isolate"` (under `"rollback"` the start still rejects). A `connect()` that
|
|
546
|
+
returns `false`, or throws a 401/403 credential error, is reported once and never retried.
|
|
547
|
+
`start()` called again afterwards returns the updated `connected` and `failed`.
|
|
548
|
+
- `connectTimeoutMs` (under `"isolate"`) gives up on one adapter's `connect()` after that many ms:
|
|
549
|
+
it is reported `timed_out` in `StartResult.failed`, never wired for inbound, and disconnected if
|
|
550
|
+
its `connect()` resolves `true` later. With `reconnect` it is retried like a transient failure.
|
|
551
|
+
`onAdapterState(platform, state, reason?)` fires as each adapter becomes `connected`, `failed`,
|
|
552
|
+
`retrying` or `timed_out`, while `start()` may still be pending; `reason` is redacted. Both are
|
|
553
|
+
ignored under `"rollback"`. `secrets: [...]` masks those exact values (longest first) with
|
|
554
|
+
`[redacted]` in every reason and log line before `redactSecrets` runs (`maskSecrets` is exported).
|
|
555
|
+
- `runner.adapter(platform)` returns the registered adapter, connected or not, or `undefined`;
|
|
556
|
+
`runner.connected()` returns the adapters started now, updated by retries and `stop()`.
|
|
557
|
+
- `reconnect: { retryFalse: true }` retries a `connect()` that resolves `false` like a throw, on the
|
|
558
|
+
same backoff. A connect abandoned by `connectTimeoutMs` that rejects later is reported once
|
|
559
|
+
through `onAdapterState` as `failed`, redacted.
|
|
560
|
+
- `connectFailure` defaults to `"rollback"`: one failed connect disconnects the adapters that did
|
|
561
|
+
connect and rejects `start()`, as before. Under `"isolate"`, `start()` resolves even when every
|
|
562
|
+
adapter failed, so check `connected` before you rely on the runner.
|
|
563
|
+
- `start()` resolves a `StartResult` (`{ connected, failed }`) under both values. Code that awaits
|
|
564
|
+
it and ignores the value is unaffected; a type or subclass that declares
|
|
565
|
+
`start(): Promise<void>` needs to change.
|
|
566
|
+
- A runner holds one channel per platform: it routes replies and `stop()` by platform.
|
|
567
|
+
`createChannels` enforces this. The first entry built for a platform wins, and a later entry for
|
|
568
|
+
it is rejected with a `GatewayConfigurationError` coded `duplicate_channel` and never built. An
|
|
569
|
+
entry whose `create` returns an adapter reporting another platform than its descriptor is
|
|
570
|
+
rejected with the code `platform_mismatch`, and that adapter is dropped unconnected. A
|
|
571
|
+
runner you build from adapters you constructed yourself is not checked, so give it one adapter
|
|
572
|
+
per platform: with two of one platform the later one sends the earlier one's replies, and the
|
|
573
|
+
earlier one is connected but never disconnected.
|
|
574
|
+
- `start()` waits for every connect under both `connectFailure` modes, so a connect that never
|
|
575
|
+
settles blocks it. Under `"rollback"` that holds after a failure too: a failing start rejects
|
|
576
|
+
only once its slowest connect settles.
|
|
577
|
+
- `rawBodyCapture(tag, { maxBytes })` (Express webhook routes) answers 413 with
|
|
578
|
+
`{ "error": "request body too large" }` to a body over `maxBytes`. The default is
|
|
579
|
+
`DEFAULT_WEBHOOK_MAX_BYTES`, 1 MiB; pass `Number.POSITIVE_INFINITY` for no limit.
|
|
580
|
+
- A webhook channel's request reaches your HTTP route; route it by platform to the descriptor's
|
|
581
|
+
`webhook.verify(adapter, { rawBody, headers })`, then parse the body and pass it to
|
|
582
|
+
`webhook.ingest(adapter, payload)`, which answers `"delivered"`, `"malformed"` or
|
|
583
|
+
`"no_handler"`. Answer the platform with a success status only for `"delivered"`.
|
|
584
|
+
`"no_handler"` means the payload held a message and no handler was subscribed: a request that
|
|
585
|
+
arrives before `start()` resolves, after `stop()`, or for a channel `start()` reported in
|
|
586
|
+
`failed` under `"isolate"`. Acknowledging it loses the message, since the platform does not
|
|
587
|
+
redeliver an acknowledged request.
|
|
588
|
+
|
|
589
|
+
### Mounting webhooks in a Fetch server
|
|
590
|
+
|
|
591
|
+
`createWebhookHandler` routes `/webhooks/<platform>` for every `transport: "webhook"` channel. It
|
|
592
|
+
answers 404 for an unknown platform, 503 while the platform has not started, 405 for a method the
|
|
593
|
+
route does not take, 413 (with `connection: close`) past `maxBodyBytes` (default 1 MiB), 401 when
|
|
594
|
+
`verify` fails, 400 for a body that is not JSON or is `"malformed"`, and 503 for `"no_handler"`. A
|
|
595
|
+
descriptor with `webhook.handle` answers the request itself (method, URL and query included).
|
|
596
|
+
A throw gives 500 with no body and calls `onError(platform, error)`. `statusForDeliver(outcomes)`
|
|
597
|
+
maps `deliver()` outcomes to a status, worst wins.
|
|
598
|
+
|
|
599
|
+
```ts
|
|
600
|
+
import { createChannels, createWebhookHandler } from "loopzero-gateway";
|
|
601
|
+
|
|
602
|
+
const { channels } = createChannels(entries);
|
|
603
|
+
const handler = createWebhookHandler({
|
|
604
|
+
channels,
|
|
605
|
+
isStarted: (platform) => runnerStarted.has(platform),
|
|
606
|
+
onError: (platform, error) => log.error({ platform, error }),
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
Bun.serve({ port: 3000, fetch: handler });
|
|
610
|
+
```
|
|
611
|
+
|
|
612
|
+
### Is the sender id authenticated?
|
|
613
|
+
|
|
614
|
+
A descriptor can say whether `sender.id` is proven by the platform with `senderIdentity`:
|
|
615
|
+
`"authenticated"`, or `{ unauthenticated: "why it can be forged" }` for a channel such as email (the
|
|
616
|
+
From header) or SMS (the caller id), where the sender writes the id (CWE-290).
|
|
617
|
+
`isAuthenticatedSender(descriptor)` is true only for `"authenticated"`. A descriptor that does not
|
|
618
|
+
set the field is unknown, and unknown is treated as not authenticated (fail closed), so an app
|
|
619
|
+
that lets owners control an agent should refuse owner entries on such a channel.
|
|
620
|
+
|
|
621
|
+
```typescript
|
|
622
|
+
import { isAuthenticatedSender } from "loopzero-gateway";
|
|
623
|
+
import { telegramChannel } from "loopzero-gateway-telegram";
|
|
624
|
+
|
|
625
|
+
isAuthenticatedSender(telegramChannel); // true
|
|
626
|
+
```
|
|
627
|
+
|
|
628
|
+
## Receiving from a LoopZero app
|
|
629
|
+
|
|
630
|
+
Three repositories share this path. `loopzero` owns the HTTP route and the signature check —
|
|
631
|
+
`handleChannelWebhook` verifies the signature, parses the body, and hands your app the parsed JSON
|
|
632
|
+
as `payload: unknown`. These packages own the translation. `loopzero-sdk` is used here for one thing
|
|
633
|
+
today: redacting a throw before it reaches a log, at two call sites.
|
|
634
|
+
|
|
635
|
+
```ts
|
|
636
|
+
import { parseInbound } from "loopzero-gateway-telegram";
|
|
637
|
+
|
|
638
|
+
// Inside onMessage. The signature and the JSON parse already happened.
|
|
639
|
+
const event = parseInbound(message.payload);
|
|
640
|
+
if (event !== null) {
|
|
641
|
+
console.log(`${event.platform} ${event.channel.id}: ${event.text}`);
|
|
642
|
+
}
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
`parseInbound` returns `null` rather than throwing for a body it does not recognise. Measured
|
|
646
|
+
against `loopzero@0.48.14`: `onMessage` is
|
|
647
|
+
awaited **before** the 200 is built, and nothing inside `handleChannelWebhook` catches — so a throw
|
|
648
|
+
on an unparseable payload means the 200 is never built. Mounted in a LoopZero route, the rejection
|
|
649
|
+
reaches that route's error boundary and is answered **500**: the platform sees a failed delivery
|
|
650
|
+
where it expected an acknowledgement.
|
|
651
|
+
|
|
652
|
+
### WhatsApp, since `loopzero@0.60.0`
|
|
653
|
+
|
|
654
|
+
Until that release this was impossible rather than undocumented: `loopzero/server/webhook`
|
|
655
|
+
exported no `whatsapp` validator, so the `validators` map could not carry one and the path
|
|
656
|
+
answered 404 by construction. Meta's subscribe handshake had no seam at all
|
|
657
|
+
([getloopscale/loopzero#556](https://github.com/getloopscale/loopzero/issues/556), filed from
|
|
658
|
+
here). Both halves exist now, and the wiring needs three things that are easy to miss:
|
|
659
|
+
|
|
660
|
+
```ts
|
|
661
|
+
import { handleChannelWebhook } from "loopzero/server/agent";
|
|
662
|
+
import { route } from "loopzero/server/define";
|
|
663
|
+
import { whatsapp, whatsappSubscribe } from "loopzero/server/webhook";
|
|
664
|
+
import { parseWebhookPayload, WhatsAppAdapter } from "loopzero-gateway-whatsapp";
|
|
665
|
+
|
|
666
|
+
// The adapter applies the sender allowlist and the group rule, and drops a message addressed to
|
|
667
|
+
// another phone number of the same Meta app. `normalizeInboundMessages` alone applies none of them.
|
|
668
|
+
const adapter = WhatsAppAdapter.fromCloud(
|
|
669
|
+
{
|
|
670
|
+
accessToken: process.env.WHATSAPP_ACCESS_TOKEN!,
|
|
671
|
+
phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!,
|
|
672
|
+
appSecret: process.env.META_APP_SECRET!,
|
|
673
|
+
},
|
|
674
|
+
{ allowedSenders: process.env.WHATSAPP_ALLOWED },
|
|
675
|
+
);
|
|
676
|
+
|
|
677
|
+
async function onMessage({ payload }: { payload: unknown }): Promise<void> {
|
|
678
|
+
const envelope = parseWebhookPayload(payload);
|
|
679
|
+
if (envelope === null) return; // not a shape we know — answer normally
|
|
680
|
+
for (const event of adapter.toDeliverableEvents(envelope)) {
|
|
681
|
+
console.log(`${event.from}: ${event.text}`);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
const handle = ({ request }: { request: Request }) =>
|
|
686
|
+
handleChannelWebhook(request, new URL(request.url).pathname, {
|
|
687
|
+
validators: { whatsapp: whatsapp({ appSecret: process.env.META_APP_SECRET! }) },
|
|
688
|
+
subscribe: { whatsapp: whatsappSubscribe({ verifyToken: process.env.META_VERIFY_TOKEN! }) },
|
|
689
|
+
onMessage,
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
// BOTH verbs, and `.csrf(false)` on each.
|
|
693
|
+
export const GET = route().csrf(false).policy("public").handler(handle).build();
|
|
694
|
+
export const POST = route().csrf(false).policy("public").handler(handle).build();
|
|
695
|
+
```
|
|
696
|
+
|
|
697
|
+
- **`GET` as well as `POST`.** Meta calls the endpoint once with
|
|
698
|
+
`?hub.mode=subscribe&hub.verify_token=…&hub.challenge=…` and expects the challenge echoed as
|
|
699
|
+
`text/plain` before it delivers anything. That is what `subscribe` answers. A `GET` on a
|
|
700
|
+
platform that has a validator and no `subscribe` entry is **405**, not 404 — configured, but
|
|
701
|
+
it does not do handshakes.
|
|
702
|
+
- **`.csrf(false)` on both.** Without it the route answers `403 CSRF_INVALID: Missing
|
|
703
|
+
X-LoopZero-Action header` before the signature is ever checked, and Meta will never send that
|
|
704
|
+
header. `policy("public")` answers a different question — may an unauthenticated caller reach
|
|
705
|
+
this — and does not lift the CSRF gate. The HMAC is strictly stronger than the header it
|
|
706
|
+
replaces, and Meta carries no session for a third-party page to ride.
|
|
707
|
+
- **`appSecret` is the Meta *app secret*,** not the access token. It accepts an array so a
|
|
708
|
+
rotation can verify against either.
|
|
709
|
+
|
|
710
|
+
This package also exports `verifyWebhookSignature` and `verifyWebhookSubscription`, which do
|
|
711
|
+
the same two jobs. Use loopzero's when you are on this seam; ours exist for an app that is not,
|
|
712
|
+
and they are what `gateway-sms` uses through its own `createWebhookServer`.
|
|
713
|
+
|
|
714
|
+
Not verified here: the `loopzero` behaviour above was measured by the session that shipped
|
|
715
|
+
0.60.0, driving a scaffolded app over HTTP. What this repository checked is narrower and
|
|
716
|
+
stated as such — that `loopzero@0.60.0` does export `whatsapp` and `whatsappSubscribe` from
|
|
717
|
+
`loopzero/server/webhook`, that `route` lives on `loopzero/server/define` rather than on the
|
|
718
|
+
`loopzero/server` umbrella that warns it is deprecated, and that `parseWebhookPayload` takes the
|
|
719
|
+
`unknown` payload `onMessage` hands over. A real delivery from Meta needs an approved app and a public URL, and
|
|
720
|
+
has not happened on either side.
|
|
721
|
+
|
|
722
|
+
`parseInbound` under that name exists on `loopzero-gateway-telegram` and `loopzero-gateway-sms`,
|
|
723
|
+
with different arguments: SMS takes `(options, ctx)` because the `SignatureContext` it needs carries
|
|
724
|
+
the raw body, the headers and the URL, and `ChannelMessage` provides none of the three — so it is wired through its
|
|
725
|
+
own `createWebhookServer` rather than this seam.
|
|
726
|
+
Every other adapter exports its translation under its own name — `gateway-line` has
|
|
727
|
+
`lineEventToMessageEvent`, `gateway-whatsapp` composes `parseWebhookPayload` with
|
|
728
|
+
`WhatsAppAdapter.toDeliverableEvents` — each with its own signature: read the one you are using rather than
|
|
729
|
+
assuming this one's.
|
|
730
|
+
|
|
731
|
+
Adapters whose transport is a long-lived connection rather than a webhook own that transport and do
|
|
732
|
+
not go through this seam.
|
|
733
|
+
|
|
734
|
+
## Verifying webhook signatures
|
|
735
|
+
|
|
736
|
+
`verifyHmac`, `verifyDigest` and `safeEqualString` do the constant-time
|
|
737
|
+
signature compare that webhook adapters otherwise hand-write. They return
|
|
738
|
+
`false` (never throw) for a missing, empty, malformed or wrong-prefix
|
|
739
|
+
signature; an empty `secrets` value throws `RangeError`.
|
|
740
|
+
|
|
741
|
+
```ts
|
|
742
|
+
import { verifyHmac } from "loopzero-gateway";
|
|
743
|
+
|
|
744
|
+
// WhatsApp-style: `X-Hub-Signature-256: sha256=<hex>`, over the raw body.
|
|
745
|
+
const ok = verifyHmac({
|
|
746
|
+
algorithm: "sha256",
|
|
747
|
+
secrets: [currentSecret, previousSecret], // accepts either during rotation
|
|
748
|
+
message: rawBody,
|
|
749
|
+
signature: req.headers["x-hub-signature-256"] as string | undefined,
|
|
750
|
+
encoding: "hex",
|
|
751
|
+
prefix: "sha256=",
|
|
752
|
+
caseInsensitive: true,
|
|
753
|
+
});
|
|
754
|
+
```
|
|
755
|
+
|
|
756
|
+
Timestamp windows and field sorting (WeChat, WeCom) stay with the caller; pass
|
|
757
|
+
the built message to `verifyDigest` for keyless SHA-1/SHA-256 schemes.
|
|
758
|
+
|
|
759
|
+
## Verifying a JWT-signed request
|
|
760
|
+
|
|
761
|
+
Platforms that sign requests with an RS256 JWT can share one key-set cache and verifier:
|
|
762
|
+
|
|
763
|
+
```ts
|
|
764
|
+
import { jwksKeySet, verifyRs256Jwt } from "loopzero-gateway";
|
|
765
|
+
|
|
766
|
+
const keys = jwksKeySet({ url: "https://www.googleapis.com/oauth2/v3/certs" });
|
|
767
|
+
const result = await verifyRs256Jwt(bearerToken, keys);
|
|
768
|
+
if (!result.ok) throw new Error(result.reason);
|
|
769
|
+
// result.payload is signature-verified; check issuer, audience and expiry yourself.
|
|
770
|
+
```
|
|
771
|
+
|
|
772
|
+
The cache honours `Cache-Control: max-age`, shares one in-flight read, refetches for an unknown `kid` at most once per `unknownKidRefetchFloorMs` (default 60 s) and, by default, serves a stale key while one refresh runs (`staleWhileRevalidate`). `reason` is `malformed`, `unsupported_alg` (only `RS256` is accepted), `unknown_kid`, `keys_unavailable` or `bad_signature`. `decodeJwt` splits a token without verifying it.
|
|
773
|
+
|
|
774
|
+
## Design principles
|
|
775
|
+
|
|
776
|
+
- **Compose, don't reimplement.** The gateway never owns session persistence (SDK does), never owns scheduling (Cron does), never owns prompt resolution (SystemPromptResolver does).
|
|
777
|
+
- **Adapters are peer-dep packages.** Install only the transports you need.
|
|
778
|
+
- **Hooks live in the gateway, not the SDK.** Transport-layer concerns shouldn't pollute the SDK's Plugin contract.
|
|
779
|
+
|
|
780
|
+
See `.claude/knowledge-base/adrs/D170-D181-*.md` for the full design rationale.
|
|
781
|
+
|
|
782
|
+
## License
|
|
783
|
+
|
|
784
|
+
Apache-2.0
|
|
785
|
+
|
|
786
|
+
### `ReconnectBackoff`
|
|
787
|
+
|
|
788
|
+
Adapters that hold a long-lived socket or stream can reuse the runner's backoff:
|
|
789
|
+
|
|
790
|
+
```ts
|
|
791
|
+
import { ReconnectBackoff } from "loopzero-gateway";
|
|
792
|
+
|
|
793
|
+
const backoff = new ReconnectBackoff({ initialDelayMs: 1000, maxDelayMs: 30_000 });
|
|
794
|
+
// on open: backoff.opened();
|
|
795
|
+
// on close: const delay = backoff.nextDelayMs(); // undefined once maxAttempts is spent
|
|
796
|
+
```
|
|
797
|
+
|
|
798
|
+
Defaults match `ReconnectPolicy` (1 s initial, 60 s cap, factor 2). A connection open for at least
|
|
799
|
+
`stableAfterMs` (default 60 s) resets the delay. A negative or non-finite delay, or a `factor`
|
|
800
|
+
below 1, throws a `RangeError` naming the field.
|
|
801
|
+
|
|
802
|
+
### Reporting diagnostics
|
|
803
|
+
|
|
804
|
+
An adapter should report a diagnostic line through `reportDiagnostic(tag, message)` rather than writing to `process.stderr` itself. It redacts credential-shaped values in `message` and writes `[tag] message` to stderr, so the redaction and any later routing live in one place. Pass `{ failure: true }` for a failure.
|