@theokit/gateway 0.18.0 → 0.19.0

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 CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.19.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9c832b2: Add `AdapterCapabilities` and `BasePlatformAdapter.capabilities` (edit, attachment kinds, typing, reactions, threads, max length), derived by default. Telegram reports `image` and `audio` attachments.
8
+ - 6a80cc5: Add `createAgentBindings` and `bindingStrategy`: rule-based choice of agent by platform, account and peer, with session keys prefixed by the bound agent.
9
+ - 8e54100: Add `parseChatCommand`, `commandHook` and `helpText`: one `pre_inbound` hook that strips a leading mention and `@bot` suffix, matches commands exactly and answers `/help`.
10
+ - 362e4ef: Add `createWebhookHandler`, a Fetch handler that routes every webhook channel, and `statusForDeliver`. `ChannelWebhook` gains optional `methods` and `handle`, and `WebhookRequest` gains `method` and `url`.
11
+ - 9f21ff7: `GatewayRunner` gains `connectTimeoutMs`, `onAdapterState` and `secrets` options (under `connectFailure: "isolate"`), an `adapter(platform)` lookup, a live `connected` set, and an exported `maskSecrets` helper and `AdapterState` type.
12
+ - 56bb1d8: Declare whether a channel's sender id is authenticated with `senderIdentity`.
13
+
14
+ ### Patch Changes
15
+
16
+ - e2a6da8: The cross-adapter lint tests no longer count `gateway-agent`, which bridges an agent to adapters and is not a platform adapter.
17
+
3
18
  ## 0.18.0
4
19
 
5
20
  ### Minor Changes
package/README.md CHANGED
@@ -246,6 +246,57 @@ reach the platform in either order, and the one that lands last stays on screen;
246
246
  edit is a separate event and clients show the newest. Await each edit before sending the next,
247
247
  or keep one in flight and send only the latest text when it settles.
248
248
 
249
+ ## Adapter capabilities
250
+
251
+ Every adapter has a `capabilities` getter, so an app reads what a channel can do instead of
252
+ keeping a table of platform names:
253
+
254
+ ```ts
255
+ const { edit, attachments, typing, reactions, threads, maxMessageChars } = adapter.capabilities;
256
+ ```
257
+
258
+ - `edit` is `supportsEdit`.
259
+ - `attachments` lists the kinds the adapter sends (`"image"`, `"audio"`); `[]` when none. An
260
+ adapter that sets only `supportsAttachments = true` reports `["image"]`; one that sends more
261
+ sets the protected `attachmentKinds`.
262
+ - `typing` and `reactions` are `true` when the adapter overrides `startTyping` and `react`.
263
+ - `threads` is `false` and `maxMessageChars` is `undefined` unless an adapter overrides the
264
+ getter; no adapter sets them yet.
265
+
266
+ The type is exported as `AdapterCapabilities`.
267
+
268
+ ## Chat commands
269
+
270
+ `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)`.
271
+
272
+ ```ts
273
+ import { commandHook } from "@theokit/gateway";
274
+
275
+ const hook = commandHook([
276
+ { name: "new", description: "Start a new chat", arg: "none", run: () => ({ block: true, message: "Reset." }) },
277
+ { name: "think", description: "Set thinking", usage: "/think off|low|medium|high", run: (_e, arg) => ({ block: true, message: `think=${arg}` }) },
278
+ ]);
279
+ ```
280
+
281
+ 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.
282
+
283
+ ## Agent bindings
284
+
285
+ 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`.
286
+
287
+ ```ts
288
+ import { bindingStrategy, createAgentBindings, defaultStrategy, SessionRouter } from "@theokit/gateway";
289
+
290
+ const bindings = createAgentBindings({
291
+ defaultAgent: "personal",
292
+ agents: ["personal", "support"],
293
+ rules: [{ agent: "support", platform: "slack" }],
294
+ });
295
+ const router = new SessionRouter(bindingStrategy(bindings, defaultStrategy));
296
+ ```
297
+
298
+ `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.
299
+
249
300
  ## Architecture (5 pieces)
