@theokit/gateway 0.18.0 → 0.20.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.js CHANGED
@@ -1,4 +1,7 @@
1
1
  import { Security } from '@theokit/sdk';
2
+ import { randomInt, randomUUID } from 'crypto';
3
+ import { readFileSync, mkdirSync, writeFileSync, renameSync } from 'fs';
4
+ import { join } from 'path';
2
5
 
3
6
  // src/text/fence.ts
4
7
  var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
@@ -214,7 +217,7 @@ function channelRendering(platform) {
214
217
  }
215
218
 
216
219
  // src/adapter/base.ts
217
- var BasePlatformAdapter = class {
220
+ var BasePlatformAdapter = class _BasePlatformAdapter {
218
221
  /**
219
222
  * Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
220
223
  *
@@ -275,17 +278,17 @@ var BasePlatformAdapter = class {
275
278
  * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
276
279
  * Returns the refusal, or `undefined` when the message may be sent.
277
280
  */
278
- refuseUnsendable(out, check) {
281
+ refuseUnsendable(out, check2) {
279
282
  const refuse = (code, message) => ({
280
283
  ok: false,
281
284
  error: { code, message }
282
285
  });
283
286
  if (out.text.length === 0) return refuse("empty_text", "outbound text is empty");
284
- if (!check.connected) {
285
- return refuse("not_connected", `${check.className}.connect() has not succeeded`);
287
+ if (!check2.connected) {
288
+ return refuse("not_connected", `${check2.className}.connect() has not succeeded`);
286
289
  }
287
- if (check.channel !== void 0 && !check.channel.valid(out.channel.id)) {
288
- return refuse("invalid_channel", check.channel.message);
290
+ if (check2.channel !== void 0 && !check2.channel.valid(out.channel.id)) {
291
+ return refuse("invalid_channel", check2.channel.message);
289
292
  }
290
293
  return void 0;
291
294
  }
@@ -305,6 +308,27 @@ var BasePlatformAdapter = class {
305
308
  * `boolean` so that an adapter that sends images can override it with `true`.
306
309
  */
307
310
  supportsAttachments = false;
311
+ /**
312
+ * The attachment kinds {@link sendMessage} can send. `undefined` means "not declared": the
313
+ * `capabilities` getter then reports `["image"]` when `supportsAttachments` is `true`, else `[]`.
314
+ */
315
+ attachmentKinds = void 0;
316
+ /**
317
+ * What this adapter can do, for an app that renders differently per channel.
318
+ *
319
+ * Derived from the members above and from which lifecycle methods the subclass overrides; an
320
+ * adapter overrides the getter only for what derivation cannot know. Read it at call time.
321
+ */
322
+ get capabilities() {
323
+ const proto = _BasePlatformAdapter.prototype;
324
+ return {
325
+ edit: this.supportsEdit,
326
+ attachments: this.attachmentKinds ?? (this.supportsAttachments ? ["image"] : []),
327
+ typing: this.startTyping !== proto.startTyping,
328
+ reactions: this.react !== proto.react,
329
+ threads: false
330
+ };
331
+ }
308
332
  /**
309
333
  * Replace the text of a message this adapter sent, keeping its id.
310
334
  *
@@ -531,6 +555,11 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
531
555
  }
532
556
  };
533
557
 
558
+ // src/channel/channel-descriptor.ts
559
+ function isAuthenticatedSender(descriptor) {
560
+ return descriptor.senderIdentity === "authenticated";
561
+ }
562
+
534
563
  // src/errors/config-error.ts
535
564
  var GatewayConfigurationError = class extends Error {
536
565
  name = "GatewayConfigurationError";
@@ -547,6 +576,54 @@ var GatewayConfigurationError = class extends Error {
547
576
  }
548
577
  };
549
578
 
579
+ // src/channel/config-from-env.ts
580
+ function readValue(env, name) {
581
+ const value = env[name]?.trim();
582
+ return value ? value : void 0;
583
+ }
584
+ function configFromEnv(descriptor, env, prefix = "") {
585
+ const config = {};
586
+ const missing = [];
587
+ const secrets = [];
588
+ for (const field of descriptor.config) {
589
+ if (field.env === void 0) continue;
590
+ const name = prefix + field.env;
591
+ const value = readValue(env, name);
592
+ if (value === void 0) {
593
+ if (field.required) missing.push(name);
594
+ continue;
595
+ }
596
+ config[field.key] = value;
597
+ recordSecret(field, value, secrets);
598
+ }
599
+ return { config, missing, secrets };
600
+ }
601
+ function recordSecret(field, value, secrets) {
602
+ if (field.secret && !secrets.includes(value)) secrets.push(value);
603
+ }
604
+ function mismatch(parent, variant, name) {
605
+ throw new GatewayConfigurationError("gateway", {
606
+ code: "platform_mismatch",
607
+ message: `channel ${parent.platform}: variant "${name}" reports platform ${variant.platform}`
608
+ });
609
+ }
610
+ function unknownVariant(descriptor, name) {
611
+ const valid = Object.keys(descriptor.variants ?? {});
612
+ const given = name === void 0 ? "(none given)" : `"${name}"`;
613
+ throw new GatewayConfigurationError("gateway", {
614
+ code: "unknown_channel_variant",
615
+ message: `channel ${descriptor.platform}: unknown variant ${given}; valid variants: ${valid.length > 0 ? valid.join(", ") : "(none)"}`
616
+ });
617
+ }
618
+ function selectVariant(descriptor, name) {
619
+ const variants = descriptor.variants ?? {};
620
+ if (name === void 0 && Object.keys(variants).length === 0) return descriptor;
621
+ const variant = name !== void 0 && Object.hasOwn(variants, name) ? variants[name] : void 0;
622
+ if (variant === void 0) return unknownVariant(descriptor, name);
623
+ if (variant.platform !== descriptor.platform) mismatch(descriptor, variant, name ?? "");
624
+ return variant;
625
+ }
626
+
550
627
  // src/channel/create-channels.ts
551
628
  function isAbsent(value) {
552
629
  return value === void 0 || value === null || value === "";
@@ -747,6 +824,262 @@ function maskShapes(text) {
747
824
  function redactSecrets(value) {
748
825
  return Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
749
826
  }
827
+ function maskSecrets(text, secrets) {
828
+ const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
829
+ let out = text;
830
+ for (const secret of ordered) out = out.split(secret).join("[redacted]");
831
+ return out;
832
+ }
833
+ function senderKey(platform, senderId) {
834
+ return `${platform}:${platform === "email" ? senderId.toLowerCase() : senderId}`;
835
+ }
836
+ var TTL_MS = 36e5;
837
+ var FILE = "pairing.json";
838
+ function unreadable() {
839
+ return new GatewayConfigurationError("gateway", {
840
+ code: "pairing_store_unreadable",
841
+ message: "gateway: pairing_store_unreadable"
842
+ });
843
+ }
844
+ function load(path) {
845
+ let raw;
846
+ try {
847
+ raw = readFileSync(path, "utf8");
848
+ } catch (e) {
849
+ if (e.code === "ENOENT") return /* @__PURE__ */ new Set();
850
+ throw unreadable();
851
+ }
852
+ let parsed;
853
+ try {
854
+ parsed = JSON.parse(raw);
855
+ } catch {
856
+ throw unreadable();
857
+ }
858
+ const list = parsed?.paired;
859
+ if (!Array.isArray(list) || !list.every((x) => typeof x === "string")) throw unreadable();
860
+ return new Set(list);
861
+ }
862
+ function createFilePairingStore(options) {
863
+ const clock = options.clock ?? Date.now;
864
+ const random = options.random ?? randomInt;
865
+ const path = join(options.dir, FILE);
866
+ const paired = load(path);
867
+ const pending = /* @__PURE__ */ new Map();
868
+ let chain = Promise.resolve();
869
+ const prune = () => {
870
+ const now = clock();
871
+ for (const [code, p] of pending) if (p.expires <= now) pending.delete(code);
872
+ };
873
+ function persist(next) {
874
+ mkdirSync(options.dir, { recursive: true });
875
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
876
+ writeFileSync(tmp, JSON.stringify({ paired: [...next].sort((a, b) => a.localeCompare(b)) }), {
877
+ mode: 384,
878
+ flag: "wx"
879
+ });
880
+ renameSync(tmp, path);
881
+ }
882
+ return {
883
+ issue(platform, senderId) {
884
+ prune();
885
+ for (const [code2, p] of pending) {
886
+ if (senderKey(p.platform, p.senderId) === senderKey(platform, senderId)) return code2;
887
+ }
888
+ let code;
889
+ do {
890
+ code = String(random(1e5, 1e6));
891
+ } while (pending.has(code));
892
+ pending.set(code, { platform, senderId, expires: clock() + TTL_MS });
893
+ return code;
894
+ },
895
+ approve(code) {
896
+ const run = async () => {
897
+ prune();
898
+ const p = pending.get(code);
899
+ if (!p) return { ok: false, reason: "unknown_or_expired" };
900
+ const next = new Set(paired);
901
+ next.add(senderKey(p.platform, p.senderId));
902
+ try {
903
+ persist(next);
904
+ } catch {
905
+ return { ok: false, reason: "write_failed" };
906
+ }
907
+ paired.add(senderKey(p.platform, p.senderId));
908
+ pending.delete(code);
909
+ return { ok: true, platform: p.platform, senderId: p.senderId };
910
+ };
911
+ const result = chain.then(run, run);
912
+ chain = result.catch(() => void 0);
913
+ return result;
914
+ },
915
+ isPaired(platform, senderId) {
916
+ return paired.has(senderKey(platform, senderId));
917
+ }
918
+ };
919
+ }
920
+
921
+ // src/hooks/access-policy.ts
922
+ var SILENT = { block: true };
923
+ var DEFAULT_REFUSAL = "Sorry, you are not authorized to use this assistant.";
924
+ function normalize(key) {
925
+ const i = key.indexOf(":");
926
+ return i < 0 ? key : senderKey(key.slice(0, i), key.slice(i + 1));
927
+ }
928
+ function check(keys, isAuth) {
929
+ const out = /* @__PURE__ */ new Set();
930
+ for (const key of keys) {
931
+ const i = key.indexOf(":");
932
+ const platform = i < 0 ? key : key.slice(0, i);
933
+ if (!isAuth(platform)) {
934
+ throw new GatewayConfigurationError("gateway", {
935
+ code: "unauthenticated_owner",
936
+ message: `gateway: unauthenticated_owner: platform ${platform} does not authenticate the sender`,
937
+ detail: platform
938
+ });
939
+ }
940
+ out.add(normalize(key));
941
+ }
942
+ return out;
943
+ }
944
+ function createAccessPolicyHook(options) {
945
+ if (options.dm === "pairing" && !options.pairing) {
946
+ throw new GatewayConfigurationError("gateway", {
947
+ code: "pairing_store_required",
948
+ message: "gateway: pairing_store_required"
949
+ });
950
+ }
951
+ const owners = check(options.owners, options.isAuthenticated);
952
+ const allowed = check(options.allowed ?? /* @__PURE__ */ new Set(), options.isAuthenticated);
953
+ const clock = options.clock ?? Date.now;
954
+ const interval = options.refusalIntervalMs ?? 36e5;
955
+ const write = options.write ?? ((line) => process.stderr.write(`${line}
956
+ `));
957
+ const refusal = options.refusalText ?? DEFAULT_REFUSAL;
958
+ const store = options.pairing;
959
+ const refused2 = /* @__PURE__ */ new Map();
960
+ const mayRefuse = (key) => {
961
+ const now = clock();
962
+ for (const [k, t] of refused2) if (now - t >= interval) refused2.delete(k);
963
+ if (refused2.has(key)) return false;
964
+ refused2.set(key, now);
965
+ return true;
966
+ };
967
+ const pairingReply = (event) => {
968
+ const code = store.issue(event.platform, event.sender.id);
969
+ return {
970
+ block: true,
971
+ message: `Your pairing code is ${code}. Ask the owner to send /approve ${code}.`
972
+ };
973
+ };
974
+ const groupDecision = () => options.groups === "open" ? void 0 : SILENT;
975
+ const stranger = (event, key) => {
976
+ if (event.channel.type !== "dm") return groupDecision();
977
+ if (options.dm === "open") return void 0;
978
+ if (options.dm === "disabled" || !mayRefuse(key)) return SILENT;
979
+ if (options.dm === "allowlist") return { block: true, message: refusal };
980
+ return pairingReply(event);
981
+ };
982
+ const ownerMessage = async (text) => {
983
+ const m = /^\/approve\s+(\d{6})\s*$/.exec(text.trim());
984
+ if (!m?.[1]) return void 0;
985
+ if (!store) return { block: true, message: "Pairing is not enabled." };
986
+ const r = await store.approve(m[1]);
987
+ if (r.ok) return { block: true, message: "Paired." };
988
+ return {
989
+ block: true,
990
+ message: r.reason === "write_failed" ? "Saving the pairing failed. Check the storage and send the code again." : "Unknown or expired code."
991
+ };
992
+ };
993
+ const isPaired = (event) => store?.isPaired(event.platform, event.sender.id) === true;
994
+ const decide = async (event) => {
995
+ if (options.passThrough?.(event)) return void 0;
996
+ if (!options.isAuthenticated(event.platform)) return SILENT;
997
+ const key = senderKey(event.platform, event.sender.id);
998
+ if (owners.has(key)) return ownerMessage(event.text);
999
+ if (allowed.has(key) || isPaired(event)) return void 0;
1000
+ return stranger(event, key);
1001
+ };
1002
+ return {
1003
+ name: "access-policy",
1004
+ async pre_inbound({ event }) {
1005
+ try {
1006
+ return await decide(event);
1007
+ } catch (e) {
1008
+ try {
1009
+ write(`access-policy: hook failed: ${redactSecrets(e)}`);
1010
+ } catch {
1011
+ }
1012
+ return SILENT;
1013
+ }
1014
+ }
1015
+ };
1016
+ }
1017
+
1018
+ // src/hooks/chat-command.ts
1019
+ var LEADING_MENTION = /^(?:<@[^>]+>|@\S+)\s+/;
1020
+ var DEFAULT_PREFIXES = ["/"];
1021
+ function matchPrefix(text, prefixes) {
1022
+ let best;
1023
+ for (const p of prefixes) {
1024
+ if (p.length > 0 && text.startsWith(p) && (best === void 0 || p.length > best.length)) {
1025
+ best = p;
1026
+ }
1027
+ }
1028
+ return best;
1029
+ }
1030
+ function parseChatCommand(text, options) {
1031
+ const body = text.trim().replace(LEADING_MENTION, "");
1032
+ const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);
1033
+ if (prefix === void 0) return void 0;
1034
+ const rest = body.slice(prefix.length);
1035
+ const m = /^([^\s@]+)(?:@\S+)?(?:\s+([\s\S]*))?$/.exec(rest);
1036
+ if (!m?.[1]) return void 0;
1037
+ return { name: m[1].toLowerCase(), arg: (m[2] ?? "").trim() };
1038
+ }
1039
+ function usageOf(c) {
1040
+ return c.usage ?? `/${c.name}`;
1041
+ }
1042
+ function helpText(commands) {
1043
+ return commands.map((c) => `${usageOf(c)} - ${c.description}`).join("\n");
1044
+ }
1045
+ function assertUnique(names) {
1046
+ const seen = /* @__PURE__ */ new Set();
1047
+ for (const raw of names) {
1048
+ const name = raw.toLowerCase();
1049
+ if (seen.has(name)) {
1050
+ throw new GatewayConfigurationError("gateway", {
1051
+ code: "duplicate_command",
1052
+ message: `gateway: duplicate_command: ${raw}`,
1053
+ detail: raw
1054
+ });
1055
+ }
1056
+ seen.add(name);
1057
+ }
1058
+ }
1059
+ function badArity(c, arg) {
1060
+ const mode = c.arg ?? "optional";
1061
+ return mode === "none" && arg !== "" || mode === "required" && arg === "";
1062
+ }
1063
+ function commandHook(commands, options) {
1064
+ const helpName = options?.helpCommand === void 0 ? "help" : options.helpCommand;
1065
+ assertUnique([...commands.map((c) => c.name), ...helpName === false ? [] : [helpName]]);
1066
+ const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));
1067
+ const help = helpText(commands);
1068
+ return {
1069
+ name: options?.name ?? "chat-commands",
1070
+ async pre_inbound({ event }) {
1071
+ const parsed = parseChatCommand(event.text);
1072
+ if (!parsed) return void 0;
1073
+ if (helpName !== false && parsed.name === helpName.toLowerCase()) {
1074
+ return { block: true, message: help };
1075
+ }
1076
+ const command = byName.get(parsed.name);
1077
+ if (!command) return void 0;
1078
+ if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };
1079
+ return command.run(event, parsed.arg);
1080
+ }
1081
+ };
1082
+ }
750
1083
 
