@mastra/telegram 0.1.1 → 0.1.2-alpha.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.cjs CHANGED
@@ -35,6 +35,8 @@ let crypto$1 = require("crypto");
35
35
  crypto$1 = __toESM(crypto$1, 1);
36
36
  let _mastra_core_channels = require("@mastra/core/channels");
37
37
  let _mastra_core_storage = require("@mastra/core/storage");
38
+ let async_hooks = require("async_hooks");
39
+ let net = require("net");
38
40
  let process$1 = require("process");
39
41
  let path = require("path");
40
42
  let url = require("url");
@@ -1261,7 +1263,7 @@ function normalizeIdentifier(value) {
1261
1263
  return value.replace(/[\t\n\r ]+/g, " ").replace(/^ | $/g, "").toLowerCase().toUpperCase();
1262
1264
  }
1263
1265
  //#endregion
1264
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm-footnote/2.1.0/e493d9f707c226a77e7187530768c6c6adc2d70dffcdba398990fbbd4395d66a/node_modules/mdast-util-gfm-footnote/lib/index.js
1266
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm-footnote/2.1.0/68eeeb793de2ef8d34172d3acb11cdd3c9293a685777d51d6f14ad62dcffa59d/node_modules/mdast-util-gfm-footnote/lib/index.js
1265
1267
  /**
1266
1268
  * @import {
1267
1269
  * CompileContext,
@@ -1453,7 +1455,7 @@ function mapAll(line, index, blank) {
1453
1455
  return (blank ? "" : " ") + line;
1454
1456
  }
1455
1457
  //#endregion
1456
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm-strikethrough/2.0.0/0fd415d2e420ac1f9e91cfb910ae470bddaf2b43532c23847b411aa73f343fe8/node_modules/mdast-util-gfm-strikethrough/lib/index.js
1458
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm-strikethrough/2.0.0/42bd5cb50e2a33d09abc031c2ec984952cc5f00979d5ec3b801581c7c0a973c9/node_modules/mdast-util-gfm-strikethrough/lib/index.js
1457
1459
  /**
1458
1460
  * @typedef {import('mdast').Delete} Delete
1459
1461
  *
@@ -1888,7 +1890,7 @@ function toAlignment(value) {
1888
1890
  * @property {Handlers} [handlers]
1889
1891
  * Handlers to use.
1890
1892
  */
1891
- const own$4 = {}.hasOwnProperty;
1893
+ const own$5 = {}.hasOwnProperty;
1892
1894
  /**
1893
1895
  * Handle values based on a field.
1894
1896
  *
@@ -1935,9 +1937,9 @@ function zwitch(key, options) {
1935
1937
  /** @type {Handler|undefined} */
1936
1938
  let fn = one.invalid;
1937
1939
  const handlers = one.handlers;
1938
- if (value && own$4.call(value, key)) {
1940
+ if (value && own$5.call(value, key)) {
1939
1941
  const id = String(value[key]);
1940
- fn = own$4.call(handlers, id) ? handlers[id] : one.unknown;
1942
+ fn = own$5.call(handlers, id) ? handlers[id] : one.unknown;
1941
1943
  }
1942
1944
  if (fn) return fn.call(this, value, ...parameters);
1943
1945
  }
