@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/dist/index.d.cts CHANGED
@@ -379,15 +379,19 @@ interface XMessageEvent extends BaseMessageEvent {
379
379
  */
380
380
 
381
381
  /**
382
- * The audio of a voice note an inbound message carries (B-715): its bytes, their media type and
383
- * the length the platform reported.
382
+ * The audio of a voice note an inbound message carries (B-715): read on demand, so an app whose
383
+ * `pre_inbound` hook refuses a sender never downloads the sender's media.
384
384
  *
385
- * The bytes travel by reference, as an outbound attachment's do: hooks and the handler see the
386
- * same array.
385
+ * Nothing is fetched until `read()` is called. The first call fetches; later calls return the
386
+ * same bytes. `read()` rejects when the platform cannot deliver them (the error message is safe
387
+ * to log: it never carries a credential).
387
388
  */
388
389
  interface InboundAudio {
389
- readonly data: Uint8Array;
390
- /** The media type of `data`, such as `audio/ogg`. */
390
+ /** The audio bytes, fetched on the first call and cached. */
391
+ read(): Promise<Uint8Array>;
392
+ /** The length in bytes the platform reported before any download; absent when it reported none. */
393
+ readonly size?: number;
394
+ /** The media type of the bytes, such as `audio/ogg`. */
391
395
  readonly mediaType: string;
392
396
  /** The length in whole seconds the platform reported; 0 when it reported none. */
393
397
  readonly durationSeconds: number;
@@ -2024,6 +2028,11 @@ interface ReconnectPolicy {
2024
2028
  readonly factor?: number;
2025
2029
  /** Give up after this many retries. Default: keep trying until `stop()`. */
2026
2030
  readonly maxAttempts?: number;
2031
+ /**
2032
+ * Treat a `connect()` that resolves `false` like one that throws a transient error: retry it on
2033
+ * the same backoff. Default `false`, where `false` is final.
2034
+ */
2035
+ readonly retryFalse?: boolean;
2027
2036
  }
2028
2037
  /**
2029
2038
  * How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
@@ -2065,13 +2074,13 @@ declare class GatewayRunner {
2065
2074
  private startInFlight;
2066
2075
  private stopped;
2067
2076
  private readonly retryTimers;
2068
- private readonly connectedPlatforms;
2077
+ private readonly connectedAdapters;
2069
2078
  private readonly redact;
2070
2079
  constructor(opts: GatewayRunnerOptions);
2071
2080
  /** The registered adapter for a platform, connected or not. */
2072
2081
  adapter(platform: PlatformName): BasePlatformAdapter | undefined;
2073
- /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
2074
- get connected(): ReadonlySet<PlatformName>;
2082
+ /** The adapters started now (a snapshot); updated by connects, retries and `stop()`. */
2083
+ connected(): BasePlatformAdapter[];
2075
2084
  private emitState;
2076
2085
  /**
2077
2086
  * Register a slash command. Match rule (EC-A): text === "/" + name
@@ -2377,6 +2386,15 @@ interface ScopedStrategyOptions {
2377
2386
  readonly accountLabel?: string;
2378
2387
  /** Group key: one per channel (default) or one per channel and sender. */
2379
2388
  readonly groupScope?: "channel" | "channel-sender";
2389
+ /**
2390
+ * Overrides the `main` and linked-peer DM keys so an app can keep the keys
2391
+ * its stored sessions already use. `peer` receives the raw (unescaped) peer
2392
+ * name. The caller owns uniqueness: a custom key can collide with other keys.
2393
+ */
2394
+ readonly keys?: {
2395
+ readonly main?: string;
2396
+ readonly peer?: (name: string) => string;
2397
+ };
2380
2398
  }
2381
2399
  /**
2382
2400
  * Builds a strategy for the chosen DM scope. Keys:
@@ -2385,6 +2403,7 @@ interface ScopedStrategyOptions {
2385
2403
  * `per-account-channel-peer` → `<platform>-dm-<account>-<sender>`.
2386
2404
  * Groups are `<platform>-grp-<channel>[-<sender>]`, topic threads
2387
2405
  * `<platform>-tpc-<channel>-<topic>`. Every segment is escaped with `sanitize`.
2406
+ * `keys` replaces the `main` and linked-peer formats. A throwing `keys.peer` throws per event.
2388
2407
  * Throws `GatewayConfigurationError` (`invalid_session_scope`) on bad options, never per event.
2389
2408
  */
2390
2409
  declare function scopedStrategy(options: ScopedStrategyOptions): AgentIdStrategy;
package/dist/index.d.ts CHANGED
@@ -379,15 +379,19 @@ interface XMessageEvent extends BaseMessageEvent {
379
379
  */
380
380
 
381
381
  /**
382
- * The audio of a voice note an inbound message carries (B-715): its bytes, their media type and
383
- * the length the platform reported.
382
+ * The audio of a voice note an inbound message carries (B-715): read on demand, so an app whose
383
+ * `pre_inbound` hook refuses a sender never downloads the sender's media.
384
384
  *
385
- * The bytes travel by reference, as an outbound attachment's do: hooks and the handler see the
386
- * same array.
385
+ * Nothing is fetched until `read()` is called. The first call fetches; later calls return the
386
+ * same bytes. `read()` rejects when the platform cannot deliver them (the error message is safe
387
+ * to log: it never carries a credential).
387
388
  */
388
389
  interface InboundAudio {
389
- readonly data: Uint8Array;
390
- /** The media type of `data`, such as `audio/ogg`. */
390
+ /** The audio bytes, fetched on the first call and cached. */
391
+ read(): Promise<Uint8Array>;
392
+ /** The length in bytes the platform reported before any download; absent when it reported none. */
393
+ readonly size?: number;
394
+ /** The media type of the bytes, such as `audio/ogg`. */
391
395
  readonly mediaType: string;
392
396
  /** The length in whole seconds the platform reported; 0 when it reported none. */
393
397
  readonly durationSeconds: number;
@@ -2024,6 +2028,11 @@ interface ReconnectPolicy {
2024
2028
  readonly factor?: number;
2025
2029
  /** Give up after this many retries. Default: keep trying until `stop()`. */
2026
2030
  readonly maxAttempts?: number;
2031
+ /**
2032
+ * Treat a `connect()` that resolves `false` like one that throws a transient error: retry it on
2033
+ * the same backoff. Default `false`, where `false` is final.
2034
+ */
2035
+ readonly retryFalse?: boolean;
2027
2036
  }
2028
2037
  /**
2029
2038
  * How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
@@ -2065,13 +2074,13 @@ declare class GatewayRunner {
2065
2074
  private startInFlight;
2066
2075
  private stopped;
2067
2076
  private readonly retryTimers;
2068
- private readonly connectedPlatforms;
2077
+ private readonly connectedAdapters;
2069
2078
  private readonly redact;
2070
2079
  constructor(opts: GatewayRunnerOptions);
2071
2080
  /** The registered adapter for a platform, connected or not. */
2072
2081
  adapter(platform: PlatformName): BasePlatformAdapter | undefined;
2073
- /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
2074
- get connected(): ReadonlySet<PlatformName>;
2082
+ /** The adapters started now (a snapshot); updated by connects, retries and `stop()`. */
2083
+ connected(): BasePlatformAdapter[];
2075
2084
  private emitState;
2076
2085
  /**
2077
2086
  * Register a slash command. Match rule (EC-A): text === "/" + name
@@ -2377,6 +2386,15 @@ interface ScopedStrategyOptions {
2377
2386
  readonly accountLabel?: string;
2378
2387
  /** Group key: one per channel (default) or one per channel and sender. */
2379
2388
  readonly groupScope?: "channel" | "channel-sender";
2389
+ /**
2390
+ * Overrides the `main` and linked-peer DM keys so an app can keep the keys
2391
+ * its stored sessions already use. `peer` receives the raw (unescaped) peer
2392
+ * name. The caller owns uniqueness: a custom key can collide with other keys.
2393
+ */
2394
+ readonly keys?: {
2395
+ readonly main?: string;
2396
+ readonly peer?: (name: string) => string;
2397
+ };
2380
2398
  }
2381
2399
  /**
2382
2400
  * Builds a strategy for the chosen DM scope. Keys:
@@ -2385,6 +2403,7 @@ interface ScopedStrategyOptions {
2385
2403
  * `per-account-channel-peer` → `<platform>-dm-<account>-<sender>`.
2386
2404
  * Groups are `<platform>-grp-<channel>[-<sender>]`, topic threads
2387
2405
  * `<platform>-tpc-<channel>-<topic>`. Every segment is escaped with `sanitize`.
2406
+ * `keys` replaces the `main` and linked-peer formats. A throwing `keys.peer` throws per event.
2388
2407
  * Throws `GatewayConfigurationError` (`invalid_session_scope`) on bad options, never per event.
2389
2408
  */
2390
2409
  declare function scopedStrategy(options: ScopedStrategyOptions): AgentIdStrategy;
package/dist/index.js CHANGED
@@ -1661,15 +1661,15 @@ var GatewayRunner = class {
1661
1661
  startInFlight;
1662
1662
  stopped = false;
1663
1663
  retryTimers = /* @__PURE__ */ new Set();
1664
- connectedPlatforms = /* @__PURE__ */ new Set();
1664
+ connectedAdapters = /* @__PURE__ */ new Set();
1665
1665
  redact;
1666
1666
  /** The registered adapter for a platform, connected or not. */
1667
1667
  adapter(platform) {
1668
1668
  return this.opts.adapters.find((a) => a.platform === platform);
1669
1669
  }
1670
- /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
1671
- get connected() {
1672
- return this.connectedPlatforms;
1670
+ /** The adapters started now (a snapshot); updated by connects, retries and `stop()`. */
1671
+ connected() {
1672
+ return [...this.connectedAdapters];
1673
1673
  }
1674
1674
  emitState(platform, state, reason) {
1675
1675
  if ((this.opts.connectFailure ?? "rollback") !== "isolate") return;
@@ -1737,12 +1737,12 @@ var GatewayRunner = class {
1737
1737
  "releasing a start that stop() overtook",
1738
1738
  this.redact
1739
1739
  );
1740
- this.connectedPlatforms.clear();
1740
+ this.connectedAdapters.clear();
1741
1741
  this.startResult = { connected: [], failed: result.failed };
1742
1742
  return this.startResult;
1743
1743
  }
1744
1744
  this.wireInbound(result.connected);
1745
- for (const a of result.connected) this.connectedPlatforms.add(a.platform);
1745
+ for (const a of result.connected) this.connectedAdapters.add(a);
1746
1746
  this.startResult = {
1747
1747
  connected: result.connected.map((a) => a.platform),
1748
1748
  failed: result.failed
@@ -1791,7 +1791,7 @@ var GatewayRunner = class {
1791
1791
  return;
1792
1792
  }
1793
1793
  this.wireInbound([adapter]);
1794
- this.connectedPlatforms.add(adapter.platform);
1794
+ this.connectedAdapters.add(adapter);
1795
1795
  this.emitState(adapter.platform, "connected");
1796
1796
  const prev = this.startResult ?? { connected: [], failed: [] };
1797
1797
  this.startResult = {
@@ -1804,8 +1804,18 @@ var GatewayRunner = class {
1804
1804
  );
1805
1805
  return;
1806
1806
  }
1807
- reportDiagnostic("gateway", `adapter "${adapter.platform}" refused to connect; not retrying`);
1808
- return;
1807
+ if (this.opts.reconnect?.retryFalse) {
1808
+ reportDiagnostic(
1809
+ "gateway",
1810
+ `adapter "${adapter.platform}" reconnect attempt ${attempt} answered false`
1811
+ );
1812
+ } else {
1813
+ reportDiagnostic(
1814
+ "gateway",
1815
+ `adapter "${adapter.platform}" refused to connect; not retrying`
1816
+ );
1817
+ return;
1818
+ }
1809
1819
  } catch (err) {
1810
1820
  const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
1811
1821
  if (isTerminalConnectError(err)) {
@@ -1895,19 +1905,23 @@ var GatewayRunner = class {
1895
1905
  }
1896
1906
  /** A connect that finished after the runner gave up on it must not stay connected unseen. */
1897
1907
  releaseLateConnect(adapter, late) {
1898
- if (late.status !== "fulfilled" || !late.value) return;
1899
- if (this.connectedPlatforms.has(adapter.platform)) return;
1908
+ if (late.status === "rejected") {
1909
+ this.emitState(adapter.platform, "failed", connectFailureReason(late, this.redact));
1910
+ return;
1911
+ }
1912
+ if (!late.value) return;
1913
+ if (this.connectedAdapters.has(adapter)) return;
1900
1914
  void releaseAdapters([adapter], "releasing a connect that timed out", this.redact);
1901
1915
  }
1902
1916
  classify(adapter, outcome) {
1903
1917
  if (outcome.status === "fulfilled" && outcome.value) {
1904
- this.connectedPlatforms.add(adapter.platform);
1918
+ this.connectedAdapters.add(adapter);
1905
1919
  this.emitState(adapter.platform, "connected");
1906
1920
  return { adapter, failure: void 0, retry: false };
1907
1921
  }
1908
1922
  const reason = connectFailureReason(outcome, this.redact);
1909
1923
  this.emitState(adapter.platform, "failed", reason);
1910
- const retry = outcome.status === "rejected" && !isTerminalConnectError(outcome.reason);
1924
+ const retry = outcome.status === "rejected" ? !isTerminalConnectError(outcome.reason) : outcome.value === false && this.opts.reconnect?.retryFalse === true;
1911
1925
  return { adapter, failure: { platform: adapter.platform, reason }, retry };
1912
1926
  }
1913
1927
  wireInbound(adapters) {
@@ -1941,7 +1955,7 @@ var GatewayRunner = class {
1941
1955
  this.unsubs.length = 0;
1942
1956
  for (const t of this.retryTimers) clearTimeout(t);
1943
1957
  this.retryTimers.clear();
1944
- this.connectedPlatforms.clear();
1958
+ this.connectedAdapters.clear();
1945
1959
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
1946
1960
  if (this.inflight.size > 0) {
1947
1961
  let timer;
@@ -2077,12 +2091,17 @@ function withMediaUnderstanding(handler, options) {
2077
2091
  const type = sanitizeType(media.mediaType);
2078
2092
  if (fn === void 0) return `[Attachment of type ${type} not understood]`;
2079
2093
  const failed = `[Attachment of type ${type} could not be understood]`;
2080
- if (media.data.byteLength > maxBytes) {
2094
+ if (media.size !== void 0 && media.size > maxBytes) {
2081
2095
  report(type, "TooLarge");
2082
2096
  return failed;
2083
2097
  }
2084
2098
  try {
2085
- const text = await fn({ data: media.data, mediaType: media.mediaType });
2099
+ const data = await media.read();
2100
+ if (data.byteLength > maxBytes) {
2101
+ report(type, "TooLarge");
2102
+ return failed;
2103
+ }
2104
+ const text = await fn({ data, mediaType: media.mediaType });
2086
2105
  return `[${kind}: ${text}]`;
2087
2106
  } catch (error) {
2088
2107
  report(type, errorName(error));
@@ -2250,7 +2269,7 @@ function invalid(message, detail) {
2250
2269
  });
2251
2270
  }
2252
2271
  function scopedStrategy(options) {
2253
- const { dmScope, peerLinks, accountLabel, groupScope = "channel" } = options;
2272
+ const { dmScope, peerLinks, accountLabel, groupScope = "channel", keys } = options;
2254
2273
  if (dmScope === "per-account-channel-peer" && (accountLabel === void 0 || accountLabel === "")) {
2255
2274
  throw invalid("per-account-channel-peer requires a non-empty accountLabel", "accountLabel");
2256
2275
  }
@@ -2262,10 +2281,11 @@ function scopedStrategy(options) {
2262
2281
  const dmKey = (platform, senderId) => {
2263
2282
  switch (dmScope) {
2264
2283
  case "main":
2265
- return "_m-dm";
2284
+ return keys?.main ?? "_m-dm";
2266
2285
  case "per-peer": {
2267
2286
  const peer = peerLinks?.get(`${platform}:${senderId}`);
2268
- return peer === void 0 ? join3(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
2287
+ if (peer === void 0) return join3(platform, "dm", senderId);
2288
+ return keys?.peer === void 0 ? `_p-dm-${sanitize(peer)}` : keys.peer(peer);
2269
2289
  }
2270
2290
  case "per-channel-peer":
2271
2291
  return join3(platform, "dm", senderId);