751
1084
  // src/hooks/executor.ts
752
1085
  var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
@@ -860,10 +1193,10 @@ function keepTyping(adapter, channelId) {
860
1193
  };
861
1194
  }
862
1195
  var DEFAULT_COMMAND_PREFIXES = ["/"];
863
- function connectFailureReason(outcome) {
1196
+ function connectFailureReason(outcome, redact) {
864
1197
  if (outcome.status === "fulfilled") return "connect returned false";
865
1198
  const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
866
- return redactSecrets(message);
1199
+ return redact(message);
867
1200
  }
868
1201
  function isTerminalConnectError(err) {
869
1202
  if (typeof err !== "object" || err === null) return false;
@@ -877,7 +1210,7 @@ function isTerminalConnectError(err) {
877
1210
  message
878
1211
  );
879
1212
  }
880
- async function releaseAdapters(adapters, during) {
1213
+ async function releaseAdapters(adapters, during, redact = redactSecrets) {
881
1214
  await Promise.all(
882
1215
  adapters.map(async (a) => {
883
1216
  try {
@@ -885,7 +1218,7 @@ async function releaseAdapters(adapters, during) {
885
1218
  } catch (err) {
886
1219
  const message = err instanceof Error ? err.message : String(err);
887
1220
  process.stderr.write(
888
- `[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redactSecrets(message)}
1221
+ `[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}
889
1222
  `
890
1223
  );
891
1224
  }
@@ -896,6 +1229,8 @@ var GatewayRunner = class {
896
1229
  constructor(opts) {
897
1230
  this.opts = opts;
898
1231
  this.hookExecutor = new HookExecutor(opts.hooks ?? []);
1232
+ const secrets = opts.secrets ?? [];
1233
+ this.redact = (text) => redactSecrets(maskSecrets(text, secrets));
899
1234
  }
900
1235
  opts;
901
1236
  hookExecutor;
@@ -908,6 +1243,23 @@ var GatewayRunner = class {
908
1243
  startInFlight;
909
1244
  stopped = false;
910
1245
  retryTimers = /* @__PURE__ */ new Set();
1246
+ connectedPlatforms = /* @__PURE__ */ new Set();
1247
+ redact;
1248
+ /** The registered adapter for a platform, connected or not. */
1249
+ adapter(platform) {
1250
+ return this.opts.adapters.find((a) => a.platform === platform);
1251
+ }
1252
+ /** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
1253
+ get connected() {
1254
+ return this.connectedPlatforms;
1255
+ }
1256
+ emitState(platform, state, reason) {
1257
+ if ((this.opts.connectFailure ?? "rollback") !== "isolate") return;
1258
+ try {
1259
+ this.opts.onAdapterState?.(platform, state, reason);
1260
+ } catch {
1261
+ }
1262
+ }
911
1263
  /**
912
1264
  * Register a slash command. Match rule (EC-A): text === "/" + name
913
1265
  * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
@@ -962,11 +1314,17 @@ var GatewayRunner = class {
962
1314
  async runStart() {
963
1315
  const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
964
1316
  if (this.stopped) {
965
- await releaseAdapters(result.connected, "releasing a start that stop() overtook");
1317
+ await releaseAdapters(
1318
+ result.connected,
1319
+ "releasing a start that stop() overtook",
1320
+ this.redact
1321
+ );
1322
+ this.connectedPlatforms.clear();
966
1323
  this.startResult = { connected: [], failed: result.failed };
967
1324
  return this.startResult;
968
1325
  }
969
1326
  this.wireInbound(result.connected);
1327
+ for (const a of result.connected) this.connectedPlatforms.add(a.platform);
970
1328
  this.startResult = {
971
1329
  connected: result.connected.map((a) => a.platform),
972
1330
  failed: result.failed
@@ -999,16 +1357,23 @@ var GatewayRunner = class {
999
1357
  `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
1000
1358
  `
1001
1359
  );
1360
+ this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
1002
1361
  }
1003
1362
  async reconnectOnce(adapter, attempt) {
1004
1363
  if (this.stopped) return;
1005
1364
  try {
1006
1365
  if (await adapter.connect()) {
1007
1366
  if (this.stopped) {
1008
- await releaseAdapters([adapter], "releasing a reconnect that stop() overtook");
1367
+ await releaseAdapters(
1368
+ [adapter],
1369
+ "releasing a reconnect that stop() overtook",
1370
+ this.redact
1371
+ );
1009
1372
  return;
1010
1373
  }
1011
1374
  this.wireInbound([adapter]);
1375
+ this.connectedPlatforms.add(adapter.platform);
1376
+ this.emitState(adapter.platform, "connected");
1012
1377
  const prev = this.startResult ?? { connected: [], failed: [] };
1013
1378
  this.startResult = {
1014
1379
  connected: [...prev.connected, adapter.platform],
@@ -1026,8 +1391,9 @@ var GatewayRunner = class {
1026
1391
  );
1027
1392
  return;
1028
1393
  } catch (err) {
1029
- const reason = connectFailureReason({ status: "rejected", reason: err });
1394
+ const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
1030
1395
  if (isTerminalConnectError(err)) {
1396
+ this.emitState(adapter.platform, "failed", reason);
1031
1397
  process.stderr.write(
1032
1398
  `[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
1033
1399
  `
@@ -1067,7 +1433,7 @@ var GatewayRunner = class {
1067
1433
  );
1068
1434
  if (failures.length > 0) {
1069
1435
  const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
1070
- await releaseAdapters(connected, "rolling back a failed start");
1436
+ await releaseAdapters(connected, "rolling back a failed start", this.redact);
1071
1437
  throw failures[0];
1072
1438
  }
1073
1439
  return { connected: [...adapters], failed: [], retryable: [] };
@@ -1079,22 +1445,55 @@ var GatewayRunner = class {
1079
1445
  */
1080
1446
  async connectIsolated() {
1081
1447
  const adapters = this.opts.adapters;
1082
- const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
1448
+ const results = await Promise.all(adapters.map((a) => this.connectOne(a)));
1083
1449
  const connected = [];
1084
1450
  const failed = [];
1085
1451
  const retryable = [];
1086
- settled.forEach((outcome, i) => {
1087
- const adapter = adapters[i];
1088
- if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
1089
- else {
1090
- failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
1091
- if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
1092
- retryable.push(adapter);
1093
- }
1094
- }
1095
- });
1452
+ for (const r of results) {
1453
+ if (r.failure === void 0) connected.push(r.adapter);
1454
+ else failed.push(r.failure);
1455
+ if (r.retry) retryable.push(r.adapter);
1456
+ }
1096
1457
  return { connected, failed, retryable };
1097
1458
  }
1459
+ /** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */
1460
+ async connectOne(adapter) {
1461
+ const attempt = Promise.allSettled([(async () => adapter.connect())()]).then(
1462
+ ([r]) => r
1463
+ );
1464
+ const ms = this.opts.connectTimeoutMs;
1465
+ if (ms === void 0) return this.classify(adapter, await attempt);
1466
+ let timer;
1467
+ const first = await Promise.race([
1468
+ attempt,
1469
+ new Promise((resolve) => {
1470
+ timer = setTimeout(() => resolve("timeout"), ms);
1471
+ })
1472
+ ]);
1473
+ if (timer !== void 0) clearTimeout(timer);
1474
+ if (first !== "timeout") return this.classify(adapter, first);
1475
+ void attempt.then((late) => this.releaseLateConnect(adapter, late));
1476
+ const reason = `connect timed out after ${ms}ms`;
1477
+ this.emitState(adapter.platform, "timed_out", reason);
1478
+ return { adapter, failure: { platform: adapter.platform, reason }, retry: true };
1479
+ }
1480
+ /** A connect that finished after the runner gave up on it must not stay connected unseen. */
1481
+ releaseLateConnect(adapter, late) {
1482
+ if (late.status !== "fulfilled" || !late.value) return;
1483
+ if (this.connectedPlatforms.has(adapter.platform)) return;
1484
+ void releaseAdapters([adapter], "releasing a connect that timed out", this.redact);
1485
+ }
1486
+ classify(adapter, outcome) {
1487
+ if (outcome.status === "fulfilled" && outcome.value) {
1488
+ this.connectedPlatforms.add(adapter.platform);
1489
+ this.emitState(adapter.platform, "connected");
1490
+ return { adapter, failure: void 0, retry: false };
1491
+ }
1492
+ const reason = connectFailureReason(outcome, this.redact);
1493
+ this.emitState(adapter.platform, "failed", reason);
1494
+ const retry = outcome.status === "rejected" && !isTerminalConnectError(outcome.reason);
1495
+ return { adapter, failure: { platform: adapter.platform, reason }, retry };
1496
+ }
1098
1497
  wireInbound(adapters) {
1099
1498
  for (const a of adapters) {
1100
1499
  const unsub = a.onInbound(async (event) => {
@@ -1126,6 +1525,7 @@ var GatewayRunner = class {
1126
1525
  this.unsubs.length = 0;
1127
1526
  for (const t of this.retryTimers) clearTimeout(t);
1128
1527
  this.retryTimers.clear();
1528
+ this.connectedPlatforms.clear();
1129
1529
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
1130
1530
  if (this.inflight.size > 0) {
1131
1531
  let timer;
@@ -1140,7 +1540,7 @@ var GatewayRunner = class {
1140
1540
  if (timer !== void 0) clearTimeout(timer);
1141
1541
  }
1142
1542
  }
1143
- await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
1543
+ await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner", this.redact);
1144
1544
  }
1145
1545
  /**
1146
1546
  * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
@@ -1160,7 +1560,7 @@ var GatewayRunner = class {
1160
1560
  await ctx.reply(decision.message).catch(async (err) => {
1161
1561
  const error = err;
1162
1562
  await this.hookExecutor.fireOnError({ event, error });
1163
- process.stderr.write(`[gateway] auto-reply error: ${redactSecrets(error.message)}
1563
+ process.stderr.write(`[gateway] auto-reply error: ${this.redact(error.message)}
1164
1564
  `);
1165
1565
  });
1166
1566
  }
@@ -1174,7 +1574,7 @@ var GatewayRunner = class {
1174
1574
  await handler(event, ctx);
1175
1575
  } catch (err) {
1176
1576
  await this.hookExecutor.fireOnError({ event, error: err });
1177
- process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
1577
+ process.stderr.write(`[gateway] handler error: ${this.redact(err.message)}
1178
1578
  `);
1179
1579
  } finally {
1180
1580
  await stopTyping();
@@ -1326,6 +1726,67 @@ var SessionRouter = class {
1326
1726
  }
1327
1727
  };
1328
1728
 
1729
+ // src/session/bindings.ts
1730
+ function unknownAgent(agent) {
1731
+ return new GatewayConfigurationError("gateway", {
1732
+ code: "unknown_agent",
1733
+ message: `gateway: unknown_agent: ${agent}`,
1734
+ detail: agent
1735
+ });
1736
+ }
1737
+ function createAgentBindings(options) {
1738
+ const known = new Set(options.agents);
1739
+ if (!known.has(options.defaultAgent)) throw unknownAgent(options.defaultAgent);
1740
+ for (const rule of options.rules) {
1741
+ if (!known.has(rule.agent)) throw unknownAgent(rule.agent);
1742
+ if (rule.platform === void 0 && rule.account === void 0 && rule.peer === void 0) {
1743
+ throw new GatewayConfigurationError("gateway", {
1744
+ code: "empty_binding_rule",
1745
+ message: `gateway: empty_binding_rule: ${rule.agent}`,
1746
+ detail: rule.agent
1747
+ });
1748
+ }
1749
+ }
1750
+ const rules = [...options.rules];
1751
+ const { accountOf } = options;
1752
+ return {
1753
+ agentFor(event) {
1754
+ const ctx = {
1755
+ platform: event.platform,
1756
+ account: accountOf?.(event),
1757
+ peer: event.channel.type === "dm" ? event.sender.id : event.channel.id
1758
+ };
1759
+ let best = options.defaultAgent;
1760
+ let bestScore = 0;
1761
+ for (const rule of rules) {
1762
+ const score = scoreRule(rule, ctx);
1763
+ if (score > bestScore) {
1764
+ best = rule.agent;
1765
+ bestScore = score;
1766
+ }
1767
+ }
1768
+ return best;
1769
+ }
1770
+ };
1771
+ }
1772
+ function scoreRule(rule, ctx) {
1773
+ const fields = [
1774
+ [rule.platform, ctx.platform, 1],
1775
+ [rule.account, ctx.account, 2],
1776
+ [rule.peer, ctx.peer, 4]
1777
+ ];
1778
+ let score = 0;
1779
+ for (const [want, got, weight] of fields) {
1780
+ if (want === void 0) continue;
1781
+ if (want !== got) return 0;
1782
+ score += weight;
1783
+ }
1784
+ return score;
1785
+ }
1786
+ function bindingStrategy(bindings, inner) {
1787
+ return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
1788
+ }
1789
+
1329
1790
  // src/text/chunk.ts
1330
1791
  function searchBoundary(remaining, window, boundaries) {
1331
1792
  let cut = window;
@@ -1483,9 +1944,9 @@ function chunkFencedByGrapheme(text, partLimit, regions) {
1483
1944
  let prefix = "";
1484
1945
  while (prefix.length + (text.length - pos) > partLimit) {
1485
1946
  const room = partLimit - prefix.length;
1486
- const plain = boundaryUpTo(pos, pos + room);
1487
- const region = fenceAt(regions, plain);
1488
- const next = region === void 0 ? { cut: plain, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo);
1947
+ const plain2 = boundaryUpTo(pos, pos + room);
1948
+ const region = fenceAt(regions, plain2);
1949
+ const next = region === void 0 ? { cut: plain2, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo);
1489
1950
  parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
1490
1951
  pos = next.cut;
1491
1952
  prefix = next.reopen;
@@ -1493,9 +1954,9 @@ function chunkFencedByGrapheme(text, partLimit, regions) {
1493
1954
  parts.push(prefix + text.slice(pos));
1494
1955
  return parts;
1495
1956
  }
1496
- function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
1497
- const none = { cut: plain, suffix: "", reopen: "" };
1498
- if (plain <= region.openerEnd) {
1957
+ function fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo) {
1958
+ const none = { cut: plain2, suffix: "", reopen: "" };
1959
+ if (plain2 <= region.openerEnd) {
1499
1960
  return region.start > pos ? { ...none, cut: region.start } : none;
1500
1961
  }
1501
1962
  const eol = openerEol(text, region);
@@ -1560,10 +2021,25 @@ function splitKeepingRows(text, partLimit) {
1560
2021
  return parts;
1561
2022
  }
1562
2023
 
2024
+ // src/webhook/deliver-status.ts
2025
+ function statusForDeliver(outcomes) {
2026
+ let status = 200;
2027
+ for (const outcome of outcomes) {
2028
+ if (outcome === "handler_threw") {
2029
+ status = 500;
2030
+ } else if (outcome === "no_handler") {
2031
+ if (status === 200) status = 503;
2032
+ } else if (outcome !== "ok") {
2033
+ throw new Error(`unknown deliver outcome: ${outcome}`);
2034
+ }
2035
+ }
2036
+ return status;
2037
+ }
2038
+
1563
2039
  // src/webhook/express-server.ts
1564
- async function loadPeer(load, onMissing) {
2040
+ async function loadPeer(load2, onMissing) {
1565
2041
  try {
1566
- const mod = await load();
2042
+ const mod = await load2();
1567
2043
  return mod.default ?? mod;
1568
2044
  } catch {
1569
2045
  onMissing();
@@ -1670,6 +2146,126 @@ function listenerLifecycle(opts) {
1670
2146
  };
1671
2147
  }
1672
2148
 
1673
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect, withMediaUnderstanding };
2149
+ // src/webhook/fetch-handler.ts
2150
+ var TOO_LARGE = /* @__PURE__ */ Symbol("too-large");
2151
+ function defaultPlatformFor(url) {
2152
+ const marker = "/webhooks/";
2153
+ const at = url.pathname.lastIndexOf(marker);
2154
+ if (at < 0) return void 0;
2155
+ const rest = url.pathname.slice(at + marker.length).replace(/\/+$/, "");
2156
+ const last = rest.split("/").pop();
2157
+ return last ? last : void 0;
2158
+ }
2159
+ function plain(status, extra) {
2160
+ return new Response(null, { status, headers: extra });
2161
+ }
2162
+ function tooLarge() {
2163
+ return plain(413, { connection: "close" });
2164
+ }
2165
+ async function readCapped(request, max) {
2166
+ const declared = request.headers.get("content-length");
2167
+ if (declared !== null && Number(declared) > max) return TOO_LARGE;
2168
+ if (request.body === null) return "";
2169
+ const reader = request.body.getReader();
2170
+ const chunks = [];
2171
+ let total = 0;
2172
+ for (; ; ) {
2173
+ const { done, value } = await reader.read();
2174
+ if (done) break;
2175
+ total += value.byteLength;
2176
+ if (total > max) {
2177
+ await reader.cancel().catch(() => void 0);
2178
+ return TOO_LARGE;
2179
+ }
2180
+ chunks.push(value);
2181
+ }
2182
+ const joined = new Uint8Array(total);
2183
+ let offset = 0;
2184
+ for (const chunk of chunks) {
2185
+ joined.set(chunk, offset);
2186
+ offset += chunk.byteLength;
2187
+ }
2188
+ return new TextDecoder().decode(joined);
2189
+ }
2190
+ function answerResponse(answer) {
2191
+ const headers = {};
2192
+ if (answer.contentType !== void 0) headers["content-type"] = answer.contentType;
2193
+ return new Response(answer.body ?? null, { status: answer.status, headers });
2194
+ }
2195
+ async function runDefault(webhook, adapter, request) {
2196
+ if (!webhook.verify(adapter, request)) return plain(401);
2197
+ let payload;
2198
+ try {
2199
+ payload = JSON.parse(request.rawBody);
2200
+ } catch {
2201
+ return plain(400);
2202
+ }
2203
+ const result = await webhook.ingest(adapter, payload);
2204
+ if (result === "delivered") return plain(200);
2205
+ return plain(result === "no_handler" ? 503 : 400);
2206
+ }
2207
+ function headersOf(request) {
2208
+ const out = {};
2209
+ request.headers.forEach((value, key) => {
2210
+ out[key] = value;
2211
+ });
2212
+ return out;
2213
+ }
2214
+ async function readBody(request, max) {
2215
+ let body;
2216
+ try {
2217
+ body = await readCapped(request, max);
2218
+ } catch {
2219
+ return plain(400);
2220
+ }
2221
+ return body === TOO_LARGE ? tooLarge() : body;
2222
+ }
2223
+ function createWebhookHandler(options) {
2224
+ const max = options.maxBodyBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;
2225
+ const platformFor = options.platformFor ?? defaultPlatformFor;
2226
+ const routes = /* @__PURE__ */ new Map();
2227
+ for (const channel of options.channels) {
2228
+ if (channel.descriptor.transport === "webhook")
2229
+ routes.set(channel.descriptor.platform, channel);
2230
+ }
2231
+ const route = (url) => {
2232
+ const platform = platformFor(url);
2233
+ return platform === void 0 ? void 0 : routes.get(platform);
2234
+ };
2235
+ return async (request) => {
2236
+ const channel = route(new URL(request.url));
2237
+ if (channel === void 0) return plain(404);
2238
+ const platform = channel.descriptor.platform;
2239
+ if (!options.isStarted(platform)) return plain(503);
2240
+ const webhook = channel.descriptor.webhook;
2241
+ const refused2 = refuseMethod(webhook, request);
2242
+ if (refused2 !== void 0) return refused2;
2243
+ const rawBody = await readBody(request, max);
2244
+ if (typeof rawBody !== "string") return rawBody;
2245
+ try {
2246
+ return await dispatch(webhook, channel.adapter, {
2247
+ rawBody,
2248
+ headers: headersOf(request),
2249
+ method: request.method.toUpperCase(),
2250
+ url: request.url
2251
+ });
2252
+ } catch (error) {
2253
+ options.onError?.(platform, error);
2254
+ return plain(500);
2255
+ }
2256
+ };
2257
+ }
2258
+ function refuseMethod(webhook, request) {
2259
+ const methods = webhook.methods ?? ["POST"];
2260
+ const method = request.method.toUpperCase();
2261
+ if (methods.some((m) => m.toUpperCase() === method)) return void 0;
2262
+ return plain(405, { allow: methods.join(", ") });
2263
+ }
2264
+ async function dispatch(webhook, adapter, request) {
2265
+ if (webhook.handle !== void 0) return answerResponse(await webhook.handle(adapter, request));
2266
+ return runDefault(webhook, adapter, request);
2267
+ }
2268
+
2269
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
1674
2270
  //# sourceMappingURL=index.js.map
1675
2271
  //# sourceMappingURL=index.js.map