@@ -1951,7 +1953,7 @@ function zwitch(key, options) {
1951
1953
  /**
1952
1954
  * @import {Options, State} from './types.js'
1953
1955
  */
1954
- const own$3 = {}.hasOwnProperty;
1956
+ const own$4 = {}.hasOwnProperty;
1955
1957
  /**
1956
1958
  * @param {State} base
1957
1959
  * @param {Options} extension
@@ -1962,7 +1964,7 @@ function configure$1(base, extension) {
1962
1964
  /** @type {keyof Options} */
1963
1965
  let key;
1964
1966
  if (extension.extensions) while (++index < extension.extensions.length) configure$1(base, extension.extensions[index]);
1965
- for (key in extension) if (own$3.call(extension, key)) switch (key) {
1967
+ for (key in extension) if (own$4.call(extension, key)) switch (key) {
1966
1968
  case "extensions": break;
1967
1969
  /* c8 ignore next 4 */
1968
1970
  case "unsafe":
@@ -5826,7 +5828,7 @@ const characterEntities = {
5826
5828
  };
5827
5829
  //#endregion
5828
5830
  //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/decode-named-character-reference/1.2.0/c3c8b6b44380b90de2b1e74a9c8d70081179a19eb6aa1e49a980be4156815e4c/node_modules/decode-named-character-reference/index.js
5829
- const own$2 = {}.hasOwnProperty;
5831
+ const own$3 = {}.hasOwnProperty;
5830
5832
  /**
5831
5833
  * Decode a single character reference (without the `&` or `;`).
5832
5834
  * You probably only need this when you’re building parsers yourself that follow
@@ -5838,8 +5840,8 @@ const own$2 = {}.hasOwnProperty;
5838
5840
  * @returns {string|false}
5839
5841
  * Decoded reference.
5840
5842
  */
5841
- function decodeNamedCharacterReference(value) {
5842
- return own$2.call(characterEntities, value) ? characterEntities[value] : false;
5843
+ function decodeNamedCharacterReference$1(value) {
5844
+ return own$3.call(characterEntities, value) ? characterEntities[value] : false;
5843
5845
  }
5844
5846
  //#endregion
5845
5847
  //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-util-decode-numeric-character-reference/2.0.2/2f367c0e1b15bf77ce33033a7bf92715227cb1dd04f3a9a248f48df6e3b18ef5/node_modules/micromark-util-decode-numeric-character-reference/index.js
@@ -5897,7 +5899,7 @@ function decode($0, $1, $2) {
5897
5899
  const hex = head === 120 || head === 88;
5898
5900
  return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10);
5899
5901
  }
5900
- return decodeNamedCharacterReference($2) || $0;
5902
+ return decodeNamedCharacterReference$1($2) || $0;
5901
5903
  }
5902
5904
  //#endregion
5903
5905
  //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-to-markdown/2.1.2/9050d17c2147fa6bd62628009c209542fd8b3285ffadb1b88a7a42d72163972a/node_modules/mdast-util-to-markdown/lib/util/association.js
@@ -6422,7 +6424,7 @@ function safeBound(value, config) {
6422
6424
  return safe(this, value, config);
6423
6425
  }
6424
6426
  //#endregion
6425
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm-table/2.0.0/401af9b79a2db1ec6989e65a1b4ead90b8fca62f10cf03d8770b5d2dc542dc30/node_modules/mdast-util-gfm-table/lib/index.js
6427
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm-table/2.0.0/dde372edf2c0870786ccaba0cd5d8bdb3fd9ad61cdc4889950537a5ebb06df7a/node_modules/mdast-util-gfm-table/lib/index.js
6426
6428
  /**
6427
6429
  * @typedef {import('mdast').InlineCode} InlineCode
6428
6430
  * @typedef {import('mdast').Table} Table
@@ -6686,7 +6688,7 @@ function gfmTableToMarkdown(options) {
6686
6688
  }
6687
6689
  }
6688
6690
  //#endregion
6689
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm-task-list-item/2.0.0/3a968586084a9e91700e984ffac9d656bc5eae9c08f8f86f85633218a4cba040/node_modules/mdast-util-gfm-task-list-item/lib/index.js
6691
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm-task-list-item/2.0.0/4098f8d02f5c6467bf48430325ef1fbedb616e982049d629025bddeba6948428/node_modules/mdast-util-gfm-task-list-item/lib/index.js
6690
6692
  /**
6691
6693
  * @typedef {import('mdast').ListItem} ListItem
6692
6694
  * @typedef {import('mdast').Paragraph} Paragraph
@@ -6796,7 +6798,7 @@ function listItemWithTaskListItem(node, parent, state, info) {
6796
6798
  }
6797
6799
  }
6798
6800
  //#endregion
6799
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm/3.1.0/dcd345adc6acbb2aa9623c2174d1497e9806e436b684f4a77ec05d743fe3824c/node_modules/mdast-util-gfm/lib/index.js
6801
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-gfm/3.1.0/a78c6d3b0e1c33e9ccf77e1477770df305f4a6714cf5ad42162866777ce44793/node_modules/mdast-util-gfm/lib/index.js
6800
6802
  /**
6801
6803
  * @import {Extension as FromMarkdownExtension} from 'mdast-util-from-markdown'
6802
6804
  * @import {Options} from 'mdast-util-gfm'
@@ -7711,7 +7713,7 @@ function resolveAll(constructs, events, context) {
7711
7713
  return events;
7712
7714
  }
7713
7715
  //#endregion
7714
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/attention.js
7716
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/attention.js
7715
7717
  /**
7716
7718
  * @import {
7717
7719
  * Code,
@@ -7931,7 +7933,7 @@ function movePoint(point, offset) {
7931
7933
  point._bufferIndex += offset;
7932
7934
  }
7933
7935
  //#endregion
7934
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/autolink.js
7936
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/autolink.js
7935
7937
  /**
7936
7938
  * @import {
7937
7939
  * Construct,
@@ -8201,7 +8203,7 @@ function factorySpace(effects, ok, type, max) {
8201
8203
  }
8202
8204
  }
8203
8205
  //#endregion
8204
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/blank-line.js
8206
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/blank-line.js
8205
8207
  /**
8206
8208
  * @import {
8207
8209
  * Construct,
@@ -8258,7 +8260,7 @@ function tokenizeBlankLine(effects, ok, nok) {
8258
8260
  }
8259
8261
  }
8260
8262
  //#endregion
8261
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/block-quote.js
8263
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/block-quote.js
8262
8264
  /**
8263
8265
  * @import {
8264
8266
  * Construct,
@@ -8385,7 +8387,7 @@ function exit(effects) {
8385
8387
  effects.exit("blockQuote");
8386
8388
  }
8387
8389
  //#endregion
8388
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/character-escape.js
8390
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/character-escape.js
8389
8391
  /**
8390
8392
  * @import {
8391
8393
  * Construct,
@@ -8445,7 +8447,24 @@ function tokenizeCharacterEscape(effects, ok, nok) {
8445
8447
  }
8446
8448
  }
8447
8449
  //#endregion
8448
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/character-reference.js
8450
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/decode-named-character-reference/1.3.0/960e57696ff78351993465a43535e8192e8f43f733eefeee641c0d88f2c1f516/node_modules/decode-named-character-reference/index.js
8451
+ const own$2 = {}.hasOwnProperty;
8452
+ /**
8453
+ * Decode a single character reference (without the `&` or `;`).
8454
+ * You probably only need this when you’re building parsers yourself that follow
8455
+ * different rules compared to HTML.
8456
+ * This is optimized to be tiny in browsers.
8457
+ *
8458
+ * @param {string} value
8459
+ * `notin` (named), `#123` (deci), `#x123` (hexa).
8460
+ * @returns {string|false}
8461
+ * Decoded reference.
8462
+ */
8463
+ function decodeNamedCharacterReference(value) {
8464
+ return own$2.call(characterEntities, value) ? characterEntities[value] : false;
8465
+ }
8466
+ //#endregion
8467
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/character-reference.js
8449
8468
  /**
8450
8469
  * @import {
8451
8470
  * Code,
@@ -8583,7 +8602,7 @@ function tokenizeCharacterReference(effects, ok, nok) {
8583
8602
  }
8584
8603
  }
8585
8604
  //#endregion
8586
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/code-fenced.js
8605
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/code-fenced.js
8587
8606
  /**
8588
8607
  * @import {
8589
8608
  * Code,
@@ -8998,7 +9017,7 @@ function tokenizeNonLazyContinuation(effects, ok, nok) {
8998
9017
  }
8999
9018
  }
9000
9019
  //#endregion
9001
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/code-indented.js
9020
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/code-indented.js
9002
9021
  /**
9003
9022
  * @import {
9004
9023
  * Construct,
@@ -9142,7 +9161,7 @@ function tokenizeFurtherStart(effects, ok, nok) {
9142
9161
  }
9143
9162
  }
9144
9163
  //#endregion
9145
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/code-text.js
9164
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/code-text.js
9146
9165
  /**
9147
9166
  * @import {
9148
9167
  * Construct,
@@ -9712,7 +9731,7 @@ function subcontent(events, eventIndex) {
9712
9731
  return gaps;
9713
9732
  }
9714
9733
  //#endregion
9715
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/content.js
9734
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/content.js
9716
9735
  /**
9717
9736
  * @import {
9718
9737
  * Construct,
@@ -10346,7 +10365,7 @@ function factoryWhitespace(effects, ok) {
10346
10365
  }
10347
10366
  }
10348
10367
  //#endregion
10349
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/definition.js
10368
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/definition.js
10350
10369
  /**
10351
10370
  * @import {
10352
10371
  * Construct,
@@ -10561,7 +10580,7 @@ function tokenizeTitleBefore(effects, ok, nok) {
10561
10580
  }
10562
10581
  }
10563
10582
  //#endregion
10564
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/hard-break-escape.js
10583
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/hard-break-escape.js
10565
10584
  /**
10566
10585
  * @import {
10567
10586
  * Construct,
@@ -10618,7 +10637,7 @@ function tokenizeHardBreakEscape(effects, ok, nok) {
10618
10637
  }
10619
10638
  }
10620
10639
  //#endregion
10621
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/heading-atx.js
10640
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/heading-atx.js
10622
10641
  /**
10623
10642
  * @import {
10624
10643
  * Construct,
@@ -10902,7 +10921,7 @@ const htmlRawNames = [
10902
10921
  "textarea"
10903
10922
  ];
10904
10923
  //#endregion
10905
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/html-flow.js
10924
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/html-flow.js
10906
10925
  /**
10907
10926
  * @import {
10908
10927
  * Code,
@@ -11675,7 +11694,7 @@ function tokenizeBlankLineBefore(effects, ok, nok) {
11675
11694
  }
11676
11695
  }
11677
11696
  //#endregion
11678
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/html-text.js
11697
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/html-text.js
11679
11698
  /**
11680
11699
  * @import {
11681
11700
  * Code,
@@ -12289,7 +12308,7 @@ function tokenizeHtmlText(effects, ok, nok) {
12289
12308
  }
12290
12309
  }
12291
12310
  //#endregion
12292
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/label-end.js
12311
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/label-end.js
12293
12312
  /**
12294
12313
  * @import {
12295
12314
  * Construct,
@@ -12759,7 +12778,7 @@ function tokenizeReferenceCollapsed(effects, ok, nok) {
12759
12778
  }
12760
12779
  }
12761
12780
  //#endregion
12762
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/label-start-image.js
12781
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/label-start-image.js
12763
12782
  /**
12764
12783
  * @import {
12765
12784
  * Construct,
@@ -12852,7 +12871,7 @@ function tokenizeLabelStartImage(effects, ok, nok) {
12852
12871
  }
12853
12872
  }
12854
12873
  //#endregion
12855
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/label-start-link.js
12874
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/label-start-link.js
12856
12875
  /**
12857
12876
  * @import {
12858
12877
  * Construct,
@@ -12900,7 +12919,7 @@ function tokenizeLabelStartLink(effects, ok, nok) {
12900
12919
  }
12901
12920
  }
12902
12921
  //#endregion
12903
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/line-ending.js
12922
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/line-ending.js
12904
12923
  /**
12905
12924
  * @import {
12906
12925
  * Construct,
@@ -12930,7 +12949,7 @@ function tokenizeLineEnding(effects, ok) {
12930
12949
  }
12931
12950
  }
12932
12951
  //#endregion
12933
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/thematic-break.js
12952
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/thematic-break.js
12934
12953
  /**
12935
12954
  * @import {
12936
12955
  * Code,
@@ -13025,7 +13044,7 @@ function tokenizeThematicBreak(effects, ok, nok) {
13025
13044
  }
13026
13045
  }
13027
13046
  //#endregion
13028
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/list.js
13047
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/list.js
13029
13048
  /**
13030
13049
  * @import {
13031
13050
  * Code,
@@ -13197,7 +13216,7 @@ function tokenizeListItemPrefixWhitespace(effects, ok, nok) {
13197
13216
  }
13198
13217
  }
13199
13218
  //#endregion
13200
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/dcdb0686fac337bf5636324004d358db888546b854169076c618d42670023f43/node_modules/micromark-core-commonmark/lib/setext-underline.js
13219
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-core-commonmark/2.0.3/a1b4dd720a345ea7669bd6eac1b98d97da85d9a8fd797edbe457df3db914e918/node_modules/micromark-core-commonmark/lib/setext-underline.js
13201
13220
  /**
13202
13221
  * @import {
13203
13222
  * Code,
@@ -13349,7 +13368,7 @@ function tokenizeSetextUnderline(effects, ok, nok) {
13349
13368
  }
13350
13369
  }
13351
13370
  //#endregion
13352
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-extension-gfm-footnote/2.1.0/6ac37bcc584b607a827c5e4296d9fcd7110c4e9c8c4f2d853e1908c9ffabc604/node_modules/micromark-extension-gfm-footnote/lib/syntax.js
13371
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-extension-gfm-footnote/2.1.0/b44c8e84d93fa798639536629ef427f51491f682b55d6753baacd913323b1d0c/node_modules/micromark-extension-gfm-footnote/lib/syntax.js
13353
13372
  /**
13354
13373
  * @import {Event, Exiter, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'
13355
13374
  */
@@ -14852,7 +14871,7 @@ function spaceThenNonSpace(effects, ok, nok) {
14852
14871
  }
14853
14872
  }
14854
14873
  //#endregion
14855
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-extension-gfm/3.0.0/0ad77c32bf2a883bc2f3cb891cac5d885e2c8505125b83914ea2c24f0a6cfe8c/node_modules/micromark-extension-gfm/index.js
14874
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark-extension-gfm/3.0.0/ecc0d38f5a0d39e6498936ab24fa7414f69a55a425511808f8b7c5359e6d2fdf/node_modules/micromark-extension-gfm/index.js
14856
14875
  /**
14857
14876
  * @typedef {import('micromark-extension-gfm-footnote').HtmlOptions} HtmlOptions
14858
14877
  * @typedef {import('micromark-extension-gfm-strikethrough').Options} Options
@@ -14880,7 +14899,7 @@ function gfm(options) {
14880
14899
  ]);
14881
14900
  }
14882
14901
  //#endregion
14883
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/remark-gfm/4.0.1/83cb88922990d12cc39a15a67825508792058e959424279628c26ffe4352ef8e/node_modules/remark-gfm/lib/index.js
14902
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/remark-gfm/4.0.1/b78fb8f7ef0f9504ebe3b95c68ee6b8ad5b7ee2f13ecfabbc9471f3883f8bb78/node_modules/remark-gfm/lib/index.js
14884
14903
  /**
14885
14904
  * @import {Root} from 'mdast'
14886
14905
  * @import {Options} from 'remark-gfm'
@@ -14911,7 +14930,7 @@ function remarkGfm(options) {
14911
14930
  toMarkdownExtensions.push(gfmToMarkdown(settings));
14912
14931
  }
14913
14932
  //#endregion
14914
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/initialize/content.js
14933
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/initialize/content.js
14915
14934
  /**
14916
14935
  * @import {
14917
14936
  * InitialConstruct,
@@ -14978,7 +14997,7 @@ function initializeContent(effects) {
14978
14997
  }
14979
14998
  }
14980
14999
  //#endregion
14981
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/initialize/document.js
15000
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/initialize/document.js
14982
15001
  /**
14983
15002
  * @import {
14984
15003
  * Construct,
@@ -15194,7 +15213,7 @@ function tokenizeContainer(effects, ok, nok) {
15194
15213
  return factorySpace(effects, effects.attempt(this.parser.constructs.document, ok, nok), "linePrefix", this.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4);
15195
15214
  }
15196
15215
  //#endregion
15197
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/initialize/flow.js
15216
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/initialize/flow.js
15198
15217
  /**
15199
15218
  * @import {
15200
15219
  * InitialConstruct,
@@ -15241,7 +15260,7 @@ function initializeFlow(effects) {
15241
15260
  }
15242
15261
  }
15243
15262
  //#endregion
15244
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/initialize/text.js
15263
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/initialize/text.js
15245
15264
  /**
15246
15265
  * @import {
15247
15266
  * Code,
@@ -15418,7 +15437,7 @@ function resolveAllLineSuffixes(events, context) {
15418
15437
  return events;
15419
15438
  }
15420
15439
  //#endregion
15421
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/constructs.js
15440
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/constructs.js
15422
15441
  /**
15423
15442
  * @import {Extension} from 'micromark-util-types'
15424
15443
  */
@@ -15496,7 +15515,7 @@ const attentionMarkers = { null: [42, 95] };
15496
15515
  /** @satisfies {Extension['disable']} */
15497
15516
  const disable = { null: [] };
15498
15517
  //#endregion
15499
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/create-tokenizer.js
15518
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/create-tokenizer.js
15500
15519
  /**
15501
15520
  * @import {
15502
15521
  * Chunk,
@@ -15965,7 +15984,7 @@ function serializeChunks(chunks, expandTabs) {
15965
15984
  return result.join("");
15966
15985
  }
15967
15986
  //#endregion
15968
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/parse.js
15987
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/parse.js
15969
15988
  /**
15970
15989
  * @import {
15971
15990
  * Create,
@@ -16009,7 +16028,7 @@ function parse(options) {
16009
16028
  }
16010
16029
  }
16011
16030
  //#endregion
16012
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/postprocess.js
16031
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/postprocess.js
16013
16032
  /**
16014
16033
  * @import {Event} from 'micromark-util-types'
16015
16034
  */
@@ -16024,7 +16043,7 @@ function postprocess(events) {
16024
16043
  return events;
16025
16044
  }
16026
16045
  //#endregion
16027
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/62ecbab6da239b033cb77c5157892bbb0d0eff40aef8f45371c11fcfa885b421/node_modules/micromark/lib/preprocess.js
16046
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromark/4.0.2/9275d6a1a760cec51ecaaa7d5ee482e3ab77e24a003ac30930c6eb50ded89fa2/node_modules/micromark/lib/preprocess.js
16028
16047
  /**
16029
16048
  * @import {Chunk, Code, Encoding, Value} from 'micromark-util-types'
16030
16049
  */
@@ -16189,7 +16208,7 @@ function index(value) {
16189
16208
  return value && typeof value === "number" ? value : 1;
16190
16209
  }
16191
16210
  //#endregion
16192
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-from-markdown/2.0.2/f173b7d7b6de9746817fbaaf06cc33e0ca1af0fc172210b51f7847594e4a4c6b/node_modules/mdast-util-from-markdown/lib/index.js
16211
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/mdast-util-from-markdown/2.0.2/f18d81ec2d1ccd3dbbd131d3f6ba55e726972116e4556e347e8be5b627ce9c62/node_modules/mdast-util-from-markdown/lib/index.js
16193
16212
  /**
16194
16213
  * @import {
16195
16214
  * Break,
@@ -16927,7 +16946,7 @@ function compiler(options) {
16927
16946
  if (type) {
16928
16947
  value = decodeNumericCharacterReference(data, type === "characterReferenceMarkerNumeric" ? 10 : 16);
16929
16948
  this.data.characterReferenceType = void 0;
16930
- } else value = decodeNamedCharacterReference(data);
16949
+ } else value = decodeNamedCharacterReference$1(data);
16931
16950
  const tail = this.stack[this.stack.length - 1];
16932
16951
  tail.value += value;
16933
16952
  }
@@ -17155,7 +17174,7 @@ function defaultOnError(left, right) {
17155
17174
  }) + ") is still open");
17156
17175
  }
17157
17176
  //#endregion
17158
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/remark-parse/11.0.0/7c93265e8376539e3e6627cff9daaea59aa9771a15e6cfc16e02419e35ba268e/node_modules/remark-parse/lib/index.js
17177
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/remark-parse/11.0.0/fd2874496ab6c1161cac79ae31cae4491e11dfa8a500a0fd1db6a60934d58df8/node_modules/remark-parse/lib/index.js
17159
17178
  /**
17160
17179
  * @typedef {import('mdast').Root} Root
17161
17180
  * @typedef {import('mdast-util-from-markdown').Options} FromMarkdownOptions
@@ -19356,7 +19375,7 @@ function isUint8Array(value) {
19356
19375
  return Boolean(value && typeof value === "object" && "byteLength" in value && "byteOffset" in value);
19357
19376
  }
19358
19377
  //#endregion
19359
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/chat/4.34.0/71296aa7b14ecc59d6853560292cb7a7c425fe59b90a86826e0d7f4d0fdbdaba/node_modules/chat/dist/chunk-TLXOQBA2.js
19378
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/chat/4.40.0/cb3a31b4f44de113e1ec4eb2f27ce29a2c95f7dfe7c4e921ae20223eef9ddd4e/node_modules/chat/dist/chunk-VB76CUI4.js
19360
19379
  function isListNode(node) {
19361
19380
  return node.type === "list";
19362
19381
  }
@@ -19419,20 +19438,21 @@ function nodeValue(node) {
19419
19438
  if ("alt" in node && typeof node.alt === "string") return node.alt;
19420
19439
  return null;
19421
19440
  }
19422
- function childPlainText(node, separator) {
19441
+ function childPlainText(node, separator, keepEmpty = false) {
19423
19442
  if (!("children" in node && Array.isArray(node.children))) return "";
19424
- return node.children.map((child) => plainTextNode(child)).filter((text2) => text2.length > 0).join(separator);
19443
+ const texts = node.children.map((child) => plainTextNode(child));
19444
+ return (keepEmpty ? texts : texts.filter((text2) => text2.length > 0)).join(separator);
19425
19445
  }
19426
19446
  function plainTextNode(node) {
19427
19447
  const value = nodeValue(node);
19428
19448
  if (value !== null) return value;
19429
19449
  switch (node.type) {
19430
19450
  case "root": return childPlainText(node, "\n\n");
19431
- case "list":
19432
- case "table": return childPlainText(node, "\n");
19451
+ case "list": return childPlainText(node, "\n");
19452
+ case "table": return node.children.map((child) => plainTextNode(child)).filter((row) => row.trim().length > 0).join("\n");
19433
19453
  case "listItem":
19434
19454
  case "blockquote": return childPlainText(node, "\n");
19435
- case "tableRow": return childPlainText(node, " ");
19455
+ case "tableRow": return childPlainText(node, " ", true);
19436
19456
  case "break": return "\n";
19437
19457
  case "thematicBreak": return "";
19438
19458
  case "tableCell": return childPlainText(node, "");
@@ -20256,7 +20276,7 @@ var vn = (n, r) => {
20256
20276
  };
20257
20277
  var $e = vn;
20258
20278
  //#endregion
20259
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/chat/4.34.0/71296aa7b14ecc59d6853560292cb7a7c425fe59b90a86826e0d7f4d0fdbdaba/node_modules/chat/dist/index.js
20279
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/chat/4.40.0/cb3a31b4f44de113e1ec4eb2f27ce29a2c95f7dfe7c4e921ae20223eef9ddd4e/node_modules/chat/dist/chunk-BKACWYIW.js
20260
20280
  var adapterMap = /* @__PURE__ */ new WeakMap();
20261
20281
  var Message = class _Message {
20262
20282
  /** Unique message ID */
@@ -20279,6 +20299,8 @@ var Message = class _Message {
20279
20299
  metadata;
20280
20300
  /** Attachments */
20281
20301
  attachments;
20302
+ /** Message this message replies to */
20303
+ replyTo;
20282
20304
  /**
20283
20305
  * Whether the bot is @-mentioned in this message.
20284
20306
  *
@@ -20328,6 +20350,7 @@ var Message = class _Message {
20328
20350
  this.author = data.author;
20329
20351
  this.metadata = data.metadata;
20330
20352
  this.attachments = data.attachments;
20353
+ this.replyTo = data.replyTo;
20331
20354
  this.isMention = data.isMention;
20332
20355
  this.links = data.links ?? [];
20333
20356
  }
@@ -20350,8 +20373,10 @@ var Message = class _Message {
20350
20373
  userId: this.author.userId,
20351
20374
  userName: this.author.userName,
20352
20375
  fullName: this.author.fullName,
20376
+ ...this.author.email === void 0 ? {} : { email: this.author.email },
20353
20377
  isBot: this.author.isBot,
20354
- isMe: this.author.isMe
20378
+ isMe: this.author.isMe,
20379
+ isSystem: this.author.isSystem
20355
20380
  },
20356
20381
  metadata: {
20357
20382
  dateSent: this.metadata.dateSent.toISOString(),
@@ -20368,13 +20393,14 @@ var Message = class _Message {
20368
20393
  height: att.height,
20369
20394
  fetchMetadata: att.fetchMetadata
20370
20395
  })),
20396
+ replyTo: this.replyTo?.toJSON(),
20371
20397
  isMention: this.isMention,
20372
- links: this.links.length > 0 ? this.links.map((link2) => ({
20373
- url: link2.url,
20374
- title: link2.title,
20375
- description: link2.description,
20376
- imageUrl: link2.imageUrl,
20377
- siteName: link2.siteName
20398
+ links: this.links.length > 0 ? this.links.map((link) => ({
20399
+ url: link.url,
20400
+ title: link.title,
20401
+ description: link.description,
20402
+ imageUrl: link.imageUrl,
20403
+ siteName: link.siteName
20378
20404
  })) : void 0
20379
20405
  };
20380
20406
  }
@@ -20396,6 +20422,7 @@ var Message = class _Message {
20396
20422
  editedAt: json.metadata.editedAt ? new Date(json.metadata.editedAt) : void 0
20397
20423
  },
20398
20424
  attachments: json.attachments,
20425
+ replyTo: json.replyTo ? _Message.fromJSON(json.replyTo) : void 0,
20399
20426
  isMention: json.isMention,
20400
20427
  links: json.links
20401
20428
  });
@@ -20657,6 +20684,10 @@ function wrapTablesForAppend(text2, closeFences = false) {
20657
20684
  if (hadTrailingNewline) output += "\n";
20658
20685
  return output;
20659
20686
  }
20687
+ new AbortController().signal;
20688
+ new async_hooks.AsyncLocalStorage();
20689
+ //#endregion
20690
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/chat/4.40.0/cb3a31b4f44de113e1ec4eb2f27ce29a2c95f7dfe7c4e921ae20223eef9ddd4e/node_modules/chat/dist/index.js
20660
20691
  var emojiRegistry = /* @__PURE__ */ new Map();
20661
20692
  function getEmoji(name) {
20662
20693
  let emojiValue = emojiRegistry.get(name);
@@ -21198,6 +21229,7 @@ function convertEmojiPlaceholders(text2, platform, resolver = defaultEmojiResolv
21198
21229
  case "messenger": return resolver.toGChat(emojiName);
21199
21230
  case "github": return resolver.toGChat(emojiName);
21200
21231
  case "linear": return resolver.toGChat(emojiName);
21232
+ case "notion": return resolver.toGChat(emojiName);
21201
21233
  case "whatsapp": return resolver.toGChat(emojiName);
21202
21234
  case "x": return resolver.toGChat(emojiName);
21203
21235
  default: return resolver.toGChat(emojiName);
@@ -21321,7 +21353,7 @@ createEmoji();
21321
21353
  var cardChildToFallbackText2 = cardChildToFallbackText;
21322
21354
  var isCardElement2 = isCardElement;
21323
21355
  //#endregion
21324
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@chat-adapter/shared/4.34.0/61b8083225faf9588f3b11da0a74f492709b94eb39a17df303f9dc1f0076bb13/node_modules/@chat-adapter/shared/dist/index.js
21356
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@chat-adapter/shared/4.40.0/ecf50e78d3a8d604f33c10dbc1a34827ee808a3bb6e8ff49bdf456e77f76b102/node_modules/@chat-adapter/shared/dist/index.js
21325
21357
  function extractCard(message) {
21326
21358
  if (isCardElement2(message)) return message;
21327
21359
  if (typeof message === "object" && message !== null && "card" in message) return message.card;
@@ -21427,8 +21459,41 @@ function childToFallbackText(child, convertText) {
21427
21459
  default: return cardChildToFallbackText2(child);
21428
21460
  }
21429
21461
  }
21462
+ var IPV4 = [
21463
+ ["0.0.0.0", 8],
21464
+ ["10.0.0.0", 8],
21465
+ ["100.64.0.0", 10],
21466
+ ["127.0.0.0", 8],
21467
+ ["169.254.0.0", 16],
21468
+ ["172.16.0.0", 12],
21469
+ ["192.0.0.0", 24],
21470
+ ["192.0.2.0", 24],
21471
+ ["192.88.99.0", 24],
21472
+ ["192.168.0.0", 16],
21473
+ ["198.18.0.0", 15],
21474
+ ["198.51.100.0", 24],
21475
+ ["203.0.113.0", 24],
21476
+ ["224.0.0.0", 4],
21477
+ ["240.0.0.0", 4]
21478
+ ];
21479
+ var IPV6 = [
21480
+ ["::", 3],
21481
+ ["2001::", 23],
21482
+ ["2001:db8::", 32],
21483
+ ["2002::", 16],
21484
+ ["3fff::", 20],
21485
+ ["4000::", 2],
21486
+ ["8000::", 1]
21487
+ ];
21488
+ function blocklist(ranges, family) {
21489
+ const list = new net.BlockList();
21490
+ for (const [address, prefix] of ranges) list.addSubnet(address, prefix, family);
21491
+ return list;
21492
+ }
21493
+ blocklist(IPV4, "ipv4");
21494
+ blocklist(IPV6, "ipv6");
21430
21495
  //#endregion
21431
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@chat-adapter/telegram/4.34.0/8825d99c56744fbc97dc2010965b232202396c71dbbcb682a311406efeacefe4/node_modules/@chat-adapter/telegram/dist/index.js
21496
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@chat-adapter/telegram/4.40.0/91df867ef2394568ac329768f45e5aa4f73d2dd9aa77e81c8468e2c68e380ab7/node_modules/@chat-adapter/telegram/dist/index.js
21432
21497
  var CALLBACK_DATA_PREFIX = "chat:";
21433
21498
  var TELEGRAM_CALLBACK_DATA_LIMIT_BYTES = 64;
21434
21499
  function convertLabel(label) {
@@ -21934,6 +21999,7 @@ function media(blocks, result) {
21934
21999
  if (photo) result.push({
21935
22000
  file: photo,
21936
22001
  height: photo.height,
22002
+ mimeType: "image/jpeg",
21937
22003
  type: "image",
21938
22004
  width: photo.width
21939
22005
  });
@@ -21971,8 +22037,40 @@ function richMessageMedia(message) {
21971
22037
  return result;
21972
22038
  }
21973
22039
  var TELEGRAM_API_BASE = "https://api.telegram.org";
22040
+ var TELEGRAM_FILE_LIMIT = 25 * 1024 * 1024;
22041
+ var TELEGRAM_FILE_TIMEOUT_MS = 3e4;
22042
+ async function readTelegramFile(response, fileId) {
22043
+ const declared = Number(response.headers.get("content-length"));
22044
+ if (Number.isFinite(declared) && declared > TELEGRAM_FILE_LIMIT) {
22045
+ await response.body?.cancel();
22046
+ throw new NetworkError("telegram", `Telegram file ${fileId} exceeds the download limit`);
22047
+ }
22048
+ const reader = response.body?.getReader();
22049
+ if (!reader) return await response.arrayBuffer();
22050
+ const chunks = [];
22051
+ let size = 0;
22052
+ for (;;) {
22053
+ const { done, value } = await reader.read();
22054
+ if (done) break;
22055
+ size += value.length;
22056
+ if (size > TELEGRAM_FILE_LIMIT) {
22057
+ await reader.cancel();
22058
+ throw new NetworkError("telegram", `Telegram file ${fileId} exceeds the download limit`);
22059
+ }
22060
+ chunks.push(value);
22061
+ }
22062
+ const data = new Uint8Array(size);
22063
+ let offset = 0;
22064
+ for (const chunk of chunks) {
22065
+ data.set(chunk, offset);
22066
+ offset += chunk.length;
22067
+ }
22068
+ return data.buffer;
22069
+ }
21974
22070
  var TELEGRAM_SECRET_TOKEN_HEADER = "x-telegram-bot-api-secret-token";
22071
+ var TELEGRAM_WEBHOOK_VERIFICATION_ERROR = "secretToken is required in webhook mode. Set TELEGRAM_WEBHOOK_SECRET_TOKEN or provide secretToken. To accept unverified webhooks, set allowUnverifiedWebhooks: true or TELEGRAM_ALLOW_UNVERIFIED_WEBHOOKS=true.";
21975
22072
  var MESSAGE_ID_PATTERN = /^([^:]+):(\d+)$/;
22073
+ var BARE_MESSAGE_ID_PATTERN = /^\d+$/;
21976
22074
  var trimTrailingSlashes = (url) => {
21977
22075
  let end = url.length;
21978
22076
  while (end > 0 && url[end - 1] === "/") end--;
@@ -22010,6 +22108,15 @@ var TELEGRAM_DEFAULT_POLLING_TIMEOUT_SECONDS = 30;
22010
22108
  var TELEGRAM_DEFAULT_POLLING_LIMIT = 100;
22011
22109
  var TELEGRAM_DEFAULT_POLLING_RETRY_DELAY_MS = 1e3;
22012
22110
  var TELEGRAM_DEFAULT_STREAM_UPDATE_INTERVAL_MS = 250;
22111
+ var TELEGRAM_DEFAULT_PRIVATE_STREAMING_EDIT_INTERVAL_MS = 1100;
22112
+ var TELEGRAM_DEFAULT_NON_PRIVATE_STREAMING_EDIT_INTERVAL_MS = 3100;
22113
+ var TELEGRAM_STREAM_FINAL_EDIT_RETRY_CAP_MS = 5e3;
22114
+ var TELEGRAM_STREAM_PLACEHOLDER_TEXT = "...";
22115
+ var TELEGRAM_INCOMING_MEDIA_GROUP_BUFFER_TTL_MS = 3e4;
22116
+ var TELEGRAM_INCOMING_MEDIA_GROUP_LOCK_TTL_MS = 5e3;
22117
+ var TELEGRAM_INCOMING_MEDIA_GROUP_RETRY_MS = 50;
22118
+ var TELEGRAM_INCOMING_MEDIA_GROUP_SETTLE_MS = 1e3;
22119
+ var TELEGRAM_WEBHOOK_UPDATE_TTL_MS = 1440 * 60 * 1e3;
22013
22120
  var TELEGRAM_MEDIA_GROUP_MIN = 2;
22014
22121
  var TELEGRAM_MEDIA_GROUP_MAX = 10;
22015
22122
  var TELEGRAM_MARKDOWN_PARSE_ERROR_PATTERN = /can't parse (?:caption )?entities/i;
@@ -22017,6 +22124,23 @@ var TELEGRAM_MAX_POLLING_LIMIT = 100;
22017
22124
  var TELEGRAM_MIN_POLLING_LIMIT = 1;
22018
22125
  var TELEGRAM_MIN_POLLING_TIMEOUT_SECONDS = 0;
22019
22126
  var TELEGRAM_MAX_POLLING_TIMEOUT_SECONDS = 300;
22127
+ var TELEGRAM_BUSINESS_ALLOWED_UPDATES = [
22128
+ "business_connection",
22129
+ "business_message",
22130
+ "edited_business_message"
22131
+ ];
22132
+ var TELEGRAM_DEFAULT_ALLOWED_UPDATES = [
22133
+ "message",
22134
+ "edited_message",
22135
+ "channel_post",
22136
+ "edited_channel_post",
22137
+ "callback_query"
22138
+ ];
22139
+ var TELEGRAM_BUSINESS_CONNECTION_TTL_MS = 3600 * 1e3;
22140
+ function normalizeBotTokenProvider(botToken) {
22141
+ if (typeof botToken === "function") return async () => await botToken();
22142
+ return () => Promise.resolve(botToken);
22143
+ }
22020
22144
  var escapeMarkdownInEntity = (text2) => text2.replace(/([[\]()\\])/g, "\\$1");
22021
22145
  function applyTelegramEntities(text2, entities) {
22022
22146
  if (entities.length === 0) return text2;
@@ -22058,13 +22182,67 @@ ${entityText}
22058
22182
  }
22059
22183
  return result;
22060
22184
  }
22185
+ function describeNonFileContent(raw) {
22186
+ if (raw.venue) return `\u{1F4CD} ${raw.venue.title}, ${raw.venue.address}`;
22187
+ if (raw.location) return `\u{1F4CD} ${raw.location.latitude}, ${raw.location.longitude}`;
22188
+ if (raw.contact) return `\u{1F464} ${[raw.contact.first_name, raw.contact.last_name].filter(Boolean).join(" ")} ${raw.contact.phone_number}`.trim();
22189
+ if (raw.poll) return `\u{1F4CA} ${raw.poll.question}`;
22190
+ if (raw.dice) return `${raw.dice.emoji} ${raw.dice.value}`;
22191
+ if (raw.game) return `\u{1F3AE} ${raw.game.title}`;
22192
+ if (raw.invoice) {
22193
+ const amount = formatInvoiceAmount(raw.invoice.total_amount, raw.invoice.currency);
22194
+ return `\u{1F9FE} ${raw.invoice.title} \u2014 ${amount} ${raw.invoice.currency}`;
22195
+ }
22196
+ if (raw.story) return "📖 Story";
22197
+ }
22198
+ var ZERO_EXPONENT_CURRENCIES = /* @__PURE__ */ new Set([
22199
+ "CLP",
22200
+ "ISK",
22201
+ "JPY",
22202
+ "KRW",
22203
+ "PYG",
22204
+ "UGX",
22205
+ "VND",
22206
+ "XTR"
22207
+ ]);
22208
+ var THREE_EXPONENT_CURRENCIES = /* @__PURE__ */ new Set([
22209
+ "BHD",
22210
+ "IQD",
22211
+ "JOD"
22212
+ ]);
22213
+ function formatInvoiceAmount(totalAmount, currency) {
22214
+ let exponent = 2;
22215
+ if (ZERO_EXPONENT_CURRENCIES.has(currency)) exponent = 0;
22216
+ else if (THREE_EXPONENT_CURRENCIES.has(currency)) exponent = 3;
22217
+ return (totalAmount / 10 ** exponent).toFixed(exponent);
22218
+ }
22219
+ function stickerAttachmentFormat(sticker) {
22220
+ if (sticker.is_video) return {
22221
+ type: "video",
22222
+ mimeType: "video/webm"
22223
+ };
22224
+ if (sticker.is_animated) return {
22225
+ type: "file",
22226
+ mimeType: "application/x-tgsticker"
22227
+ };
22228
+ return {
22229
+ type: "image",
22230
+ mimeType: "image/webp"
22231
+ };
22232
+ }
22061
22233
  var TelegramAdapter = class {
22062
22234
  name = "telegram";
22063
22235
  lockScope = "channel";
22064
22236
  persistThreadHistory = true;
22065
- botToken;
22237
+ allowedUserIds;
22238
+ allowUnverifiedWebhooks;
22239
+ botTokenProvider;
22240
+ staticBotToken;
22066
22241
  apiBaseUrl;
22067
22242
  secretToken;
22243
+ mentionOnReply;
22244
+ botIdentityPromise = null;
22245
+ webhookScope;
22068
22246
  warnedNoVerification = false;
22069
22247
  logger;
22070
22248
  formatConverter = new TelegramFormatConverter();
@@ -22072,9 +22250,14 @@ var TelegramAdapter = class {
22072
22250
  chat = null;
22073
22251
  _botUserId;
22074
22252
  _userName;
22253
+ _mentionRegexUsername;
22254
+ _mentionRegex;
22075
22255
  hasExplicitUserName;
22076
22256
  mode;
22257
+ nativeStreaming;
22258
+ streamingEditIntervalMs;
22077
22259
  longPolling;
22260
+ businessMode;
22078
22261
  _runtimeMode = "webhook";
22079
22262
  pollingAbortController = null;
22080
22263
  pollingTask = null;
@@ -22096,20 +22279,49 @@ var TelegramAdapter = class {
22096
22279
  constructor(config = {}) {
22097
22280
  const botToken = config.botToken ?? process.env.TELEGRAM_BOT_TOKEN;
22098
22281
  if (!botToken) throw new ValidationError("telegram", "botToken is required. Set TELEGRAM_BOT_TOKEN or provide it in config.");
22099
- this.botToken = botToken;
22282
+ this.botTokenProvider = normalizeBotTokenProvider(botToken);
22283
+ this.staticBotToken = typeof botToken === "string" ? botToken : void 0;
22100
22284
  this.apiBaseUrl = trimTrailingSlashes(config.apiUrl ?? config.apiBaseUrl ?? process.env.TELEGRAM_API_BASE_URL ?? TELEGRAM_API_BASE);
22101
22285
  this.secretToken = config.secretToken ?? process.env.TELEGRAM_WEBHOOK_SECRET_TOKEN;
22286
+ this.allowUnverifiedWebhooks = config.allowUnverifiedWebhooks ?? process.env.TELEGRAM_ALLOW_UNVERIFIED_WEBHOOKS === "true";
22287
+ this.mentionOnReply = config.mentionOnReply ?? process.env.TELEGRAM_MENTION_ON_REPLY === "true";
22288
+ const normalizedAllowedUserIds = (config.allowedUserIds ?? process.env.TELEGRAM_ALLOWED_USER_IDS?.split(","))?.map((id) => String(id).trim()).filter(Boolean);
22289
+ this.allowedUserIds = normalizedAllowedUserIds?.length ? new Set(normalizedAllowedUserIds) : void 0;
22102
22290
  this.logger = config.logger ?? new ConsoleLogger("info").child("telegram");
22103
22291
  const userName = config.userName ?? process.env.TELEGRAM_BOT_USERNAME;
22104
22292
  this._userName = this.normalizeUserName(userName ?? "bot");
22105
22293
  this.hasExplicitUserName = Boolean(userName);
22106
22294
  this.mode = config.mode ?? "auto";
22295
+ this.nativeStreaming = config.nativeStreaming ?? false;
22296
+ this.streamingEditIntervalMs = typeof config.streamingEditIntervalMs !== "number" || !Number.isFinite(config.streamingEditIntervalMs) ? void 0 : this.clampInteger(config.streamingEditIntervalMs, 0, 0, Number.MAX_SAFE_INTEGER);
22107
22297
  this.longPolling = config.longPolling;
22298
+ this.businessMode = config.businessMode ?? false;
22108
22299
  if (![
22109
22300
  "auto",
22110
22301
  "webhook",
22111
22302
  "polling"
22112
22303
  ].includes(this.mode)) throw new ValidationError("telegram", `Invalid mode: ${this.mode}. Expected "auto", "webhook", or "polling".`);
22304
+ if (this.mode === "webhook" && !(this.secretToken || this.allowUnverifiedWebhooks)) throw new ValidationError("telegram", TELEGRAM_WEBHOOK_VERIFICATION_ERROR);
22305
+ }
22306
+ async resolveBotToken() {
22307
+ const botToken = await this.botTokenProvider();
22308
+ if (!botToken) throw new AuthenticationError("telegram", "Telegram bot token resolver returned an empty token. Check TELEGRAM_BOT_TOKEN or the Vercel Connect connector.");
22309
+ return botToken;
22310
+ }
22311
+ async ensureBotIdentity() {
22312
+ if (this.webhookScope) return;
22313
+ if (!this.botIdentityPromise) this.botIdentityPromise = this.telegramFetch("getMe").then((me) => {
22314
+ this._botUserId = String(me.id);
22315
+ this.webhookScope = (0, crypto$1.createHash)("sha256").update(this._botUserId).digest("hex");
22316
+ if (!this.hasExplicitUserName && me.username) this._userName = this.normalizeUserName(me.username);
22317
+ this.logger.info("Telegram bot identity resolved", {
22318
+ botUserId: this._botUserId,
22319
+ userName: this._userName
22320
+ });
22321
+ }).finally(() => {
22322
+ this.botIdentityPromise = null;
22323
+ });
22324
+ await this.botIdentityPromise;
22113
22325
  }
22114
22326
  async initialize(chat) {
22115
22327
  this.chat = chat;
@@ -22118,18 +22330,13 @@ var TelegramAdapter = class {
22118
22330
  if (typeof chatUserName === "string" && chatUserName.trim()) this._userName = this.normalizeUserName(chatUserName);
22119
22331
  }
22120
22332
  try {
22121
- const me = await this.telegramFetch("getMe");
22122
- this._botUserId = String(me.id);
22123
- if (!this.hasExplicitUserName && me.username) this._userName = this.normalizeUserName(me.username);
22124
- this.logger.info("Telegram adapter initialized", {
22125
- botUserId: this._botUserId,
22126
- userName: this._userName
22127
- });
22333
+ await this.ensureBotIdentity();
22128
22334
  } catch (error) {
22129
22335
  this.logger.warn("Failed to fetch Telegram bot identity", { error: String(error) });
22130
22336
  }
22131
22337
  const runtimeMode = await this.resolveRuntimeMode();
22132
22338
  this._runtimeMode = runtimeMode;
22339
+ if (runtimeMode === "webhook" && !(this.secretToken || this.allowUnverifiedWebhooks)) throw new ValidationError("telegram", TELEGRAM_WEBHOOK_VERIFICATION_ERROR);
22133
22340
  if (runtimeMode === "polling") {
22134
22341
  const pollingConfig = this.longPolling;
22135
22342
  if (this.mode === "auto") await this.startPolling(pollingConfig ? {
@@ -22155,6 +22362,10 @@ var TelegramAdapter = class {
22155
22362
  }
22156
22363
  }
22157
22364
  async handleWebhook(request, options) {
22365
+ if (!(this.secretToken || this.allowUnverifiedWebhooks)) {
22366
+ this.logger.warn("Telegram webhook rejected because verification is not configured");
22367
+ return new Response("Webhook verification required", { status: 401 });
22368
+ }
22158
22369
  if (this.secretToken) {
22159
22370
  const headerToken = request.headers.get(TELEGRAM_SECRET_TOKEN_HEADER);
22160
22371
  let valid = false;
@@ -22167,7 +22378,7 @@ var TelegramAdapter = class {
22167
22378
  }
22168
22379
  } else if (!this.warnedNoVerification) {
22169
22380
  this.warnedNoVerification = true;
22170
- this.logger.warn("Telegram webhook verification is disabled. Set TELEGRAM_WEBHOOK_SECRET_TOKEN or secretToken to verify incoming requests.");
22381
+ this.logger.warn("Telegram webhook verification is explicitly disabled");
22171
22382
  }
22172
22383
  let update;
22173
22384
  try {
@@ -22179,6 +22390,29 @@ var TelegramAdapter = class {
22179
22390
  this.logger.warn("Chat instance not initialized, ignoring Telegram webhook");
22180
22391
  return new Response("OK", { status: 200 });
22181
22392
  }
22393
+ if (Number.isInteger(update.update_id)) {
22394
+ let webhookScope = this.webhookScope;
22395
+ if (!webhookScope) try {
22396
+ await this.ensureBotIdentity();
22397
+ webhookScope = this.webhookScope;
22398
+ } catch (error) {
22399
+ this.logger.warn("Telegram webhook update could not resolve bot identity", { error: String(error) });
22400
+ return new Response("Service unavailable", { status: 503 });
22401
+ }
22402
+ if (!webhookScope) return new Response("Service unavailable", { status: 503 });
22403
+ try {
22404
+ if (!await this.chat.getState().setIfNotExists(`${this.name}:webhook-update:${webhookScope}:${update.update_id}`, true, TELEGRAM_WEBHOOK_UPDATE_TTL_MS)) {
22405
+ this.logger.debug("Ignoring duplicate Telegram webhook update", { updateId: update.update_id });
22406
+ return new Response("OK", { status: 200 });
22407
+ }
22408
+ } catch (error) {
22409
+ this.logger.warn("Failed to claim Telegram webhook update", {
22410
+ error: String(error),
22411
+ updateId: update.update_id
22412
+ });
22413
+ return new Response("Service unavailable", { status: 503 });
22414
+ }
22415
+ }
22182
22416
  try {
22183
22417
  this.processUpdate(update, options);
22184
22418
  } catch (error) {
@@ -22260,11 +22494,105 @@ var TelegramAdapter = class {
22260
22494
  return Boolean(process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME || process.env.AWS_EXECUTION_ENV?.includes("AWS_Lambda") || process.env.FUNCTIONS_WORKER_RUNTIME || process.env.NETLIFY || process.env.K_SERVICE);
22261
22495
  }
22262
22496
  processUpdate(update, options) {
22497
+ if (this.businessMode && update.business_connection) {
22498
+ const connection = update.business_connection;
22499
+ const task = this.cacheBusinessConnection(connection).catch((error) => {
22500
+ this.logger.warn("Failed to cache Telegram business connection", {
22501
+ error: String(error),
22502
+ connectionId: connection.id
22503
+ });
22504
+ });
22505
+ options?.waitUntil?.(task);
22506
+ }
22263
22507
  const messageUpdate = update.message ?? update.edited_message ?? update.channel_post ?? update.edited_channel_post;
22264
- const handledSlashCommand = update.message !== void 0 && this.handleSlashCommandUpdate(update.message, options);
22508
+ const businessMessageUpdate = update.business_message ?? update.edited_business_message;
22509
+ const userId = update.callback_query?.from.id ?? update.message_reaction?.user?.id ?? messageUpdate?.from?.id ?? businessMessageUpdate?.from?.id;
22510
+ if (this.allowedUserIds && (userId === void 0 || !this.allowedUserIds.has(String(userId)))) return;
22511
+ const handledSlashCommand = update.message !== void 0 && !update.message.media_group_id && this.handleSlashCommandUpdate(update.message, this.encodeThreadId({
22512
+ chatId: String(update.message.chat.id),
22513
+ messageThreadId: update.message.message_thread_id
22514
+ }), options);
22265
22515
  if (messageUpdate && !handledSlashCommand) this.handleIncomingMessageUpdate(messageUpdate, options);
22266
22516
  if (update.callback_query) this.handleCallbackQuery(update.callback_query, options);
22267
22517
  if (update.message_reaction) this.handleMessageReactionUpdate(update.message_reaction, options);
22518
+ if (this.businessMode && businessMessageUpdate) {
22519
+ const task = this.handleBusinessMessageUpdate(businessMessageUpdate, { isEdit: update.business_message === void 0 }, options).catch((error) => {
22520
+ this.logger.warn("Failed to process Telegram business message", {
22521
+ error: String(error),
22522
+ connectionId: businessMessageUpdate.business_connection_id
22523
+ });
22524
+ });
22525
+ options?.waitUntil?.(task);
22526
+ }
22527
+ }
22528
+ businessConnectionCacheKey(connectionId) {
22529
+ return `${this.name}:business-connection:${connectionId}`;
22530
+ }
22531
+ /**
22532
+ * Business connections live in shared state rather than a per-instance map
22533
+ * so a rights change that reaches one serverless instance is visible to all
22534
+ * of them on the next message.
22535
+ */
22536
+ async cacheBusinessConnection(connection) {
22537
+ if (!this.chat) return;
22538
+ await this.chat.getState().set(this.businessConnectionCacheKey(connection.id), connection, TELEGRAM_BUSINESS_CONNECTION_TTL_MS);
22539
+ }
22540
+ async resolveBusinessConnection(connectionId) {
22541
+ const state = this.chat?.getState();
22542
+ const key = this.businessConnectionCacheKey(connectionId);
22543
+ const cached = await state?.get(key);
22544
+ if (cached) return cached;
22545
+ const connection = await this.telegramFetch("getBusinessConnection", { business_connection_id: connectionId });
22546
+ await state?.set(key, connection, TELEGRAM_BUSINESS_CONNECTION_TTL_MS);
22547
+ return connection;
22548
+ }
22549
+ isBusinessConnectionUsable(connection) {
22550
+ return connection.is_enabled && (connection.rights?.can_reply ?? false);
22551
+ }
22552
+ async handleBusinessMessageUpdate(telegramMessage, routing, options) {
22553
+ if (!this.chat) return;
22554
+ const connectionId = telegramMessage.business_connection_id;
22555
+ if (!connectionId) {
22556
+ this.logger.warn("Telegram business message missing connection id", { messageId: telegramMessage.message_id });
22557
+ return;
22558
+ }
22559
+ const connection = await this.resolveBusinessConnection(connectionId);
22560
+ if (!this.isBusinessConnectionUsable(connection)) {
22561
+ this.logger.debug("Ignoring Telegram business message: connection cannot reply", {
22562
+ connectionId,
22563
+ isEnabled: connection.is_enabled,
22564
+ canReply: connection.rights?.can_reply ?? false
22565
+ });
22566
+ return;
22567
+ }
22568
+ if (telegramMessage.sender_business_bot) return;
22569
+ if (telegramMessage.from?.id === connection.user.id) {
22570
+ this.logger.debug("Ignoring Telegram business message typed by the account owner", {
22571
+ connectionId,
22572
+ messageId: telegramMessage.message_id
22573
+ });
22574
+ return;
22575
+ }
22576
+ const threadId = this.encodeThreadId({
22577
+ chatId: String(telegramMessage.chat.id),
22578
+ businessConnectionId: connectionId
22579
+ });
22580
+ if (telegramMessage.media_group_id) {
22581
+ const task = this.processIncomingMediaGroup(telegramMessage, threadId).catch((error) => {
22582
+ this.logger.warn("Failed to process incoming Telegram media group", {
22583
+ error: String(error),
22584
+ mediaGroupId: telegramMessage.media_group_id,
22585
+ threadId
22586
+ });
22587
+ });
22588
+ options?.waitUntil?.(task);
22589
+ return;
22590
+ }
22591
+ if (!routing.isEdit && this.handleSlashCommandUpdate(telegramMessage, threadId, options)) return;
22592
+ this.startTypingForPrivateMessage(telegramMessage, threadId, options);
22593
+ const parsedMessage = this.parseTelegramMessage(telegramMessage, threadId);
22594
+ this.cacheMessage(parsedMessage);
22595
+ this.chat.processMessage(this, threadId, parsedMessage, options);
22268
22596
  }
22269
22597
  handleIncomingMessageUpdate(telegramMessage, options) {
22270
22598
  if (!this.chat) return;
@@ -22272,19 +22600,87 @@ var TelegramAdapter = class {
22272
22600
  chatId: String(telegramMessage.chat.id),
22273
22601
  messageThreadId: telegramMessage.message_thread_id
22274
22602
  });
22603
+ if (telegramMessage.media_group_id) {
22604
+ const task = this.processIncomingMediaGroup(telegramMessage, threadId).catch((error) => {
22605
+ this.logger.warn("Failed to process incoming Telegram media group", {
22606
+ error: String(error),
22607
+ mediaGroupId: telegramMessage.media_group_id,
22608
+ threadId
22609
+ });
22610
+ });
22611
+ options?.waitUntil?.(task);
22612
+ return;
22613
+ }
22275
22614
  this.startTypingForPrivateMessage(telegramMessage, threadId, options);
22276
22615
  const parsedMessage = this.parseTelegramMessage(telegramMessage, threadId);
22277
22616
  this.cacheMessage(parsedMessage);
22278
22617
  this.chat.processMessage(this, threadId, parsedMessage, options);
22279
22618
  }
22280
- handleSlashCommandUpdate(telegramMessage, options) {
22619
+ async processIncomingMediaGroup(telegramMessage, threadId) {
22620
+ if (!(this.chat && telegramMessage.media_group_id)) return;
22621
+ const state = this.chat.getState();
22622
+ const mediaGroupKey = `${this.name}:incoming-media-group:${threadId}:${telegramMessage.media_group_id}`;
22623
+ const lockKey = `${mediaGroupKey}:lock`;
22624
+ let appended = false;
22625
+ for (;;) {
22626
+ const lock = await state.acquireLock(lockKey, TELEGRAM_INCOMING_MEDIA_GROUP_LOCK_TTL_MS);
22627
+ if (!lock) {
22628
+ await this.sleep(TELEGRAM_INCOMING_MEDIA_GROUP_RETRY_MS);
22629
+ continue;
22630
+ }
22631
+ let entries = [];
22632
+ let remainingSettleMs = 0;
22633
+ try {
22634
+ entries = await state.get(mediaGroupKey) ?? [];
22635
+ if (!appended) {
22636
+ entries.push({
22637
+ message: telegramMessage,
22638
+ receivedAt: Date.now()
22639
+ });
22640
+ await state.set(mediaGroupKey, entries.slice(-TELEGRAM_MEDIA_GROUP_MAX), TELEGRAM_INCOMING_MEDIA_GROUP_BUFFER_TTL_MS);
22641
+ appended = true;
22642
+ remainingSettleMs = TELEGRAM_INCOMING_MEDIA_GROUP_SETTLE_MS;
22643
+ } else if (entries.length === 0) return;
22644
+ else {
22645
+ const newestReceivedAt = Math.max(...entries.map((entry) => entry.receivedAt));
22646
+ remainingSettleMs = Math.max(0, TELEGRAM_INCOMING_MEDIA_GROUP_SETTLE_MS - (Date.now() - newestReceivedAt));
22647
+ if (remainingSettleMs === 0) await state.delete(mediaGroupKey);
22648
+ }
22649
+ } finally {
22650
+ await state.releaseLock(lock);
22651
+ }
22652
+ if (remainingSettleMs > 0) {
22653
+ await this.sleep(remainingSettleMs);
22654
+ continue;
22655
+ }
22656
+ const orderedMessages = entries.map((entry) => entry.message).sort((left, right) => left.message_id - right.message_id);
22657
+ const parsedMessages = orderedMessages.map((message) => this.parseTelegramMessage(message, threadId));
22658
+ const latestMessage = parsedMessages.at(-1);
22659
+ if (!latestMessage) return;
22660
+ const contentMessage = parsedMessages.find((message) => message.text.length > 0) ?? latestMessage;
22661
+ const combinedMessage = new Message({
22662
+ id: latestMessage.id,
22663
+ threadId,
22664
+ text: contentMessage.text,
22665
+ formatted: contentMessage.formatted,
22666
+ raw: latestMessage.raw,
22667
+ author: latestMessage.author,
22668
+ metadata: latestMessage.metadata,
22669
+ attachments: parsedMessages.flatMap((message) => message.attachments),
22670
+ replyTo: parsedMessages.find((message) => message.replyTo)?.replyTo,
22671
+ isMention: parsedMessages.some((message) => message.isMention),
22672
+ links: parsedMessages.flatMap((message) => message.links)
22673
+ });
22674
+ this.startTypingForPrivateMessage(orderedMessages[0], threadId);
22675
+ this.cacheMessage(combinedMessage);
22676
+ await this.chat.processMessage(this, threadId, combinedMessage);
22677
+ return;
22678
+ }
22679
+ }
22680
+ handleSlashCommandUpdate(telegramMessage, threadId, options) {
22281
22681
  if (!this.chat) return false;
22282
22682
  const slashCommand = this.parseSlashCommand(telegramMessage);
22283
22683
  if (!slashCommand) return false;
22284
- const threadId = this.encodeThreadId({
22285
- chatId: String(telegramMessage.chat.id),
22286
- messageThreadId: telegramMessage.message_thread_id
22287
- });
22288
22684
  this.startTypingForPrivateMessage(telegramMessage, threadId, options);
22289
22685
  const parsedMessage = this.parseTelegramMessage(telegramMessage, threadId);
22290
22686
  this.cacheMessage(parsedMessage);
@@ -22332,7 +22728,8 @@ var TelegramAdapter = class {
22332
22728
  if (!(this.chat && callbackQuery.message)) return;
22333
22729
  const threadId = this.encodeThreadId({
22334
22730
  chatId: String(callbackQuery.message.chat.id),
22335
- messageThreadId: callbackQuery.message.message_thread_id
22731
+ messageThreadId: callbackQuery.message.message_thread_id,
22732
+ businessConnectionId: callbackQuery.message.business_connection_id
22336
22733
  });
22337
22734
  const messageId = this.encodeMessageId(String(callbackQuery.message.chat.id), callbackQuery.message.message_id);
22338
22735
  const { actionId, value } = decodeTelegramCallbackData(callbackQuery.data);
@@ -22390,8 +22787,9 @@ var TelegramAdapter = class {
22390
22787
  }, options);
22391
22788
  }
22392
22789
  }
22393
- async postMessage(threadId, message) {
22790
+ async postMessage(threadId, message, replyToMessageId) {
22394
22791
  const parsedThread = this.resolveThreadId(threadId);
22792
+ const replyParameters = this.buildReplyParameters(replyToMessageId, parsedThread.chatId);
22395
22793
  const card = extractCard(message);
22396
22794
  const replyMarkup = card ? cardToTelegramInlineKeyboard(card) : void 0;
22397
22795
  const parseMode = this.resolveParseMode(message, card);
@@ -22405,19 +22803,19 @@ var TelegramAdapter = class {
22405
22803
  if (files.length > 0) {
22406
22804
  const [file] = files;
22407
22805
  if (!file) throw new ValidationError("telegram", "File upload payload is empty");
22408
- rawMessages = files.length === 1 ? [await this.sendDocument(parsedThread, file, text2, plainText, replyMarkup, parseMode)] : await this.sendDocumentMediaGroup(parsedThread, files, text2, plainText, replyMarkup, parseMode);
22806
+ rawMessages = files.length === 1 ? [await this.sendDocument(parsedThread, file, text2, plainText, replyMarkup, parseMode, replyParameters)] : await this.sendDocumentMediaGroup(parsedThread, files, text2, plainText, replyMarkup, parseMode, replyParameters);
22409
22807
  } else if (attachments.length > 0) {
22410
22808
  const [attachment] = attachments;
22411
22809
  if (!attachment) throw new ValidationError("telegram", "Attachment upload payload is empty");
22412
- rawMessages = attachments.length === 1 ? [await this.sendAttachment(parsedThread, attachment, text2, plainText, replyMarkup, parseMode)] : await this.sendAttachmentMediaGroup(parsedThread, attachments, text2, plainText, replyMarkup, parseMode);
22810
+ rawMessages = attachments.length === 1 ? [await this.sendAttachment(parsedThread, attachment, text2, plainText, replyMarkup, parseMode, replyParameters)] : await this.sendAttachmentMediaGroup(parsedThread, attachments, text2, plainText, replyMarkup, parseMode, replyParameters);
22413
22811
  } else {
22414
22812
  if (!text2.trim()) throw new ValidationError("telegram", "Message text cannot be empty");
22415
- const sendRegular = () => this.sendRegularMessage(parsedThread, text2, plainText, parseMode, replyMarkup, threadId);
22813
+ const sendRegular = () => this.sendRegularMessage(parsedThread, text2, plainText, parseMode, replyMarkup, threadId, replyParameters);
22416
22814
  rawMessages = [rich ? await this.withTelegramRichFallback(() => this.telegramFetch("sendRichMessage", {
22417
- chat_id: parsedThread.chatId,
22418
- message_thread_id: parsedThread.messageThreadId,
22815
+ ...this.buildChatTargetParams(parsedThread),
22419
22816
  rich_message: { markdown: rich.markdown },
22420
- reply_markup: replyMarkup
22817
+ reply_markup: replyMarkup,
22818
+ reply_parameters: replyParameters
22421
22819
  }), sendRegular, {
22422
22820
  method: "sendRichMessage",
22423
22821
  threadId
@@ -22425,7 +22823,8 @@ var TelegramAdapter = class {
22425
22823
  }
22426
22824
  const parsedMessages = rawMessages.map((rawMessage) => this.parseTelegramMessage(rawMessage, this.encodeThreadId({
22427
22825
  chatId: String(rawMessage.chat.id),
22428
- messageThreadId: rawMessage.message_thread_id ?? parsedThread.messageThreadId
22826
+ messageThreadId: rawMessage.message_thread_id ?? parsedThread.messageThreadId,
22827
+ businessConnectionId: parsedThread.businessConnectionId
22429
22828
  }), rich ? {
22430
22829
  formatted: rich.formatted,
22431
22830
  text: rich.text
@@ -22442,9 +22841,20 @@ var TelegramAdapter = class {
22442
22841
  async postChannelMessage(channelId, message) {
22443
22842
  return this.postMessage(channelId, message);
22444
22843
  }
22844
+ /**
22845
+ * Post a message as a native Telegram reply to `messageId`.
22846
+ *
22847
+ * Telegram threads the answer to its question with `reply_parameters`, which
22848
+ * is what `Thread.reply()` expects an adapter to provide. Every Telegram
22849
+ * send is a single API call (text is truncated, media groups are one
22850
+ * request), so the reference always rides on that one call.
22851
+ */
22852
+ async reply(threadId, messageId, message) {
22853
+ return this.postMessage(threadId, message, messageId);
22854
+ }
22445
22855
  async editMessage(threadId, messageId, message) {
22446
22856
  const parsedThread = this.resolveThreadId(threadId);
22447
- const { chatId, messageId: telegramMessageId, compositeId } = this.decodeCompositeMessageId(messageId, parsedThread.chatId);
22857
+ const { messageId: telegramMessageId, compositeId } = this.decodeCompositeMessageId(messageId, parsedThread.chatId);
22448
22858
  const card = extractCard(message);
22449
22859
  const replyMarkup = card ? cardToTelegramInlineKeyboard(card) : void 0;
22450
22860
  const parseMode = this.resolveParseMode(message, card);
@@ -22453,7 +22863,7 @@ var TelegramAdapter = class {
22453
22863
  const rich = this.resolveRichMessage(message, card, 0, 0);
22454
22864
  if (!text2.trim()) throw new ValidationError("telegram", "Message text cannot be empty");
22455
22865
  const editRegular = () => this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => this.telegramFetch("editMessageText", {
22456
- chat_id: chatId,
22866
+ ...this.buildChatTargetParams(parsedThread),
22457
22867
  message_id: telegramMessageId,
22458
22868
  text: resolvedText,
22459
22869
  reply_markup: replyMarkup ?? emptyTelegramInlineKeyboard(),
@@ -22466,7 +22876,7 @@ var TelegramAdapter = class {
22466
22876
  threadId
22467
22877
  });
22468
22878
  const result = rich ? await this.withTelegramRichFallback(() => this.telegramFetch("editMessageText", {
22469
- chat_id: chatId,
22879
+ ...this.buildChatTargetParams(parsedThread),
22470
22880
  message_id: telegramMessageId,
22471
22881
  rich_message: { markdown: rich.markdown },
22472
22882
  reply_markup: replyMarkup ?? emptyTelegramInlineKeyboard()
@@ -22497,7 +22907,8 @@ var TelegramAdapter = class {
22497
22907
  }
22498
22908
  const resultingThreadId = this.encodeThreadId({
22499
22909
  chatId: String(result.chat.id),
22500
- messageThreadId: result.message_thread_id ?? parsedThread.messageThreadId
22910
+ messageThreadId: result.message_thread_id ?? parsedThread.messageThreadId,
22911
+ businessConnectionId: parsedThread.businessConnectionId
22501
22912
  });
22502
22913
  const parsedMessage = this.parseTelegramMessage(result, resultingThreadId, rich ? {
22503
22914
  formatted: rich.formatted,
@@ -22512,41 +22923,155 @@ var TelegramAdapter = class {
22512
22923
  }
22513
22924
  async deleteMessage(threadId, messageId) {
22514
22925
  const parsedThread = this.resolveThreadId(threadId);
22515
- const { chatId, messageId: telegramMessageId, compositeId } = this.decodeCompositeMessageId(messageId, parsedThread.chatId);
22516
- await this.telegramFetch("deleteMessage", {
22517
- chat_id: chatId,
22926
+ const { messageId: telegramMessageId, compositeId } = this.decodeCompositeMessageId(messageId, parsedThread.chatId);
22927
+ if (parsedThread.businessConnectionId) await this.telegramFetch("deleteBusinessMessages", {
22928
+ business_connection_id: parsedThread.businessConnectionId,
22929
+ message_ids: [telegramMessageId]
22930
+ });
22931
+ else await this.telegramFetch("deleteMessage", {
22932
+ chat_id: parsedThread.chatId,
22518
22933
  message_id: telegramMessageId
22519
22934
  });
22520
22935
  this.deleteCachedMessage(compositeId);
22521
22936
  }
22522
22937
  async addReaction(threadId, messageId, emoji) {
22523
22938
  const parsedThread = this.resolveThreadId(threadId);
22524
- const { chatId, messageId: telegramMessageId } = this.decodeCompositeMessageId(messageId, parsedThread.chatId);
22939
+ this.assertReactionsSupported(parsedThread, "addReaction");
22940
+ const { messageId: telegramMessageId } = this.decodeCompositeMessageId(messageId, parsedThread.chatId);
22525
22941
  await this.telegramFetch("setMessageReaction", {
22526
- chat_id: chatId,
22942
+ chat_id: parsedThread.chatId,
22527
22943
  message_id: telegramMessageId,
22528
22944
  reaction: [this.toTelegramReaction(emoji)]
22529
22945
  });
22530
22946
  }
22531
22947
  async removeReaction(threadId, messageId, _emoji) {
22532
22948
  const parsedThread = this.resolveThreadId(threadId);
22533
- const { chatId, messageId: telegramMessageId } = this.decodeCompositeMessageId(messageId, parsedThread.chatId);
22949
+ this.assertReactionsSupported(parsedThread, "removeReaction");
22950
+ const { messageId: telegramMessageId } = this.decodeCompositeMessageId(messageId, parsedThread.chatId);
22534
22951
  await this.telegramFetch("setMessageReaction", {
22535
- chat_id: chatId,
22952
+ chat_id: parsedThread.chatId,
22536
22953
  message_id: telegramMessageId,
22537
22954
  reaction: []
22538
22955
  });
22539
22956
  }
22957
+ /**
22958
+ * `setMessageReaction` has no `business_connection_id` parameter, and the
22959
+ * bot cannot address a business chat by `chat_id` alone, so reactions on
22960
+ * business threads fail with an opaque Telegram error. Surface that up
22961
+ * front instead.
22962
+ */
22963
+ assertReactionsSupported(thread, method) {
22964
+ if (thread.businessConnectionId) throw new NotImplementedError("Telegram Bot API does not support reactions on behalf of a business account", method);
22965
+ }
22540
22966
  async startTyping(threadId) {
22541
22967
  const parsedThread = this.resolveThreadId(threadId);
22542
22968
  await this.telegramFetch("sendChatAction", {
22543
- chat_id: parsedThread.chatId,
22544
- message_thread_id: parsedThread.messageThreadId,
22969
+ ...this.buildChatTargetParams(parsedThread),
22545
22970
  action: "typing"
22546
22971
  });
22547
22972
  }
22548
22973
  async stream(threadId, textStream, options) {
22549
- if (!this.isDM(threadId)) return null;
22974
+ if (this.nativeStreaming && this.isDM(threadId)) return await this.nativeDraftStream(threadId, textStream, options);
22975
+ return await this.postAndEditStream(threadId, textStream, options);
22976
+ }
22977
+ /**
22978
+ * Post a placeholder message and edit it as chunks arrive.
22979
+ *
22980
+ * The adapter owns this loop rather than deferring to the chat core's
22981
+ * fallback so edits can be throttled to Telegram's per-chat rate limit,
22982
+ * which the core interval (500ms by default) sits under.
22983
+ */
22984
+ async postAndEditStream(threadId, textStream, options) {
22985
+ const defaultIntervalMs = this.isDM(threadId) ? TELEGRAM_DEFAULT_PRIVATE_STREAMING_EDIT_INTERVAL_MS : TELEGRAM_DEFAULT_NON_PRIVATE_STREAMING_EDIT_INTERVAL_MS;
22986
+ const intervalMs = Math.max(this.clampInteger(options?.updateIntervalMs, 0, 0, Number.MAX_SAFE_INTEGER), this.streamingEditIntervalMs ?? defaultIntervalMs);
22987
+ const placeholderText = options?.fallbackStreamingPlaceholderText === void 0 ? TELEGRAM_STREAM_PLACEHOLDER_TEXT : options.fallbackStreamingPlaceholderText;
22988
+ const renderer = new StreamingMarkdownRenderer();
22989
+ let accumulated = "";
22990
+ let posted = null;
22991
+ let editThreadId = threadId;
22992
+ let lastEditContent = "";
22993
+ let lastEditAt = 0;
22994
+ let blockedUntil = 0;
22995
+ let rateLimitError = null;
22996
+ if (placeholderText !== null) {
22997
+ posted = await this.postMessage(threadId, placeholderText);
22998
+ editThreadId = posted.threadId || threadId;
22999
+ lastEditContent = placeholderText;
23000
+ lastEditAt = Date.now();
23001
+ }
23002
+ const applyEdit = async (content) => {
23003
+ if (!posted) return;
23004
+ posted = await this.editMessage(editThreadId, posted.id, { markdown: content });
23005
+ editThreadId = posted.threadId || editThreadId;
23006
+ lastEditContent = content;
23007
+ lastEditAt = Date.now();
23008
+ blockedUntil = 0;
23009
+ rateLimitError = null;
23010
+ };
23011
+ const rememberRateLimit = (error) => {
23012
+ const retryAfterMs = Math.max(0, error.retryAfter ?? 1) * 1e3;
23013
+ blockedUntil = Math.max(blockedUntil, Date.now() + retryAfterMs);
23014
+ rateLimitError = error;
23015
+ };
23016
+ const shouldEdit = (content) => Boolean(posted) && content.trim().length > 0 && content !== lastEditContent;
23017
+ const flushEdit = async (content) => {
23018
+ if (!shouldEdit(content)) return;
23019
+ try {
23020
+ await applyEdit(content);
23021
+ } catch (error) {
23022
+ if (error instanceof AdapterRateLimitError) rememberRateLimit(error);
23023
+ this.logger.warn("Telegram stream edit failed", {
23024
+ error: String(error),
23025
+ threadId
23026
+ });
23027
+ }
23028
+ };
23029
+ const flushFinalEdit = async (content) => {
23030
+ if (!shouldEdit(content)) return;
23031
+ const blockedMs = Math.max(0, blockedUntil - Date.now());
23032
+ const pacingMs = Math.max(0, intervalMs - (Date.now() - lastEditAt));
23033
+ if (blockedMs > TELEGRAM_STREAM_FINAL_EDIT_RETRY_CAP_MS && rateLimitError) throw rateLimitError;
23034
+ await this.sleep(Math.max(blockedMs, pacingMs));
23035
+ try {
23036
+ await applyEdit(content);
23037
+ return;
23038
+ } catch (error) {
23039
+ if (!(error instanceof AdapterRateLimitError)) throw error;
23040
+ rememberRateLimit(error);
23041
+ const retryAfterMs = (error.retryAfter ?? 1) * 1e3;
23042
+ if (retryAfterMs > TELEGRAM_STREAM_FINAL_EDIT_RETRY_CAP_MS) throw error;
23043
+ await this.sleep(retryAfterMs);
23044
+ }
23045
+ await applyEdit(content);
23046
+ };
23047
+ for await (const chunk of textStream) {
23048
+ let text2 = null;
23049
+ if (typeof chunk === "string") text2 = chunk;
23050
+ else if (chunk.type === "markdown_text") text2 = chunk.text;
23051
+ if (text2 === null) continue;
23052
+ accumulated += text2;
23053
+ renderer.push(text2);
23054
+ if (posted) {
23055
+ if (Date.now() >= blockedUntil && Date.now() - lastEditAt >= intervalMs) await flushEdit(renderer.render());
23056
+ continue;
23057
+ }
23058
+ const initial = renderer.render();
23059
+ if (initial.trim()) {
23060
+ posted = await this.postMessage(threadId, { markdown: initial });
23061
+ editThreadId = posted.threadId || threadId;
23062
+ lastEditContent = initial;
23063
+ lastEditAt = Date.now();
23064
+ }
23065
+ }
23066
+ const finalContent = renderer.finish();
23067
+ if (posted) {
23068
+ await flushFinalEdit(finalContent);
23069
+ return posted;
23070
+ }
23071
+ if (!accumulated.trim()) throw new ValidationError("telegram", "Telegram streaming requires text content");
23072
+ return await this.postMessage(threadId, { markdown: accumulated });
23073
+ }
23074
+ async nativeDraftStream(threadId, textStream, options) {
22550
23075
  const parsedThread = this.resolveThreadId(threadId);
22551
23076
  const updateIntervalMs = this.clampInteger(options?.updateIntervalMs, TELEGRAM_DEFAULT_STREAM_UPDATE_INTERVAL_MS, 0, Number.MAX_SAFE_INTEGER);
22552
23077
  const renderer = new StreamingMarkdownRenderer();
@@ -22565,8 +23090,7 @@ var TelegramAdapter = class {
22565
23090
  let draftText = text2;
22566
23091
  if (streamUsesRich) try {
22567
23092
  await this.telegramFetch("sendRichMessageDraft", {
22568
- chat_id: parsedThread.chatId,
22569
- message_thread_id: parsedThread.messageThreadId,
23093
+ ...this.buildChatTargetParams(parsedThread),
22570
23094
  draft_id: draftId,
22571
23095
  rich_message: { markdown: text2 }
22572
23096
  });
@@ -22592,15 +23116,13 @@ var TelegramAdapter = class {
22592
23116
  }
22593
23117
  try {
22594
23118
  if (useMarkdown) await this.telegramFetch("sendMessageDraft", {
22595
- chat_id: parsedThread.chatId,
22596
- message_thread_id: parsedThread.messageThreadId,
23119
+ ...this.buildChatTargetParams(parsedThread),
22597
23120
  draft_id: draftId,
22598
23121
  text: draftText,
22599
23122
  parse_mode: toBotApiParseMode("MarkdownV2")
22600
23123
  });
22601
23124
  else await this.telegramFetch("sendMessageDraft", {
22602
- chat_id: parsedThread.chatId,
22603
- message_thread_id: parsedThread.messageThreadId,
23125
+ ...this.buildChatTargetParams(parsedThread),
22604
23126
  draft_id: draftId,
22605
23127
  text: draftText
22606
23128
  });
@@ -22612,8 +23134,7 @@ var TelegramAdapter = class {
22612
23134
  const plainDraftText = renderPlainText(accumulated);
22613
23135
  try {
22614
23136
  await this.telegramFetch("sendMessageDraft", {
22615
- chat_id: parsedThread.chatId,
22616
- message_thread_id: parsedThread.messageThreadId,
23137
+ ...this.buildChatTargetParams(parsedThread),
22617
23138
  draft_id: draftId,
22618
23139
  text: plainDraftText
22619
23140
  });
@@ -22637,9 +23158,10 @@ var TelegramAdapter = class {
22637
23158
  };
22638
23159
  const flushDraft = async () => {
22639
23160
  if (!draftStreamingEnabled) return;
22640
- let draftText = renderPlainText(accumulated);
23161
+ let draftText;
22641
23162
  if (streamUsesRich) draftText = truncateRichMarkdown(renderer.render());
22642
23163
  else if (streamUsesMarkdown) draftText = renderMarkdownText(renderer.render());
23164
+ else draftText = renderPlainText(accumulated);
22643
23165
  await sendDraft(draftText, streamUsesMarkdown);
22644
23166
  };
22645
23167
  for await (const chunk of textStream) {
@@ -22658,13 +23180,13 @@ var TelegramAdapter = class {
22658
23180
  const markdown = truncateRichMarkdown(finalMarkdown);
22659
23181
  try {
22660
23182
  const raw2 = await this.telegramFetch("sendRichMessage", {
22661
- chat_id: parsedThread.chatId,
22662
- message_thread_id: parsedThread.messageThreadId,
23183
+ ...this.buildChatTargetParams(parsedThread),
22663
23184
  rich_message: { markdown }
22664
23185
  });
22665
23186
  const resultingThreadId2 = this.encodeThreadId({
22666
23187
  chatId: String(raw2.chat.id),
22667
- messageThreadId: raw2.message_thread_id ?? parsedThread.messageThreadId
23188
+ messageThreadId: raw2.message_thread_id ?? parsedThread.messageThreadId,
23189
+ businessConnectionId: parsedThread.businessConnectionId
22668
23190
  });
22669
23191
  const formatted = this.formatConverter.toAst(accumulated);
22670
23192
  const message2 = this.parseTelegramMessage(raw2, resultingThreadId2, {
@@ -22687,7 +23209,8 @@ var TelegramAdapter = class {
22687
23209
  const raw = await this.sendRegularMessage(parsedThread, regularText, plainText, streamUsesMarkdown ? "MarkdownV2" : "plain", void 0, threadId);
22688
23210
  const resultingThreadId = this.encodeThreadId({
22689
23211
  chatId: String(raw.chat.id),
22690
- messageThreadId: raw.message_thread_id ?? parsedThread.messageThreadId
23212
+ messageThreadId: raw.message_thread_id ?? parsedThread.messageThreadId,
23213
+ businessConnectionId: parsedThread.businessConnectionId
22691
23214
  });
22692
23215
  const message = this.parseTelegramMessage(raw, resultingThreadId);
22693
23216
  this.cacheMessage(message);
@@ -22721,9 +23244,23 @@ var TelegramAdapter = class {
22721
23244
  }
22722
23245
  async fetchThread(threadId) {
22723
23246
  const parsedThread = this.resolveThreadId(threadId);
23247
+ const encodedThreadId = this.encodeThreadId(parsedThread);
23248
+ if (parsedThread.businessConnectionId) {
23249
+ const chat2 = await this.fetchBusinessChat(parsedThread, encodedThreadId);
23250
+ return {
23251
+ id: encodedThreadId,
23252
+ channelId: parsedThread.chatId,
23253
+ channelName: chat2 ? this.chatDisplayName(chat2) : void 0,
23254
+ isDM: true,
23255
+ metadata: {
23256
+ chat: chat2,
23257
+ businessConnectionId: parsedThread.businessConnectionId
23258
+ }
23259
+ };
23260
+ }
22724
23261
  const chat = await this.telegramFetch("getChat", { chat_id: parsedThread.chatId });
22725
23262
  return {
22726
- id: this.encodeThreadId(parsedThread),
23263
+ id: encodedThreadId,
22727
23264
  channelId: String(chat.id),
22728
23265
  channelName: this.chatDisplayName(chat),
22729
23266
  isDM: chat.type === "private",
@@ -22733,6 +23270,19 @@ var TelegramAdapter = class {
22733
23270
  }
22734
23271
  };
22735
23272
  }
23273
+ async fetchBusinessChat(thread, threadId) {
23274
+ const cachedChat = this.messageCache.get(threadId)?.at(-1)?.raw.chat;
23275
+ try {
23276
+ return await this.telegramFetch("getChat", { chat_id: thread.chatId });
23277
+ } catch (error) {
23278
+ if (!cachedChat) throw error;
23279
+ this.logger.debug("Telegram getChat failed for business thread, using cached chat", {
23280
+ error: String(error),
23281
+ threadId
23282
+ });
23283
+ return cachedChat;
23284
+ }
23285
+ }
22736
23286
  async fetchChannelInfo(channelId) {
22737
23287
  const chat = await this.telegramFetch("getChat", { chat_id: channelId });
22738
23288
  let memberCount;
@@ -22750,7 +23300,11 @@ var TelegramAdapter = class {
22750
23300
  };
22751
23301
  }
22752
23302
  channelIdFromThreadId(threadId) {
22753
- const { chatId } = this.resolveThreadId(threadId);
23303
+ const { chatId, businessConnectionId } = this.resolveThreadId(threadId);
23304
+ if (businessConnectionId) return this.encodeThreadId({
23305
+ chatId,
23306
+ businessConnectionId
23307
+ });
22754
23308
  return `telegram:${chatId}`;
22755
23309
  }
22756
23310
  async openDM(userId) {
@@ -22761,12 +23315,24 @@ var TelegramAdapter = class {
22761
23315
  return !chatId.startsWith("-");
22762
23316
  }
22763
23317
  encodeThreadId(platformData) {
23318
+ if (platformData.businessConnectionId) return `telegram:biz:${platformData.businessConnectionId}:${platformData.chatId}`;
22764
23319
  if (typeof platformData.messageThreadId === "number") return `telegram:${platformData.chatId}:${platformData.messageThreadId}`;
22765
23320
  return `telegram:${platformData.chatId}`;
22766
23321
  }
22767
23322
  decodeThreadId(threadId) {
22768
23323
  const parts = threadId.split(":");
22769
- if (parts[0] !== "telegram" || parts.length < 2 || parts.length > 3) throw new ValidationError("telegram", `Invalid Telegram thread ID: ${threadId}`);
23324
+ if (parts[0] !== "telegram") throw new ValidationError("telegram", `Invalid Telegram thread ID: ${threadId}`);
23325
+ if (parts[1] === "biz") {
23326
+ if (parts.length !== 4) throw new ValidationError("telegram", `Invalid Telegram business thread ID: ${threadId}`);
23327
+ const businessConnectionId = parts[2];
23328
+ const chatId2 = parts[3];
23329
+ if (!(businessConnectionId && chatId2)) throw new ValidationError("telegram", `Invalid Telegram business thread ID: ${threadId}`);
23330
+ return {
23331
+ chatId: chatId2,
23332
+ businessConnectionId
23333
+ };
23334
+ }
23335
+ if (parts.length < 2 || parts.length > 3) throw new ValidationError("telegram", `Invalid Telegram thread ID: ${threadId}`);
22770
23336
  const chatId = parts[1];
22771
23337
  if (!chatId) throw new ValidationError("telegram", `Invalid Telegram thread ID: ${threadId}`);
22772
23338
  const messageThreadPart = parts[2];
@@ -22792,11 +23358,12 @@ var TelegramAdapter = class {
22792
23358
  }
22793
23359
  parseTelegramMessage(raw, threadId, content) {
22794
23360
  const richMarkdown = raw.rich_message ? richMessageToMarkdown(raw.rich_message) : "";
22795
- const plainText = content?.text ?? raw.text ?? raw.caption ?? (raw.rich_message ? richMessageToText(raw.rich_message) : "");
23361
+ const plainText = content?.text ?? raw.text ?? raw.caption ?? (raw.sticker ? raw.sticker.emoji ?? raw.sticker.set_name ?? "sticker" : void 0) ?? describeNonFileContent(raw) ?? (raw.rich_message ? richMessageToText(raw.rich_message) : "");
22796
23362
  const entities = raw.entities ?? raw.caption_entities ?? [];
22797
23363
  const text2 = content?.text ? content.text : applyTelegramEntities(plainText, entities);
22798
23364
  let author;
22799
- if (raw.from) author = this.toAuthor(raw.from);
23365
+ if (raw.sender_business_bot) author = this.toAuthor(raw.sender_business_bot);
23366
+ else if (raw.from) author = this.toAuthor(raw.from);
22800
23367
  else if (raw.sender_chat) author = this.toReactionActorAuthor(raw.sender_chat);
22801
23368
  else {
22802
23369
  const fallbackName = this.chatDisplayName(raw.chat) ?? String(raw.chat.id);
@@ -22821,6 +23388,7 @@ var TelegramAdapter = class {
22821
23388
  editedAt: raw.edit_date !== void 0 ? /* @__PURE__ */ new Date(raw.edit_date * 1e3) : void 0
22822
23389
  },
22823
23390
  attachments: this.extractAttachments(raw),
23391
+ replyTo: raw.reply_to_message ? this.parseTelegramMessage(raw.reply_to_message, threadId) : void 0,
22824
23392
  isMention: this.isBotMentioned(raw, plainText)
22825
23393
  });
22826
23394
  }
@@ -22830,40 +23398,66 @@ var TelegramAdapter = class {
22830
23398
  if (photo) attachments.push(this.createAttachment("image", photo.file_id, {
22831
23399
  size: photo.file_size,
22832
23400
  width: photo.width,
22833
- height: photo.height
23401
+ height: photo.height,
23402
+ fileUniqueId: photo.file_unique_id,
23403
+ mimeType: "image/jpeg"
22834
23404
  }));
22835
23405
  if (raw.video) attachments.push(this.createAttachment("video", raw.video.file_id, {
22836
23406
  size: raw.video.file_size,
22837
23407
  width: raw.video.width,
22838
23408
  height: raw.video.height,
22839
23409
  name: raw.video.file_name,
22840
- mimeType: raw.video.mime_type
23410
+ mimeType: raw.video.mime_type,
23411
+ fileUniqueId: raw.video.file_unique_id
22841
23412
  }));
22842
23413
  if (raw.audio) attachments.push(this.createAttachment("audio", raw.audio.file_id, {
22843
23414
  size: raw.audio.file_size,
22844
23415
  name: raw.audio.file_name,
22845
- mimeType: raw.audio.mime_type
23416
+ mimeType: raw.audio.mime_type,
23417
+ fileUniqueId: raw.audio.file_unique_id
22846
23418
  }));
22847
23419
  if (raw.voice) attachments.push(this.createAttachment("audio", raw.voice.file_id, {
22848
23420
  size: raw.voice.file_size,
22849
- mimeType: raw.voice.mime_type
23421
+ mimeType: raw.voice.mime_type,
23422
+ fileUniqueId: raw.voice.file_unique_id
22850
23423
  }));
22851
- if (raw.document) attachments.push(this.createAttachment("file", raw.document.file_id, {
23424
+ if (raw.document && !raw.animation) attachments.push(this.createAttachment("file", raw.document.file_id, {
22852
23425
  size: raw.document.file_size,
22853
23426
  name: raw.document.file_name,
22854
- mimeType: raw.document.mime_type
23427
+ mimeType: raw.document.mime_type,
23428
+ fileUniqueId: raw.document.file_unique_id
22855
23429
  }));
22856
23430
  if (raw.video_note) attachments.push(this.createAttachment("video", raw.video_note.file_id, {
22857
23431
  size: raw.video_note.file_size,
22858
23432
  width: raw.video_note.length,
22859
- height: raw.video_note.length
23433
+ height: raw.video_note.length,
23434
+ fileUniqueId: raw.video_note.file_unique_id
23435
+ }));
23436
+ if (raw.animation) attachments.push(this.createAttachment("video", raw.animation.file_id, {
23437
+ size: raw.animation.file_size,
23438
+ width: raw.animation.width,
23439
+ height: raw.animation.height,
23440
+ name: raw.animation.file_name,
23441
+ mimeType: raw.animation.mime_type,
23442
+ fileUniqueId: raw.animation.file_unique_id
22860
23443
  }));
23444
+ if (raw.sticker) {
23445
+ const format = stickerAttachmentFormat(raw.sticker);
23446
+ attachments.push(this.createAttachment(format.type, raw.sticker.file_id, {
23447
+ size: raw.sticker.file_size,
23448
+ width: raw.sticker.width,
23449
+ height: raw.sticker.height,
23450
+ mimeType: format.mimeType,
23451
+ fileUniqueId: raw.sticker.file_unique_id
23452
+ }));
23453
+ }
22861
23454
  if (raw.rich_message) for (const media2 of richMessageMedia(raw.rich_message)) attachments.push(this.createAttachment(media2.type, media2.file.file_id, {
22862
23455
  size: media2.file.file_size,
22863
23456
  width: media2.width,
22864
23457
  height: media2.height,
22865
23458
  name: media2.name,
22866
- mimeType: media2.mimeType
23459
+ mimeType: media2.mimeType,
23460
+ fileUniqueId: media2.file.file_unique_id
22867
23461
  }));
22868
23462
  return attachments;
22869
23463
  }
@@ -22875,7 +23469,10 @@ var TelegramAdapter = class {
22875
23469
  height: metadata?.height,
22876
23470
  name: metadata?.name,
22877
23471
  mimeType: metadata?.mimeType,
22878
- fetchMetadata: { fileId },
23472
+ fetchMetadata: {
23473
+ fileId,
23474
+ ...metadata?.fileUniqueId ? { fileUniqueId: metadata.fileUniqueId } : {}
23475
+ },
22879
23476
  fetchData: async () => this.downloadFile(fileId)
22880
23477
  };
22881
23478
  }
@@ -22890,29 +23487,35 @@ var TelegramAdapter = class {
22890
23487
  async downloadFile(fileId) {
22891
23488
  const file = await this.telegramFetch("getFile", { file_id: fileId });
22892
23489
  if (!file.file_path) throw new ResourceNotFoundError("telegram", "file", fileId);
22893
- const fileUrl = `${this.apiBaseUrl}/file/bot${this.botToken}/${file.file_path}`;
23490
+ const botToken = this.staticBotToken ?? await this.resolveBotToken();
23491
+ const fileUrl = `${this.apiBaseUrl}/file/bot${botToken}/${file.file_path}`;
22894
23492
  let response;
22895
23493
  try {
22896
- response = await fetch(fileUrl);
23494
+ response = await fetch(fileUrl, { signal: AbortSignal.timeout(TELEGRAM_FILE_TIMEOUT_MS) });
22897
23495
  } catch (error) {
22898
23496
  throw new NetworkError("telegram", `Failed to download Telegram file ${fileId}`, error instanceof Error ? error : void 0);
22899
23497
  }
22900
23498
  if (!response.ok) throw new NetworkError("telegram", `Failed to download Telegram file ${fileId}: ${response.status}`);
22901
- return Buffer.from(await response.arrayBuffer());
23499
+ try {
23500
+ return await readTelegramFile(response, fileId);
23501
+ } catch (error) {
23502
+ if (error instanceof NetworkError) throw error;
23503
+ throw new NetworkError("telegram", `Failed to download Telegram file ${fileId}`, error instanceof Error ? error : void 0);
23504
+ }
22902
23505
  }
22903
- async sendDocument(thread, file, text2, plainText, replyMarkup, parseMode = "plain") {
23506
+ async sendDocument(thread, file, text2, plainText, replyMarkup, parseMode = "plain", replyParameters) {
22904
23507
  const buffer = await this.toTelegramBuffer(file.data);
22905
- return this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => this.telegramFetch("sendDocument", this.createTelegramDocumentFormData(thread, file, buffer, resolvedText, replyMarkup, resolvedParseMode)), {
23508
+ return this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => this.telegramFetch("sendDocument", this.createTelegramDocumentFormData(thread, file, buffer, resolvedText, replyMarkup, resolvedParseMode, replyParameters)), {
22906
23509
  initialText: text2,
22907
23510
  fallbackText: plainText,
22908
23511
  method: "sendDocument",
22909
23512
  threadId: this.encodeThreadId(thread)
22910
23513
  });
22911
23514
  }
22912
- createTelegramDocumentFormData(thread, file, buffer, text2, replyMarkup, parseMode = "plain") {
23515
+ createTelegramDocumentFormData(thread, file, buffer, text2, replyMarkup, parseMode = "plain", replyParameters) {
22913
23516
  const formData = new FormData();
22914
- formData.append("chat_id", thread.chatId);
22915
- if (typeof thread.messageThreadId === "number") formData.append("message_thread_id", String(thread.messageThreadId));
23517
+ this.appendChatTargetToFormData(formData, thread);
23518
+ this.appendReplyParameters(formData, replyParameters);
22916
23519
  if (text2.trim()) {
22917
23520
  formData.append("caption", truncateForTelegram(text2, TELEGRAM_CAPTION_LIMIT, parseMode));
22918
23521
  const botApiParseMode = toBotApiParseMode(parseMode);
@@ -22923,7 +23526,7 @@ var TelegramAdapter = class {
22923
23526
  if (replyMarkup) formData.append("reply_markup", JSON.stringify(replyMarkup));
22924
23527
  return formData;
22925
23528
  }
22926
- async sendAttachment(thread, attachment, text2, plainText, replyMarkup, parseMode = "plain") {
23529
+ async sendAttachment(thread, attachment, text2, plainText, replyMarkup, parseMode = "plain", replyParameters) {
22927
23530
  const upload = ATTACHMENT_UPLOADS[attachment.type];
22928
23531
  const data = attachment.data ?? (attachment.fetchData ? await attachment.fetchData() : void 0);
22929
23532
  if (!(data || attachment.url)) throw new ValidationError("telegram", `Attachment data or URL required for ${attachment.type}`);
@@ -22931,10 +23534,10 @@ var TelegramAdapter = class {
22931
23534
  return this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => {
22932
23535
  if (!buffer) {
22933
23536
  const payload = {
22934
- chat_id: thread.chatId,
22935
- [upload.field]: attachment.url
23537
+ ...this.buildChatTargetParams(thread),
23538
+ [upload.field]: attachment.url,
23539
+ reply_parameters: replyParameters
22936
23540
  };
22937
- if (typeof thread.messageThreadId === "number") payload.message_thread_id = thread.messageThreadId;
22938
23541
  if (resolvedText.trim()) {
22939
23542
  payload.caption = truncateForTelegram(resolvedText, TELEGRAM_CAPTION_LIMIT, resolvedParseMode);
22940
23543
  const botApiParseMode = toBotApiParseMode(resolvedParseMode);
@@ -22948,8 +23551,7 @@ var TelegramAdapter = class {
22948
23551
  return this.telegramFetch(upload.method, payload);
22949
23552
  }
22950
23553
  const formData = new FormData();
22951
- formData.append("chat_id", thread.chatId);
22952
- if (typeof thread.messageThreadId === "number") formData.append("message_thread_id", String(thread.messageThreadId));
23554
+ this.appendChatTargetToFormData(formData, thread);
22953
23555
  if (resolvedText.trim()) {
22954
23556
  formData.append("caption", truncateForTelegram(resolvedText, TELEGRAM_CAPTION_LIMIT, resolvedParseMode));
22955
23557
  const botApiParseMode = toBotApiParseMode(resolvedParseMode);
@@ -22962,6 +23564,7 @@ var TelegramAdapter = class {
22962
23564
  const blob = new Blob([new Uint8Array(buffer)], { type: attachment.mimeType ?? "application/octet-stream" });
22963
23565
  formData.append(upload.field, blob, attachment.name ?? "attachment");
22964
23566
  if (replyMarkup) formData.append("reply_markup", JSON.stringify(replyMarkup));
23567
+ this.appendReplyParameters(formData, replyParameters);
22965
23568
  return this.telegramFetch(upload.method, formData);
22966
23569
  }, {
22967
23570
  initialText: text2,
@@ -22970,7 +23573,7 @@ var TelegramAdapter = class {
22970
23573
  threadId: this.encodeThreadId(thread)
22971
23574
  });
22972
23575
  }
22973
- async sendDocumentMediaGroup(thread, files, text2, plainText, replyMarkup, parseMode = "plain") {
23576
+ async sendDocumentMediaGroup(thread, files, text2, plainText, replyMarkup, parseMode = "plain", replyParameters) {
22974
23577
  this.validateMediaGroupLength(files.length);
22975
23578
  if (replyMarkup) throw new ValidationError("telegram", "Telegram media groups do not support inline keyboards");
22976
23579
  const parts = [];
@@ -22981,14 +23584,14 @@ var TelegramAdapter = class {
22981
23584
  mimeType: file.mimeType,
22982
23585
  type: "document"
22983
23586
  });
22984
- return this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => this.telegramFetch("sendMediaGroup", this.createTelegramMediaGroupFormData(thread, parts, resolvedText, resolvedParseMode)), {
23587
+ return this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => this.telegramFetch("sendMediaGroup", this.createTelegramMediaGroupFormData(thread, parts, resolvedText, resolvedParseMode, replyParameters)), {
22985
23588
  initialText: text2,
22986
23589
  fallbackText: plainText,
22987
23590
  method: "sendMediaGroup",
22988
23591
  threadId: this.encodeThreadId(thread)
22989
23592
  });
22990
23593
  }
22991
- async sendAttachmentMediaGroup(thread, attachments, text2, plainText, replyMarkup, parseMode = "plain") {
23594
+ async sendAttachmentMediaGroup(thread, attachments, text2, plainText, replyMarkup, parseMode = "plain", replyParameters) {
22992
23595
  this.validateMediaGroupLength(attachments.length);
22993
23596
  this.validateAttachmentMediaGroupTypes(attachments);
22994
23597
  if (replyMarkup) throw new ValidationError("telegram", "Telegram media groups do not support inline keyboards");
@@ -23009,17 +23612,17 @@ var TelegramAdapter = class {
23009
23612
  width: attachment.width
23010
23613
  });
23011
23614
  }
23012
- return this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => this.telegramFetch("sendMediaGroup", this.createTelegramMediaGroupFormData(thread, parts, resolvedText, resolvedParseMode)), {
23615
+ return this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => this.telegramFetch("sendMediaGroup", this.createTelegramMediaGroupFormData(thread, parts, resolvedText, resolvedParseMode, replyParameters)), {
23013
23616
  initialText: text2,
23014
23617
  fallbackText: plainText,
23015
23618
  method: "sendMediaGroup",
23016
23619
  threadId: this.encodeThreadId(thread)
23017
23620
  });
23018
23621
  }
23019
- createTelegramMediaGroupFormData(thread, parts, text2, parseMode) {
23622
+ createTelegramMediaGroupFormData(thread, parts, text2, parseMode, replyParameters) {
23020
23623
  const formData = new FormData();
23021
- formData.append("chat_id", thread.chatId);
23022
- if (typeof thread.messageThreadId === "number") formData.append("message_thread_id", String(thread.messageThreadId));
23624
+ this.appendChatTargetToFormData(formData, thread);
23625
+ this.appendReplyParameters(formData, replyParameters);
23023
23626
  const captionIndex = 0;
23024
23627
  const botApiParseMode = toBotApiParseMode(parseMode);
23025
23628
  const media2 = parts.map((part, index) => {
@@ -23121,9 +23724,45 @@ var TelegramAdapter = class {
23121
23724
  if (value.startsWith("telegram:")) return this.decodeThreadId(value);
23122
23725
  return { chatId: value };
23123
23726
  }
23727
+ /**
23728
+ * Bot API chat-target fields (`chat_id`, `message_thread_id`, and optionally
23729
+ * `business_connection_id`) derived from a decoded thread.
23730
+ */
23731
+ buildChatTargetParams(thread) {
23732
+ const params = { chat_id: thread.chatId };
23733
+ if (typeof thread.messageThreadId === "number") params.message_thread_id = thread.messageThreadId;
23734
+ if (thread.businessConnectionId) params.business_connection_id = thread.businessConnectionId;
23735
+ return params;
23736
+ }
23737
+ appendChatTargetToFormData(formData, thread) {
23738
+ formData.append("chat_id", thread.chatId);
23739
+ if (typeof thread.messageThreadId === "number") formData.append("message_thread_id", String(thread.messageThreadId));
23740
+ if (thread.businessConnectionId) formData.append("business_connection_id", thread.businessConnectionId);
23741
+ }
23124
23742
  encodeMessageId(chatId, messageId) {
23125
23743
  return `${chatId}:${messageId}`;
23126
23744
  }
23745
+ /**
23746
+ * Build Bot API `reply_parameters` for an optional reply target.
23747
+ *
23748
+ * `allow_sending_without_reply` keeps delivery working when the target was
23749
+ * deleted in the meantime: the message arrives unthreaded instead of the
23750
+ * send failing outright. The same applies to a message id that never
23751
+ * existed in the chat or lives in another forum topic — only the chat half
23752
+ * of a composite target is validated here, so those deliver unthreaded
23753
+ * without an error.
23754
+ */
23755
+ buildReplyParameters(replyToMessageId, expectedChatId) {
23756
+ if (!replyToMessageId) return;
23757
+ const { messageId } = this.decodeCompositeMessageId(replyToMessageId, expectedChatId);
23758
+ return {
23759
+ message_id: messageId,
23760
+ allow_sending_without_reply: true
23761
+ };
23762
+ }
23763
+ appendReplyParameters(formData, replyParameters) {
23764
+ if (replyParameters) formData.append("reply_parameters", JSON.stringify(replyParameters));
23765
+ }
23127
23766
  decodeCompositeMessageId(messageId, expectedChatId) {
23128
23767
  const compositeMatch = messageId.match(MESSAGE_ID_PATTERN);
23129
23768
  if (compositeMatch) {
@@ -23137,8 +23776,8 @@ var TelegramAdapter = class {
23137
23776
  };
23138
23777
  }
23139
23778
  if (!expectedChatId) throw new ValidationError("telegram", `Telegram message ID must be in <chatId>:<messageId> format, got: ${messageId}`);
23779
+ if (!BARE_MESSAGE_ID_PATTERN.test(messageId)) throw new ValidationError("telegram", `Invalid Telegram message ID: ${messageId}`);
23140
23780
  const parsedMessageId = Number.parseInt(messageId, 10);
23141
- if (!Number.isFinite(parsedMessageId)) throw new ValidationError("telegram", `Invalid Telegram message ID: ${messageId}`);
23142
23781
  return {
23143
23782
  chatId: expectedChatId,
23144
23783
  messageId: parsedMessageId,
@@ -23172,6 +23811,7 @@ var TelegramAdapter = class {
23172
23811
  return chat.username;
23173
23812
  }
23174
23813
  isBotMentioned(message, text2) {
23814
+ if (this.mentionOnReply && this._botUserId && message.reply_to_message?.from && String(message.reply_to_message.from.id) === this._botUserId && message.reply_to_message.message_id !== message.message_thread_id && !(message.from && String(message.from.id) === this._botUserId)) return true;
23175
23815
  if (!text2) return false;
23176
23816
  const username = this._userName;
23177
23817
  const entities = message.entities ?? message.caption_entities ?? [];
@@ -23184,7 +23824,14 @@ var TelegramAdapter = class {
23184
23824
  if (this.entityText(text2, entity).toLowerCase().endsWith(`@${username.toLowerCase()}`)) return true;
23185
23825
  }
23186
23826
  }
23187
- return new RegExp(`@${this.escapeRegex(username)}(?![\\w-])`, "i").test(text2);
23827
+ return this.getMentionRegex(username).test(text2);
23828
+ }
23829
+ getMentionRegex(username) {
23830
+ if (!this._mentionRegex || this._mentionRegexUsername !== username) {
23831
+ this._mentionRegexUsername = username;
23832
+ this._mentionRegex = new RegExp(`@${this.escapeRegex(username)}(?![\\w-])`, "i");
23833
+ }
23834
+ return this._mentionRegex;
23188
23835
  }
23189
23836
  entityText(text2, entity) {
23190
23837
  return text2.slice(entity.offset, entity.offset + entity.length);
@@ -23230,13 +23877,13 @@ var TelegramAdapter = class {
23230
23877
  resolveTelegramFallbackText(originalText, fallbackText) {
23231
23878
  return fallbackText.trim() ? fallbackText : originalText;
23232
23879
  }
23233
- async sendRegularMessage(thread, text2, plainText, parseMode, replyMarkup, threadId) {
23880
+ async sendRegularMessage(thread, text2, plainText, parseMode, replyMarkup, threadId, replyParameters) {
23234
23881
  return this.withTelegramMarkdownFallback(parseMode, (resolvedParseMode, resolvedText) => this.telegramFetch("sendMessage", {
23235
- chat_id: thread.chatId,
23236
- message_thread_id: thread.messageThreadId,
23882
+ ...this.buildChatTargetParams(thread),
23237
23883
  text: resolvedText,
23238
23884
  reply_markup: replyMarkup,
23239
- parse_mode: toBotApiParseMode(resolvedParseMode)
23885
+ parse_mode: toBotApiParseMode(resolvedParseMode),
23886
+ reply_parameters: replyParameters
23240
23887
  }), {
23241
23888
  initialText: text2,
23242
23889
  fallbackText: plainText,
@@ -23248,7 +23895,8 @@ var TelegramAdapter = class {
23248
23895
  const message = error instanceof ValidationError ? error.message.toLowerCase() : "";
23249
23896
  const missingMethod = message.includes("method") && message.includes("not found");
23250
23897
  const unsupportedRich = message.includes("rich message") && message.includes("unsupported");
23251
- return method.startsWith("sendRichMessage") && error instanceof ResourceNotFoundError || error instanceof ValidationError && (message.includes("can't parse") || missingMethod || unsupportedRich);
23898
+ const rejectedReplyParameters = message.includes("reply_parameters");
23899
+ return method.startsWith("sendRichMessage") && error instanceof ResourceNotFoundError || error instanceof ValidationError && (message.includes("can't parse") || missingMethod || unsupportedRich || rejectedReplyParameters);
23252
23900
  }
23253
23901
  rememberRichMessageFailure(error, method) {
23254
23902
  const message = error instanceof ValidationError ? error.message.toLowerCase() : "";
@@ -23301,6 +23949,11 @@ var TelegramAdapter = class {
23301
23949
  timeout: config.timeout
23302
23950
  }, { signal: this.pollingAbortController.signal });
23303
23951
  consecutiveFailures = 0;
23952
+ if (updates.length > 0 && !this.webhookScope) try {
23953
+ await this.ensureBotIdentity();
23954
+ } catch (error) {
23955
+ this.logger.warn("Telegram polling could not resolve bot identity", { error: String(error) });
23956
+ }
23304
23957
  for (const update of updates) {
23305
23958
  offset = update.update_id + 1;
23306
23959
  try {
@@ -23322,7 +23975,7 @@ var TelegramAdapter = class {
23322
23975
  consecutiveFailures
23323
23976
  });
23324
23977
  if (!this.pollingActive) return;
23325
- await this.sleep(backoffMs);
23978
+ await this.sleep(backoffMs, this.pollingAbortController?.signal);
23326
23979
  } finally {
23327
23980
  this.pollingAbortController = null;
23328
23981
  }
@@ -23334,7 +23987,7 @@ var TelegramAdapter = class {
23334
23987
  ...override
23335
23988
  };
23336
23989
  return {
23337
- allowedUpdates: merged.allowedUpdates && merged.allowedUpdates.length > 0 ? [...merged.allowedUpdates] : void 0,
23990
+ allowedUpdates: this.resolveAllowedUpdates(merged.allowedUpdates),
23338
23991
  deleteWebhook: merged.deleteWebhook ?? true,
23339
23992
  dropPendingUpdates: merged.dropPendingUpdates ?? false,
23340
23993
  limit: this.clampInteger(merged.limit, TELEGRAM_DEFAULT_POLLING_LIMIT, TELEGRAM_MIN_POLLING_LIMIT, TELEGRAM_MAX_POLLING_LIMIT),
@@ -23342,6 +23995,11 @@ var TelegramAdapter = class {
23342
23995
  timeout: this.clampInteger(merged.timeout, TELEGRAM_DEFAULT_POLLING_TIMEOUT_SECONDS, TELEGRAM_MIN_POLLING_TIMEOUT_SECONDS, TELEGRAM_MAX_POLLING_TIMEOUT_SECONDS)
23343
23996
  };
23344
23997
  }
23998
+ resolveAllowedUpdates(allowedUpdates) {
23999
+ if (!this.businessMode) return allowedUpdates && allowedUpdates.length > 0 ? [...allowedUpdates] : void 0;
24000
+ const base = allowedUpdates && allowedUpdates.length > 0 ? allowedUpdates : TELEGRAM_DEFAULT_ALLOWED_UPDATES;
24001
+ return [.../* @__PURE__ */ new Set([...base, ...TELEGRAM_BUSINESS_ALLOWED_UPDATES])];
24002
+ }
23345
24003
  clampInteger(value, fallback, min, max) {
23346
24004
  if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
23347
24005
  return Math.max(min, Math.min(max, Math.trunc(value)));
@@ -23349,14 +24007,24 @@ var TelegramAdapter = class {
23349
24007
  isAbortError(error) {
23350
24008
  return error instanceof Error && error.name === "AbortError";
23351
24009
  }
23352
- async sleep(delayMs) {
23353
- if (delayMs <= 0) return;
24010
+ async sleep(delayMs, signal) {
24011
+ if (delayMs <= 0 || signal?.aborted) return;
23354
24012
  await new Promise((resolve) => {
23355
- setTimeout(resolve, delayMs);
24013
+ const timeoutId = setTimeout(() => {
24014
+ signal?.removeEventListener("abort", onAbort);
24015
+ resolve();
24016
+ }, delayMs);
24017
+ const onAbort = () => {
24018
+ clearTimeout(timeoutId);
24019
+ signal?.removeEventListener("abort", onAbort);
24020
+ resolve();
24021
+ };
24022
+ signal?.addEventListener("abort", onAbort, { once: true });
23356
24023
  });
23357
24024
  }
23358
24025
  async telegramFetch(method, payload, request) {
23359
- const url = `${this.apiBaseUrl}/bot${this.botToken}/${method}`;
24026
+ const botToken = this.staticBotToken ?? await this.resolveBotToken();
24027
+ const url = `${this.apiBaseUrl}/bot${botToken}/${method}`;
23360
24028
  let response;
23361
24029
  try {
23362
24030
  response = await fetch(url, {