@theokit/gateway 0.25.0 → 0.26.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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.26.0
4
+
5
+ ### Minor Changes
6
+
7
+ - f357dab: Export `ReconnectBackoff` and `ReconnectBackoffOptions` so adapters that hold a long-lived connection can share the runner's reconnect backoff, including a reset after a stable connection. `GatewayRunner` now uses it for its own retries.
8
+ - 770b67f: Type `SendResult.error` as `SendError` with shared `SendErrorCode` values, `retryAfterMs` and `platformCode`, and add `sendErrorFromHttp` to map an HTTP status to a `SendResult`.
9
+ - d7dbc27: `splitKeepingRows` takes an optional `{ unit: "utf16" | "codepoint" }` so `partLimit` can be measured in code points. `SplitKeepingRowsOptions` is exported.
10
+ - 28d3dd5: Add `createTokenCache` for expiring access tokens with one shared refresh, and use it in `WeixinAdapterBase`.
11
+
3
12
  ## 0.25.0
4
13
 
5
14
  ### Minor Changes
package/README.md CHANGED
@@ -88,6 +88,10 @@ presenter per turn; it keeps state between `present()` calls.
88
88
  does with `format`; none was observed on a real client.
89
89
  - The presenter never splits. Each adapter's `sendMessage` splits a long message at its own
