@theokit/gateway 0.28.0 → 0.29.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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.29.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 4defb5a: `InboundAudio` is read on demand: `data` is replaced by `read(): Promise<Uint8Array>` and an optional `size`. The Telegram adapter downloads a voice note on the first `read()`, so a `pre_inbound` hook that blocks the message causes no download. `withMediaUnderstanding` reads the audio only when a transcriber is configured.
8
+ - 3bf9133: `reconnect: { retryFalse: true }` retries an adapter whose `connect()` answers `false`. A connect the runner abandoned (`connectTimeoutMs`) that rejects later is reported once through `onAdapterState` as `failed`. `runner.connected` is now a method, `runner.connected()`, returning the started adapters (it was a getter returning a set of platform names).
9
+ - dde3a3f: `scopedStrategy` accepts `keys` to override the `main` and linked-peer session keys, so apps with stored sessions can adopt it.
10
+
11
+ ## 0.28.1
12
+
13
+ ### Patch Changes
14
+
15
+ - 6d42c80: Widen the `@theokit/sdk` peer range to `>=4.62.0 <10` so npm admits SDK 6, 7, 8 and 9.
16
+
3
17
  ## 0.28.0
4
18
 
5
19
  ### Minor Changes
package/README.md CHANGED
@@ -148,13 +148,15 @@ An adapter that is called directly (not through `GatewayRunner` or `DeliveryRout
148
148
 
149
149
  ## Voice notes and spoken replies
150
150
 
151
- An inbound event may carry `audio`, an `InboundAudio`: the voice note's bytes (`data`, a
152
- `Uint8Array`), their `mediaType` (such as `audio/ogg`) and `durationSeconds`, a whole number the
153
- platform reported (0 when it reported none). The field is optional and absent on every message
154
- without a voice note. Only the Telegram adapter fills it today, and only for updates it polls: a
155
- voice arriving through a webhook is not read. A voice the adapter could not read leaves `audio`
156
- absent and writes one stderr line naming the reason, so an empty `text` with no `audio` can mean
157
- either; the message is delivered in both cases. The bytes reach `post_inbound` hooks by reference.
151
+ An inbound event may carry `audio`, an `InboundAudio`: `read()`, which returns the voice note's
152
+ bytes as a `Uint8Array`, `size` (the length in bytes the platform reported, absent when it
153
+ reported none), `mediaType` (such as `audio/ogg`) and `durationSeconds`, a whole number the
154
+ platform reported (0 when it reported none). The bytes are fetched on the first `read()` and
155
+ cached, so a `pre_inbound` hook that refuses a sender causes no download. `read()` rejects when
156
+ the bytes cannot be fetched; the message never carries a credential. The field is optional and
157
+ absent on every message without a voice note. Only the Telegram adapter fills it today, and only
158
+ for updates it polls: a voice arriving through a webhook is not read. Migrating from `audio.data`:
159
+ `const data = await event.audio.read()`.
158
160
 
159
161
  To answer with speech, attach an audio clip: `{ kind: "audio", mediaType: "audio/ogg", data }`.
160
162
  `OutboundAttachment` is a union of the image and the audio member, told apart by `kind`; code
@@ -166,7 +168,7 @@ const runner = new GatewayRunner({
166
168
  adapters: [adapter],
167
169
  handler: async (event, ctx) => {
168
170
  if (event.audio === undefined) return;
169
- const text = await transcribe(event.audio.data, event.audio.mediaType);
171
+ const text = await transcribe(await event.audio.read(), event.audio.mediaType);
170
172
  const speech = await synthesize(await answer(text));
171
173
  await ctx.reply(text, { attachments: [{ kind: "audio", mediaType: "audio/ogg", data: speech }] });
172
174
  },
@@ -177,9 +179,8 @@ const runner = new GatewayRunner({
177
179
 
178
180
  A voice note's `text` is empty, so the agent would see nothing. `withMediaUnderstanding` wraps a
179
181
  handler and appends one line per item to `text`: `[Audio transcript: ...]`, or
180
- `[Attachment of type audio/ogg could not be understood]` when the function throws or the payload
181
- exceeds `maxBytes` (default 20 MiB), or `[Attachment of type audio/ogg not understood]` when no
182
- function is configured. The media type is sanitized to `[\w/.+-]`, the event keeps `audio`, and
182
+ `[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
183
+ 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
183
184
  the handler always runs once. `write` receives one line per failure with the type and error name
184
185
  only. The gateway makes no network call; pass plugin-voice's `transcribe`:
185
186
 
@@ -377,6 +378,18 @@ const router = new SessionRouter(
377
378
  );
378
379
  ```
379
380
 
381
+ ### Adopting the strategy with stored sessions
382
+
383
+ 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.
384
+
385
+ ```ts
386
+ scopedStrategy({
387
+ dmScope: "per-peer",
388
+ peerLinks,
389
+ keys: { main: "main", peer: (name) => `peer-${name}` },
390
+ });
391
+ ```
392
+
380
393
  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.
381
394
 
382
395
  ## Keeping a credential across restarts
@@ -520,7 +533,10 @@ else {
520
533
  ignored under `"rollback"`. `secrets: [...]` masks those exact values (longest first) with
521
534
  `[redacted]` in every reason and log line before `redactSecrets` runs (`maskSecrets` is exported).
522
535
  - `runner.adapter(platform)` returns the registered adapter, connected or not, or `undefined`;
523
- `runner.connected` is the live set of connected platforms, updated by retries and `stop()`.
536
+ `runner.connected()` returns the adapters started now, updated by retries and `stop()`.
537
+ - `reconnect: { retryFalse: true }` retries a `connect()` that resolves `false` like a throw, on the
538
+ same backoff. A connect abandoned by `connectTimeoutMs` that rejects later is reported once
539
+ through `onAdapterState` as `failed`, redacted.
524
540
  - `connectFailure` defaults to `"rollback"`: one failed connect disconnects the adapters that did
525
541
  connect and rejects `start()`, as before. Under `"isolate"`, `start()` resolves even when every
526
542
  adapter failed, so check `connected` before you rely on the runner.
package/dist/index.cjs CHANGED
@@ -1663,15 +1663,15 @@ var GatewayRunner = class {
1663
1663
  startInFlight;
1664
1664
  stopped = false;
1665
1665
  retryTimers = /* @__PURE__ */ new Set();
1666
- connectedPlatforms = /* @__PURE__ */ new Set();
1666
+ connectedAdapters = /* @__PURE__ */ new Set();
1667
1667
  redact;
1668
1668
  /** The registered adapter for a platform, connected or not. */
1669
1669
  adapter(platform) {
1670
1670
  return this.opts.adapters.find((a) => a.platform === platform);
1671
1671
  }
1672
- /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
1673
- get connected() {
1674
- return this.connectedPlatforms;
1672
+ /** The adapters started now (a snapshot); updated by connects, retries and `stop()`. */
1673
+ connected() {
1674
+ return [...this.connectedAdapters];
1675
1675
  }
1676
1676
  emitState(platform, state, reason) {
1677
1677
  if ((this.opts.connectFailure ?? "rollback") !== "isolate") return;
@@ -1739,12 +1739,12 @@ var GatewayRunner = class {
1739
1739
  "releasing a start that stop() overtook",
1740
1740
  this.redact
1741
1741
  );
1742
- this.connectedPlatforms.clear();
1742
+ this.connectedAdapters.clear();
1743
1743
  this.startResult = { connected: [], failed: result.failed };
1744
1744
  return this.startResult;
1745
1745
  }
1746
1746
  this.wireInbound(result.connected);
1747
- for (const a of result.connected) this.connectedPlatforms.add(a.platform);
1747
+ for (const a of result.connected) this.connectedAdapters.add(a);
1748
1748
  this.startResult = {
1749
1749
  connected: result.connected.map((a) => a.platform),
1750
1750
  failed: result.failed
@@ -1793,7 +1793,7 @@ var GatewayRunner = class {
1793
1793
  return;
1794
1794
  }
1795
1795
  this.wireInbound([adapter]);
1796
- this.connectedPlatforms.add(adapter.platform);
1796
+ this.connectedAdapters.add(adapter);
1797
1797
  this.emitState(adapter.platform, "connected");
1798
1798
  const prev = this.startResult ?? { connected: [], failed: [] };
1799
1799
  this.startResult = {
@@ -1806,8 +1806,18 @@ var GatewayRunner = class {
1806
1806
  );
1807
1807
  return;
1808
1808
  }
1809
- reportDiagnostic("gateway", `adapter "${adapter.platform}" refused to connect; not retrying`);
1810
- return;
1809
+ if (this.opts.reconnect?.retryFalse) {
1810
+ reportDiagnostic(
1811
+ "gateway",
1812
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} answered false`
1813
+ );
1814
+ } else {
1815
+ reportDiagnostic(
1816
+ "gateway",
1817
+ `adapter "${adapter.platform}" refused to connect; not retrying`
1818
+ );
1819
+ return;
1820
+ }
1811
1821
  } catch (err) {
1812
1822
  const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
1813
1823
  if (isTerminalConnectError(err)) {
@@ -1897,19 +1907,23 @@ var GatewayRunner = class {
1897
1907
  }
1898
1908
  /** A connect that finished after the runner gave up on it must not stay connected unseen. */
1899
1909
  releaseLateConnect(adapter, late) {
1900
- if (late.status !== "fulfilled" || !late.value) return;
1901
- if (this.connectedPlatforms.has(adapter.platform)) return;
1910
+ if (late.status === "rejected") {
1911
+ this.emitState(adapter.platform, "failed", connectFailureReason(late, this.redact));
1912
+ return;
1913
+ }
1914
+ if (!late.value) return;
1915
+ if (this.connectedAdapters.has(adapter)) return;
1902
1916
  void releaseAdapters([adapter], "releasing a connect that timed out", this.redact);
1903
1917
  }
1904
1918
  classify(adapter, outcome) {
1905
1919
  if (outcome.status === "fulfilled" && outcome.value) {
1906
- this.connectedPlatforms.add(adapter.platform);
1920
+ this.connectedAdapters.add(adapter);
1907
1921
  this.emitState(adapter.platform, "connected");
1908
1922
  return { adapter, failure: void 0, retry: false };
1909
1923
  }
1910
1924
  const reason = connectFailureReason(outcome, this.redact);
1911
1925
  this.emitState(adapter.platform, "failed", reason);
1912
- const retry = outcome.status === "rejected" && !isTerminalConnectError(outcome.reason);
1926
+ const retry = outcome.status === "rejected" ? !isTerminalConnectError(outcome.reason) : outcome.value === false && this.opts.reconnect?.retryFalse === true;
1913
1927
  return { adapter, failure: { platform: adapter.platform, reason }, retry };
1914
1928
  }
1915
1929
  wireInbound(adapters) {
@@ -1943,7 +1957,7 @@ var GatewayRunner = class {
1943
1957
  this.unsubs.length = 0;
1944
1958
  for (const t of this.retryTimers) clearTimeout(t);
1945
1959
  this.retryTimers.clear();
1946
- this.connectedPlatforms.clear();
1960
+ this.connectedAdapters.clear();
1947
1961
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
1948
1962
  if (this.inflight.size > 0) {
1949
1963
  let timer;
@@ -2079,12 +2093,17 @@ function withMediaUnderstanding(handler, options) {
2079
2093
  const type = sanitizeType(media.mediaType);
2080
2094
  if (fn === void 0) return `[Attachment of type ${type} not understood]`;
2081
2095
  const failed = `[Attachment of type ${type} could not be understood]`;
2082
- if (media.data.byteLength > maxBytes) {
2096
+ if (media.size !== void 0 && media.size > maxBytes) {
2083
2097
  report(type, "TooLarge");
2084
2098
  return failed;
2085
2099
  }
2086
2100
  try {
2087
- const text = await fn({ data: media.data, mediaType: media.mediaType });
2101
+ const data = await media.read();
2102
+ if (data.byteLength > maxBytes) {
2103
+ report(type, "TooLarge");
2104
+ return failed;
2105
+ }
2106
+ const text = await fn({ data, mediaType: media.mediaType });
2088
2107
  return `[${kind}: ${text}]`;
2089
2108
  } catch (error) {
2090
2109
  report(type, errorName(error));
@@ -2252,7 +2271,7 @@ function invalid(message, detail) {
2252
2271
  });
2253
2272
  }
2254
2273
  function scopedStrategy(options) {
2255
- const { dmScope, peerLinks, accountLabel, groupScope = "channel" } = options;
2274
+ const { dmScope, peerLinks, accountLabel, groupScope = "channel", keys } = options;
2256
2275
  if (dmScope === "per-account-channel-peer" && (accountLabel === void 0 || accountLabel === "")) {
2257
2276
  throw invalid("per-account-channel-peer requires a non-empty accountLabel", "accountLabel");
2258
2277
  }
@@ -2264,10 +2283,11 @@ function scopedStrategy(options) {
2264
2283
  const dmKey = (platform, senderId) => {
2265
2284
  switch (dmScope) {
2266
2285
  case "main":
2267
- return "_m-dm";
2286
+ return keys?.main ?? "_m-dm";
2268
2287
  case "per-peer": {
2269
2288
  const peer = peerLinks?.get(`${platform}:${senderId}`);
2270
- return peer === void 0 ? join3(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
2289
+ if (peer === void 0) return join3(platform, "dm", senderId);
2290
+ return keys?.peer === void 0 ? `_p-dm-${sanitize(peer)}` : keys.peer(peer);
2271
2291
  }
2272
2292
  case "per-channel-peer":
2273
2293
  return join3(platform, "dm", senderId);