@theokit/gateway 0.16.1 → 0.18.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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.18.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 58aadd0: Add `withMediaUnderstanding`, a handler wrapper that folds a voice note's transcript into the turn text, naming any attachment it could not understand.
8
+
9
+ ## 0.17.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 6329554: `rawBodyCapture` now refuses a body over 1 MiB with 413 when `maxBytes` is not given. The default is exported as `DEFAULT_WEBHOOK_MAX_BYTES`; pass `maxBytes: Number.POSITIVE_INFINITY` for no limit.
14
+
3
15
  ## 0.16.1
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -167,6 +167,30 @@ const runner = new GatewayRunner({
167
167
  });
168
168
  ```
169
169
 
170
+ ### Folding a transcript into the turn text
171
+
172
+ A voice note's `text` is empty, so the agent would see nothing. `withMediaUnderstanding` wraps a
173
+ handler and appends one line per item to `text`: `[Audio transcript: ...]`, or
174
+ `[Attachment of type audio/ogg could not be understood]` when the function throws or the payload
175
+ exceeds `maxBytes` (default 20 MiB), or `[Attachment of type audio/ogg not understood]` when no
176
+ function is configured. The media type is sanitized to `[\w/.+-]`, the event keeps `audio`, and
177
+ the handler always runs once. `write` receives one line per failure with the type and error name
178
+ only. The gateway makes no network call; pass plugin-voice's `transcribe`:
179
+
180
+ ```typescript
181
+ import { GatewayRunner, withMediaUnderstanding } from "@theokit/gateway";
182
+ import { transcribe } from "@theokit/plugin-voice";
183
+
184
+ const runner = new GatewayRunner({
185
+ adapters: [adapter],
186
+ handler: withMediaUnderstanding(answer, {
187
+ transcribe: (audio) => transcribe(audio, voiceConfig),
188
+ }),
189
+ });
190
+ ```
191
+
192
+ `describeImage` is accepted for when events carry image bytes; no adapter fills them today.
193
+
170
194
  ## Editing a sent message
171
195
 
172
196
  Six adapters can replace the text of a message they sent, keeping its id: Telegram, Discord,
@@ -325,6 +349,9 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
325
349
  - `start()` waits for every connect under both `connectFailure` modes, so a connect that never
326
350
  settles blocks it. Under `"rollback"` that holds after a failure too: a failing start rejects
327
351
  only once its slowest connect settles.
352
+ - `rawBodyCapture(tag, { maxBytes })` (Express webhook routes) answers 413 with
353
+ `{ "error": "request body too large" }` to a body over `maxBytes`. The default is
354
+ `DEFAULT_WEBHOOK_MAX_BYTES`, 1 MiB; pass `Number.POSITIVE_INFINITY` for no limit.
328
355
  - A webhook channel's request reaches your HTTP route; route it by platform to the descriptor's
329
356
  `webhook.verify(adapter, { rawBody, headers })`, then parse the body and pass it to
330
357
  `webhook.ingest(adapter, payload)`, which answers `"delivered"`, `"malformed"` or
package/dist/index.cjs CHANGED
@@ -1250,6 +1250,54 @@ var GatewayRunner = class {
1250
1250
  }
1251
1251
  };
1252
1252
 
1253
+ // src/runner/media-understanding.ts
1254
+ var DEFAULT_MAX_BYTES = 20 * 1024 * 1024;
1255
+ function sanitizeType(mediaType) {
1256
+ return mediaType.replace(/[^\w/.+-]/g, "");
1257
+ }
1258
+ function errorName(error) {
1259
+ return error instanceof Error ? error.name : "UnknownError";
1260
+ }
1261
+ function withMediaUnderstanding(handler, options) {
1262
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
1263
+ const write = options.write ?? ((line) => void process.stderr.write(`${line}
1264
+ `));
1265
+ const understand = async (kind, media, fn) => {
1266
+ const type = sanitizeType(media.mediaType);
1267
+ if (fn === void 0) return `[Attachment of type ${type} not understood]`;
1268
+ const failed = `[Attachment of type ${type} could not be understood]`;
1269
+ if (media.data.byteLength > maxBytes) {
1270
+ report(type, "TooLarge");
1271
+ return failed;
1272
+ }
1273
+ try {
1274
+ const text = await fn({ data: media.data, mediaType: media.mediaType });
1275
+ return `[${kind}: ${text}]`;
1276
+ } catch (error) {
1277
+ report(type, errorName(error));
1278
+ return failed;
1279
+ }
1280
+ };
1281
+ const report = (type, name) => {
1282
+ try {
1283
+ write(`[gateway] media understanding failed for ${type}: ${name}`);
1284
+ } catch {
1285
+ }
1286
+ };
1287
+ return async (event, ctx) => {
1288
+ const lines = [];
1289
+ if (event.audio !== void 0) {
1290
+ lines.push(
1291
+ await understand("Audio transcript", event.audio, options.transcribe?.bind(options))
1292
+ );
1293
+ }
1294
+ if (lines.length === 0) return handler(event, ctx);
1295
+ const text = [event.text, ...lines].filter((part) => part !== "").join("\n");
1296
+ const wrapped = { ...event, text };
1297
+ return handler(wrapped, ctx);
1298
+ };
1299
+ }
1300
+
1253
1301
  // src/session/router.ts
1254
1302
  function defaultStrategy(event) {
1255
1303
  const { platform, channel, sender } = event;
@@ -1524,10 +1572,10 @@ async function loadPeer(load, onMissing) {
1524
1572
  }
1525
1573
  }
1526
1574
  function rawBodyCapture(tag, options = {}) {
1527
- const { maxBytes } = options;
1528
- if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes >= 0)) {
1575
+ const maxBytes = options.maxBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;
1576
+ if (!(maxBytes >= 0)) {
1529
1577
  throw new RangeError(
1530
- `[${tag}] rawBodyCapture: maxBytes must be a finite number of zero or more, got ${maxBytes}`
1578
+ `[${tag}] rawBodyCapture: maxBytes must be a number of zero or more (Infinity allowed), got ${maxBytes}`
1531
1579
  );
1532
1580
  }
1533
1581
  return (rawReq, rawRes, next) => {
@@ -1543,13 +1591,13 @@ function rawBodyCapture(tag, options = {}) {
1543
1591
  }
1544
1592
  let buf = "";
1545
1593
  let bytes = 0;
1546
- let refused2 = maxBytes !== void 0 && declaredLength(req) > maxBytes;
1594
+ let refused2 = declaredLength(req) > maxBytes;
1547
1595
  let settled = false;
1548
1596
  req.setEncoding("utf8");
1549
1597
  req.on("data", (chunk) => {
1550
1598
  if (refused2 || settled) return;
1551
1599
  bytes += Buffer.byteLength(chunk);
1552
- if (maxBytes !== void 0 && bytes > maxBytes) {
1600
+ if (bytes > maxBytes) {
1553
1601
  refused2 = true;
1554
1602
  buf = "";
1555
1603
  return;
@@ -1560,7 +1608,7 @@ function rawBodyCapture(tag, options = {}) {
1560
1608
  if (settled) return;
1561
1609
  settled = true;
1562
1610
  if (refused2) {
1563
- answerTooLarge(rawRes, tag, maxBytes ?? 0);
1611
+ answerTooLarge(rawRes, tag, maxBytes);
1564
1612
  return;
1565
1613
  }
1566
1614
  req.rawBody = buf;
@@ -1574,6 +1622,7 @@ function rawBodyCapture(tag, options = {}) {
1574
1622
  });
1575
1623
  };
1576
1624
  }
1625
+ var DEFAULT_WEBHOOK_MAX_BYTES = 1024 * 1024;
1577
1626
  function declaredLength(req) {
1578
1627
  const value = req.headers?.["content-length"];
1579
1628
  const declared = Number(Array.isArray(value) ? value[0] : value);
@@ -1625,6 +1674,7 @@ function listenerLifecycle(opts) {
1625
1674
 
1626
1675
  exports.BasePlatformAdapter = BasePlatformAdapter;
1627
1676
  exports.CREDENTIAL_SHAPES = CREDENTIAL_SHAPES;
1677
+ exports.DEFAULT_WEBHOOK_MAX_BYTES = DEFAULT_WEBHOOK_MAX_BYTES;
1628
1678
  exports.DeliveryRouter = DeliveryRouter;
1629
1679
  exports.GatewayConfigurationError = GatewayConfigurationError;
1630
1680
  exports.GatewayLifecycleError = GatewayLifecycleError;
@@ -1647,5 +1697,6 @@ exports.redactSecrets = redactSecrets;
1647
1697
  exports.scanFences = scanFences;
1648
1698
  exports.splitKeepingRows = splitKeepingRows;
1649
1699
  exports.toDialect = toDialect;
1700
+ exports.withMediaUnderstanding = withMediaUnderstanding;
1650
1701
  //# sourceMappingURL=index.cjs.map
1651
1702
  //# sourceMappingURL=index.cjs.map