90
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`.
91
95
  - `channelRendering` throws a `RangeError` for a platform it does not know, rather than letting
92
96
  the presenter fall back to markdown.
93
97
  - `@theokit/presenter` is your dependency, not this package's: `@theokit/gateway` does not depend
@@ -265,6 +269,31 @@ const { edit, attachments, typing, reactions, threads, maxMessageChars } = adapt
265
269
 
266
270
  The type is exported as `AdapterCapabilities`.
267
271
 
272
+ ## Send error codes
273
+
274
+ A failed `SendResult` carries `error: { code, message, retryAfterMs?, platformCode? }`. `code` is a
275
+ `SendErrorCode`, or a platform-specific string an adapter has not mapped yet.
276
+
277
+ | Code | Used when |
278
+ | --- | --- |
279
+ | `empty_text` | core: the message has no text |
280
+ | `not_connected` | core: the adapter is not connected |
281
+ | `invalid_channel` | core: the channel is not valid for the adapter |
282
+ | `attachments_unsupported` | core: attachments sent to an adapter that cannot send them |
283
+ | `rate_limit` | the platform throttled the send (HTTP 429); `retryAfterMs` holds the wait |
284
+ | `permission_denied` | the credential may not post here (HTTP 403) |
285
+ | `auth_failed` | the credential was rejected (HTTP 401) |
286
+ | `timeout` | the request timed out (HTTP 408) |
287
+ | `server_error` | the platform failed (HTTP 5xx) |
288
+ | `network_error` | the request got no answer |
289
+ | `platform_error` | any other platform refusal |
290
+
291
+ `sendErrorFromHttp(status, message, { retryAfter, platformCode, now })` builds the `SendResult`
292
+ for an HTTP status; `retryAfter` is a `Retry-After` value in seconds or an HTTP date. It throws
293
+ `RangeError` when `status` is not an integer in 100..599. Adapters still return their own codes
294
+ today (`rate_limited`, `no_permission`, `<platform>_http_error`); moving them onto the shared
295
+ codes is follow-up work.
296
+
268
297
  ## Chat commands
269
298
 
270
299
  `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)`.
@@ -356,6 +385,17 @@ keeps one file per key under `dir` (mode 0600, written to a temp file and rename
356
385
  `invalid_credential_key`. `get` returns `undefined` for a missing key; any other read error throws
357
386
  code `credential_store_unreadable`. `@theokit/gateway-x` uses it to keep a rotated refresh token.
358
387
 
388
+ ## Caching an expiring access token
389
+
390
+ `createTokenCache({ fetchToken })` holds one access token. `get()` returns the cached token, or
391
+ runs `fetchToken` once and gives the same result to every concurrent caller. A token is refreshed
392
+ `marginMs` (default 60 000) before it expires; its lifetime is `expiresInS` from `fetchToken`, or
393
+ `defaultTtlS` (default 7200) when that is absent or not positive. `get({ force: true })` skips the
394
+ cache but still joins a fetch already in flight. `clear()` forgets the token, and a fetch that was
395
+ running at that moment does not store its result. A failed fetch rejects every waiting caller and
396
+ is not cached. The signal passed to `get` reaches `fetchToken` only for the caller that starts the
397
+ fetch. `now` replaces the clock in tests.
398
+
359
399
  ## Architecture (5 pieces)
360
400
 
361
401
  | Module | Responsibility |
@@ -655,3 +695,19 @@ See `.claude/knowledge-base/adrs/D170-D181-*.md` for the full design rationale.
655
695
  ## License
656
696
 
657
697
  Apache-2.0
698
+
699
+ ### `ReconnectBackoff`
700
+
701
+ Adapters that hold a long-lived socket or stream can reuse the runner's backoff:
702
+
703
+ ```ts
704
+ import { ReconnectBackoff } from "@theokit/gateway";
705
+
706
+ const backoff = new ReconnectBackoff({ initialDelayMs: 1000, maxDelayMs: 30_000 });
707
+ // on open: backoff.opened();
708
+ // on close: const delay = backoff.nextDelayMs(); // undefined once maxAttempts is spent
709
+ ```
710
+
711
+ Defaults match `ReconnectPolicy` (1 s initial, 60 s cap, factor 2). A connection open for at least
712
+ `stableAfterMs` (default 60 s) resets the delay. A negative or non-finite delay, or a `factor`
713
+ below 1, throws a `RangeError` naming the field.
package/dist/index.cjs CHANGED
@@ -380,6 +380,81 @@ var BasePlatformAdapter = class _BasePlatformAdapter {
380
380
  }
381
381
  };
382
382
 
383
+ // src/adapter/send-error.ts
384
+ function parseRetryAfter(value, now) {
385
+ if (value == null) return void 0;
386
+ const v = value.trim();
387
+ if (/^\d+$/.test(v)) return Number(v) * 1e3;
388
+ if (!/[A-Za-z]/.test(v)) return void 0;
389
+ const at = Date.parse(v);
390
+ if (Number.isNaN(at)) return void 0;
391
+ return Math.max(0, at - now);
392
+ }
393
+ var STATUS_CODES = {
394
+ 429: "rate_limit",
395
+ 401: "auth_failed",
396
+ 403: "permission_denied",
397
+ 408: "timeout"
398
+ };
399
+ function codeForStatus(status) {
400
+ return STATUS_CODES[status] ?? (status >= 500 ? "server_error" : "platform_error");
401
+ }
402
+ function sendErrorFromHttp(status, message, options) {
403
+ if (!Number.isInteger(status) || status < 100 || status > 599) {
404
+ throw new RangeError(`status must be an integer in 100..599, got ${String(status)}`);
405
+ }
406
+ const code = codeForStatus(status);
407
+ const retryAfterMs = status === 429 ? parseRetryAfter(options?.retryAfter, (options?.now ?? Date.now)()) : void 0;
408
+ return {
409
+ ok: false,
410
+ error: {
411
+ code,
412
+ message,
413
+ ...retryAfterMs !== void 0 ? { retryAfterMs } : {},
414
+ ...options?.platformCode !== void 0 ? { platformCode: options.platformCode } : {}
415
+ }
416
+ };
417
+ }
418
+
419
+ // src/auth/token-cache.ts
420
+ function createTokenCache(options) {
421
+ const marginMs = options.marginMs ?? 6e4;
422
+ const defaultTtlS = options.defaultTtlS ?? 7200;
423
+ const now = options.now ?? Date.now;
424
+ let cached;
425
+ let pending;
426
+ let generation = 0;
427
+ const refresh = (signal) => {
428
+ const started = generation;
429
+ const run = (async () => {
430
+ const fetched = await options.fetchToken(signal);
431
+ const ttl = fetched.expiresInS !== void 0 && fetched.expiresInS > 0 ? fetched.expiresInS : defaultTtlS;
432
+ if (started === generation) {
433
+ cached = { value: fetched.value, expiresAt: now() + ttl * 1e3 };
434
+ }
435
+ return fetched.value;
436
+ })();
437
+ const tracked = run.finally(() => {
438
+ if (pending === tracked) pending = void 0;
439
+ });
440
+ pending = tracked;
441
+ return tracked;
442
+ };
443
+ return {
444
+ get(opts) {
445
+ if (opts?.force !== true && cached !== void 0 && cached.expiresAt - marginMs > now()) {
446
+ return Promise.resolve(cached.value);
447
+ }
448
+ return pending ?? refresh(opts?.signal);
449
+ },
450
+ clear() {
451
+ generation += 1;
452
+ cached = void 0;
453
+ pending = void 0;
454
+ }
455
+ };
456
+ }
457
+
383
458
  // src/text/seen-ids.ts
384
459
  var DEFAULT_LIMIT = 1e3;
385
460
  var SeenIds = class {
@@ -429,7 +504,6 @@ function decodeEntities(s) {
429
504
 
430
505
  // src/adapter/weixin-base.ts
431
506
  var REQUEST_TIMEOUT_MS = 3e4;
432
- var TOKEN_MARGIN_MS = 6e4;
433
507
  var defaultFetch = async (url, init) => {
434
508
  const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
435
509
  return { status: res.status, text: () => res.text() };
@@ -444,12 +518,13 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
444
518
  cfg;
445
519
  doFetch;
446
520
  connected = false;
447
- accessToken;
521
+ tokens;
448
522
  seen = new SeenIds();
449
523
  constructor(cfg) {
450
524
  super();
451
525
  this.cfg = cfg;
452
526
  this.doFetch = cfg.fetch ?? defaultFetch;
527
+ this.tokens = createTokenCache({ fetchToken: () => this.requestToken() });
453
528
  }
454
529
  async connect() {
455
530
  if (this.connected) return true;
@@ -465,7 +540,7 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
465
540
  }
466
541
  async disconnect() {
467
542
  this.connected = false;
468
- this.accessToken = void 0;
543
+ this.tokens.clear();
469
544
  }
470
545
  /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
471
546
  async sendText(out) {
@@ -527,21 +602,19 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
527
602
  if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
528
603
  return weixinAck(outcome);
529
604
  }
530
- async token(force) {
531
- const cached = this.accessToken;
532
- if (!force && cached !== void 0 && cached.expiresAt - TOKEN_MARGIN_MS > Date.now()) {
533
- return cached.value;
534
- }
605
+ token(force) {
606
+ return this.tokens.get({ force });
607
+ }
608
+ async requestToken() {
535
609
  const body = await this.call("GET", this.tokenPath());
536
610
  if (body.errcode !== void 0 && body.errcode !== 0) {
537
611
  throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
538
612
  }
539
613
  if (!body.access_token) throw new Error("token answer has no access_token");
540
- this.accessToken = {
614
+ return {
541
615
  value: body.access_token,
542
- expiresAt: Date.now() + (body.expires_in ?? 7200) * 1e3
616
+ ...body.expires_in === void 0 ? {} : { expiresInS: body.expires_in }
543
617
  };
544
- return body.access_token;
545
618
  }
546
619
  async call(method, path, payload) {
547
620
  const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
@@ -1250,6 +1323,56 @@ var HookExecutor = class {
1250
1323
  }
1251
1324
  };
1252
1325
 
1326
+ // src/runner/reconnect-backoff.ts
1327
+ function checkNonNegativeFinite(name, value) {
1328
+ if (!Number.isFinite(value) || value < 0) {
1329
+ throw new RangeError(`${name} must be a finite number >= 0, got ${value}`);
1330
+ }
1331
+ }
1332
+ var ReconnectBackoff = class {
1333
+ initialDelayMs;
1334
+ maxDelayMs;
1335
+ factor;
1336
+ maxAttempts;
1337
+ stableAfterMs;
1338
+ now;
1339
+ attempts = 0;
1340
+ openedAt;
1341
+ constructor(options = {}) {
1342
+ this.initialDelayMs = options.initialDelayMs ?? 1e3;
1343
+ this.maxDelayMs = options.maxDelayMs ?? 6e4;
1344
+ this.factor = options.factor ?? 2;
1345
+ this.maxAttempts = options.maxAttempts;
1346
+ this.stableAfterMs = options.stableAfterMs ?? 6e4;
1347
+ this.now = options.now ?? Date.now;
1348
+ checkNonNegativeFinite("initialDelayMs", this.initialDelayMs);
1349
+ checkNonNegativeFinite("maxDelayMs", this.maxDelayMs);
1350
+ if (!(this.factor >= 1) || !Number.isFinite(this.factor)) {
1351
+ throw new RangeError(`factor must be a finite number >= 1, got ${this.factor}`);
1352
+ }
1353
+ }
1354
+ /** Call when the connection opens. */
1355
+ opened() {
1356
+ this.openedAt = this.now();
1357
+ }
1358
+ /** Delay before the next attempt; `undefined` once `maxAttempts` is spent. Resets first if the last connection was stable. */
1359
+ nextDelayMs() {
1360
+ if (this.openedAt !== void 0) {
1361
+ if (this.now() - this.openedAt >= this.stableAfterMs) this.attempts = 0;
1362
+ this.openedAt = void 0;
1363
+ }
1364
+ if (this.maxAttempts !== void 0 && this.attempts >= this.maxAttempts) return void 0;
1365
+ const delay = Math.min(this.initialDelayMs * this.factor ** this.attempts, this.maxDelayMs);
1366
+ this.attempts += 1;
1367
+ return delay;
1368
+ }
1369
+ /** Back to the initial delay. */
1370
+ reset() {
1371
+ this.attempts = 0;
1372
+ this.openedAt = void 0;
1373
+ }
1374
+ };
1375
+
1253
1376
  // src/runner/gateway-runner.ts
1254
1377
  var DEFAULT_DRAIN_MS = 1e4;
1255
1378
  var TYPING_RENEW_MS = 4e3;
@@ -1401,27 +1524,28 @@ var GatewayRunner = class {
1401
1524
  connected: result.connected.map((a) => a.platform),
1402
1525
  failed: result.failed
1403
1526
  };
1404
- for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);
1527
+ for (const adapter of result.retryable) {
1528
+ const policy = this.opts.reconnect;
1529
+ if (policy === void 0) break;
1530
+ this.scheduleReconnect(adapter, 1, new ReconnectBackoff(policy));
1531
+ }
1405
1532
  return this.startResult;
1406
1533
  }
1407
1534
  /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
1408
- scheduleReconnect(adapter, attempt) {
1535
+ scheduleReconnect(adapter, attempt, backoff) {
1409
1536
  const policy = this.opts.reconnect;
1410
1537
  if (policy === void 0 || this.stopped) return;
1411
- if (policy.maxAttempts !== void 0 && attempt > policy.maxAttempts) {
1538
+ const delay = backoff.nextDelayMs();
1539
+ if (delay === void 0) {
1412
1540
  process.stderr.write(
1413
1541
  `[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
1414
1542
  `
1415
1543
  );
1416
1544
  return;
1417
1545
  }
1418
- const delay = Math.min(
1419
- (policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
1420
- policy.maxDelayMs ?? 6e4
1421
- );
1422
1546
  const timer = setTimeout(() => {
1423
1547
  this.retryTimers.delete(timer);
1424
- void this.reconnectOnce(adapter, attempt);
1548
+ void this.reconnectOnce(adapter, attempt, backoff);
1425
1549
  }, delay);
1426
1550
  timer.unref();
1427
1551
  this.retryTimers.add(timer);
@@ -1431,7 +1555,7 @@ var GatewayRunner = class {
1431
1555
  );
1432
1556
  this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
1433
1557
  }
1434
- async reconnectOnce(adapter, attempt) {
1558
+ async reconnectOnce(adapter, attempt, backoff) {
1435
1559
  if (this.stopped) return;
1436
1560
  try {
1437
1561
  if (await adapter.connect()) {
@@ -1477,7 +1601,7 @@ var GatewayRunner = class {
1477
1601
  `
1478
1602
  );