250
301
 
251
302
  | Module | Responsibility |
@@ -332,6 +383,15 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
332
383
  `connectFailure: "isolate"` (under `"rollback"` the start still rejects). A `connect()` that
333
384
  returns `false`, or throws a 401/403 credential error, is reported once and never retried.
334
385
  `start()` called again afterwards returns the updated `connected` and `failed`.
386
+ - `connectTimeoutMs` (under `"isolate"`) gives up on one adapter's `connect()` after that many ms:
387
+ it is reported `timed_out` in `StartResult.failed`, never wired for inbound, and disconnected if
388
+ its `connect()` resolves `true` later. With `reconnect` it is retried like a transient failure.
389
+ `onAdapterState(platform, state, reason?)` fires as each adapter becomes `connected`, `failed`,
390
+ `retrying` or `timed_out`, while `start()` may still be pending; `reason` is redacted. Both are
391
+ ignored under `"rollback"`. `secrets: [...]` masks those exact values (longest first) with
392
+ `[redacted]` in every reason and log line before `redactSecrets` runs (`maskSecrets` is exported).
393
+ - `runner.adapter(platform)` returns the registered adapter, connected or not, or `undefined`;
394
+ `runner.connected` is the live set of connected platforms, updated by retries and `stop()`.
335
395
  - `connectFailure` defaults to `"rollback"`: one failed connect disconnects the adapters that did
336
396
  connect and rejects `start()`, as before. Under `"isolate"`, `start()` resolves even when every
337
397
  adapter failed, so check `connected` before you rely on the runner.
@@ -361,6 +421,45 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
361
421
  `failed` under `"isolate"`. Acknowledging it loses the message, since the platform does not
362
422
  redeliver an acknowledged request.
363
423
 
424
+ ### Mounting webhooks in a Fetch server
425
+
426
+ `createWebhookHandler` routes `/webhooks/<platform>` for every `transport: "webhook"` channel. It
427
+ answers 404 for an unknown platform, 503 while the platform has not started, 405 for a method the
428
+ route does not take, 413 (with `connection: close`) past `maxBodyBytes` (default 1 MiB), 401 when
429
+ `verify` fails, 400 for a body that is not JSON or is `"malformed"`, and 503 for `"no_handler"`. A
430
+ descriptor with `webhook.handle` answers the request itself (method, URL and query included).
431
+ A throw gives 500 with no body and calls `onError(platform, error)`. `statusForDeliver(outcomes)`
432
+ maps `deliver()` outcomes to a status, worst wins.
433
+
434
+ ```ts
435
+ import { createChannels, createWebhookHandler } from "@theokit/gateway";
436
+
437
+ const { channels } = createChannels(entries);
438
+ const handler = createWebhookHandler({
439
+ channels,
440
+ isStarted: (platform) => runnerStarted.has(platform),
441
+ onError: (platform, error) => log.error({ platform, error }),
442
+ });
443
+
444
+ Bun.serve({ port: 3000, fetch: handler });
445
+ ```
446
+
447
+ ### Is the sender id authenticated?
448
+
449
+ A descriptor can say whether `sender.id` is proven by the platform with `senderIdentity`:
450
+ `"authenticated"`, or `{ unauthenticated: "why it can be forged" }` for a channel such as email (the
451
+ From header) or SMS (the caller id), where the sender writes the id (CWE-290).
452
+ `isAuthenticatedSender(descriptor)` is true only for `"authenticated"`. A descriptor that does not
453
+ set the field is unknown, and unknown is treated as not authenticated (fail closed), so an app
454
+ that lets owners control an agent should refuse owner entries on such a channel.
455
+
456
+ ```typescript
457
+ import { isAuthenticatedSender } from "@theokit/gateway";
458
+ import { telegramChannel } from "@theokit/gateway-telegram";
459
+
460
+ isAuthenticatedSender(telegramChannel); // true
461
+ ```
462
+
364
463
  ## Receiving from a TheoKit app
365
464
 
366
465
  Three repositories share this path. `theokit` owns the HTTP route and the signature check —