1479
1603
  }
1480
- this.scheduleReconnect(adapter, attempt + 1);
1604
+ this.scheduleReconnect(adapter, attempt + 1, backoff);
1481
1605
  }
1482
1606
  /**
1483
1607
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
@@ -2147,30 +2271,60 @@ function lineEndFrom(text, cut, bound) {
2147
2271
  while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
2148
2272
  return at;
2149
2273
  }
2150
- function rowSafeCut2(text, partStart, cut, partLimit) {
2274
+ function advance(text, from, count, codepoint) {
2275
+ if (!codepoint) return Math.min(from + count, text.length);
2276
+ let at = from;
2277
+ for (let left = count; left > 0 && at < text.length; left -= 1) {
2278
+ at += (text.codePointAt(at) ?? 0) > 65535 ? 2 : 1;
2279
+ }
2280
+ return at;
2281
+ }
2282
+ function rowSafeCut2(text, partStart, cut, partLimit, codepoint) {
2151
2283
  const lineStart = lineStartBefore(text, cut, partStart);
2152
2284
  if (lineStart <= partStart || lineStart === cut) return cut;
2153
2285
  if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
2154
- const lineEnd = lineEndFrom(text, cut, lineStart + partLimit);
2155
- return lineEnd - lineStart <= partLimit ? lineStart : cut;
2286
+ const bound = advance(text, lineStart, partLimit, codepoint);
2287
+ return lineEndFrom(text, cut, bound) <= bound ? lineStart : cut;
2156
2288
  }
2157
- function graphemeCut(segments, start, partLimit) {
2158
- const cut = start + partLimit;
2159
- const segment = segments.containing(cut);
2160
- if (segment === void 0 || segment.index >= cut) return cut;
2289
+ function graphemeCut(segments, start, limitCut) {
2290
+ const segment = segments.containing(limitCut);
2291
+ if (segment === void 0 || segment.index >= limitCut) return limitCut;
2161
2292
  return segment.index > start ? segment.index : segment.index + segment.segment.length;
2162
2293
  }
2163
- function splitKeepingRows(text, partLimit) {
2294
+ function readUnit(partLimit, options) {
2295
+ const unit = options.unit ?? "utf16";
2296
+ if (unit !== "utf16" && unit !== "codepoint") {
2297
+ throw new RangeError(
2298
+ `splitKeepingRows: unit must be "utf16" or "codepoint", got ${String(unit)}`
2299
+ );
2300
+ }
2301
+ if (unit === "codepoint" && !(Number.isInteger(partLimit) && partLimit > 0)) {
2302
+ throw new RangeError(
2303
+ `splitKeepingRows: partLimit must be a positive integer, got ${partLimit}`
2304
+ );
2305
+ }
2306
+ return unit === "codepoint";
2307
+ }
2308
+ function splitKeepingRows(text, partLimit, options = {}) {
2309
+ const codepoint = readUnit(partLimit, options);
2164
2310
  const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
2165
2311
  const parts = [];
2166
2312
  let start = 0;
2167
- while (text.length - start > partLimit) {
2168
- const cut = rowSafeCut2(text, start, graphemeCut(segments, start, partLimit), partLimit);
2313
+ let limitCut = advance(text, start, partLimit, codepoint);
2314
+ while (limitCut < text.length) {
2315
+ const grapheme = graphemeCut(segments, start, limitCut);
2316
+ if (codepoint && grapheme > limitCut) {
2317
+ throw new RangeError(
2318
+ `splitKeepingRows: a grapheme at offset ${start} is longer than ${partLimit} code points`
2319
+ );
2320
+ }
2321
+ const cut = rowSafeCut2(text, start, grapheme, partLimit, codepoint);
2169
2322
  if (cut <= start) {
2170
2323
  throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
2171
2324
  }
2172
2325
  parts.push(text.slice(start, cut));
2173
2326
  start = cut;
2327
+ limitCut = advance(text, start, partLimit, codepoint);
2174
2328
  }
2175
2329
  if (start < text.length) parts.push(text.slice(start));
2176
2330
  return parts;
@@ -2441,6 +2595,7 @@ exports.GatewayConfigurationError = GatewayConfigurationError;
2441
2595
  exports.GatewayLifecycleError = GatewayLifecycleError;
2442
2596
  exports.GatewayRunner = GatewayRunner;
2443
2597
  exports.HookExecutor = HookExecutor;
2598
+ exports.ReconnectBackoff = ReconnectBackoff;
2444
2599
  exports.SeenIds = SeenIds;
2445
2600
  exports.SessionRouter = SessionRouter;
2446
2601
  exports.WeixinAdapterBase = WeixinAdapterBase;
@@ -2456,6 +2611,7 @@ exports.createAgentBindings = createAgentBindings;
2456
2611
  exports.createChannels = createChannels;
2457
2612
  exports.createFileCredentialStore = createFileCredentialStore;
2458
2613
  exports.createFilePairingStore = createFilePairingStore;
2614
+ exports.createTokenCache = createTokenCache;
2459
2615
  exports.createWebhookHandler = createWebhookHandler;
2460
2616
  exports.defaultStrategy = defaultStrategy;
2461
2617
  exports.helpText = helpText;
@@ -2471,6 +2627,7 @@ exports.redactSecrets = redactSecrets;
2471
2627
  exports.scanFences = scanFences;
2472
2628
  exports.scopedStrategy = scopedStrategy;
2473
2629
  exports.selectVariant = selectVariant;
2630
+ exports.sendErrorFromHttp = sendErrorFromHttp;
2474
2631
  exports.senderKey = senderKey;
2475
2632
  exports.splitKeepingRows = splitKeepingRows;
2476
2633
  exports.statusForDeliver = statusForDeliver;