@xopcai/xopc 0.0.464 → 0.0.465

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.
Files changed (119) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/feishu/src/adapters/cli-login.js +23 -49
  3. package/dist/extensions/feishu/src/adapters/gateway-setup.d.ts +3 -0
  4. package/dist/extensions/feishu/src/adapters/gateway-setup.js +180 -128
  5. package/dist/extensions/feishu/src/adapters/onboard-cli.d.ts +1 -1
  6. package/dist/extensions/feishu/src/adapters/onboard-cli.js +27 -15
  7. package/dist/extensions/feishu/src/auth/app-registration.d.ts +1 -0
  8. package/dist/extensions/feishu/src/auth/app-registration.js +12 -9
  9. package/dist/extensions/feishu/src/outbound/outbound-adapter.js +40 -16
  10. package/dist/extensions/feishu/src/plugin.d.ts +2 -0
  11. package/dist/extensions/feishu/src/plugin.js +37 -23
  12. package/dist/extensions/feishu/src/status/status-adapter.d.ts +1 -1
  13. package/dist/extensions/feishu/src/status/status-adapter.js +8 -5
  14. package/dist/extensions/feishu/src/streaming/streaming-adapter.js +97 -69
  15. package/dist/extensions/feishu/src/transport/client/bot-info.d.ts +10 -0
  16. package/dist/extensions/feishu/src/transport/client/bot-info.js +34 -0
  17. package/dist/extensions/feishu/src/transport/client/client.d.ts +7 -1
  18. package/dist/extensions/feishu/src/transport/client/client.js +6 -5
  19. package/dist/extensions/feishu/src/transport/client/install-sdk.d.ts +2 -0
  20. package/dist/extensions/feishu/src/transport/client/install-sdk.js +77 -0
  21. package/dist/extensions/feishu/src/transport/client/lark-sdk.d.ts +2 -0
  22. package/dist/extensions/feishu/src/transport/client/lark-sdk.js +27 -3
  23. package/dist/extensions/feishu/src/transport/client/sdk-catalog.d.ts +1 -0
  24. package/dist/extensions/feishu/src/transport/client/sdk-catalog.js +317 -0
  25. package/dist/extensions/feishu/src/transport/reliability/inbound-pipeline.d.ts +1 -1
  26. package/dist/extensions/feishu/src/transport/reliability/inbound-pipeline.js +13 -5
  27. package/dist/extensions/feishu/src/transport/reliability/message-ingress.d.ts +21 -0
  28. package/dist/extensions/feishu/src/transport/reliability/message-ingress.js +313 -0
  29. package/dist/extensions/feishu/src/transport/socket-mode/monitor.d.ts +1 -0
  30. package/dist/extensions/feishu/src/transport/socket-mode/monitor.js +56 -171
  31. package/dist/extensions/feishu/src/transport/webhook/monitor.d.ts +1 -0
  32. package/dist/extensions/feishu/src/transport/webhook/monitor.js +10 -102
  33. package/dist/extensions/telegram/src/account-manager.d.ts +1 -0
  34. package/dist/extensions/telegram/src/account-manager.js +3 -0
  35. package/dist/extensions/telegram/src/adapters/debounce-keys.js +7 -2
  36. package/dist/extensions/telegram/src/adapters/gateway-setup.js +113 -63
  37. package/dist/extensions/telegram/src/adapters/streaming-adapter.js +8 -4
  38. package/dist/extensions/telegram/src/doctor.js +1 -1
  39. package/dist/extensions/telegram/src/inbound-coalescer.d.ts +8 -6
  40. package/dist/extensions/telegram/src/inbound-coalescer.js +47 -88
  41. package/dist/extensions/telegram/src/inbound-processor.js +5 -1
  42. package/dist/extensions/telegram/src/outbound-sender.js +16 -23
  43. package/dist/extensions/telegram/src/plugin.js +80 -57
  44. package/dist/extensions/telegram/src/polling-session.d.ts +3 -6
  45. package/dist/extensions/telegram/src/polling-session.js +107 -94
  46. package/dist/extensions/telegram/src/rich-message.d.ts +4 -0
  47. package/dist/extensions/telegram/src/rich-message.js +23 -0
  48. package/dist/extensions/telegram/src/timeout-abort.d.ts +1 -1
  49. package/dist/extensions/telegram/src/timeout-abort.js +9 -3
  50. package/dist/extensions/telegram/src/update-offset-store.d.ts +1 -0
  51. package/dist/extensions/telegram/src/update-offset-store.js +6 -1
  52. package/dist/extensions/telegram/xopc.extension.json +1 -1
  53. package/dist/extensions/weixin/src/api/api.d.ts +1 -0
  54. package/dist/extensions/weixin/src/api/api.js +12 -6
  55. package/dist/extensions/weixin/src/api/types.d.ts +5 -2
  56. package/dist/extensions/weixin/src/auth/login-qr.d.ts +7 -1
  57. package/dist/extensions/weixin/src/auth/login-qr.js +48 -13
  58. package/dist/extensions/weixin/src/cdn/pic-decrypt.d.ts +2 -2
  59. package/dist/extensions/weixin/src/cdn/pic-decrypt.js +37 -25
  60. package/dist/extensions/weixin/src/cli/gateway-qr-login.d.ts +8 -0
  61. package/dist/extensions/weixin/src/cli/gateway-qr-login.js +45 -6
  62. package/dist/extensions/weixin/src/cli/qr-login.d.ts +1 -1
  63. package/dist/extensions/weixin/src/cli/qr-login.js +9 -3
  64. package/dist/extensions/weixin/src/media/media-download.d.ts +1 -0
  65. package/dist/extensions/weixin/src/media/media-download.js +4 -5
  66. package/dist/extensions/weixin/src/messaging/process-message.d.ts +2 -0
  67. package/dist/extensions/weixin/src/messaging/process-message.js +90 -65
  68. package/dist/extensions/weixin/src/messaging/quote-cache.d.ts +10 -0
  69. package/dist/extensions/weixin/src/messaging/quote-cache.js +46 -0
  70. package/dist/extensions/weixin/src/monitor/monitor.d.ts +3 -3
  71. package/dist/extensions/weixin/src/monitor/monitor.js +108 -104
  72. package/dist/extensions/weixin/src/plugin.d.ts +5 -1
  73. package/dist/extensions/weixin/src/plugin.js +138 -42
  74. package/dist/gateway/static/root/assets/{capabilities-page-rTjkjo71.js → capabilities-page-U_hQx5ou.js} +2 -2
  75. package/dist/gateway/static/root/assets/channels-BUzno8Pi.js +1 -0
  76. package/dist/gateway/static/root/assets/extension-settings-page-BvUtZGLT.js +1 -0
  77. package/dist/gateway/static/root/assets/index-Cdo4_zon.js +11 -0
  78. package/dist/gateway/static/root/assets/index-DYTktubl.css +1 -0
  79. package/dist/gateway/static/root/assets/{route-preload-5iwjWERk.js → route-preload-ClsAFFQc.js} +2 -2
  80. package/dist/gateway/static/root/assets/schema-form-BxBDgLrg.js +1 -0
  81. package/dist/gateway/static/root/assets/{settings-page-DNiRlM5x.js → settings-page-M6XwzIyu.js} +1 -1
  82. package/dist/gateway/static/root/assets/understanding-refresh-store-CM6bUcaJ.js +1 -0
  83. package/dist/gateway/static/root/assets/user-model-page-CBcGMhrR.js +2 -0
  84. package/dist/gateway/static/root/index.html +4 -4
  85. package/dist/package.js +1 -1
  86. package/dist/src/agent/inbound/inbound-loop.js +14 -0
  87. package/dist/src/agent/messaging/outbound-coordinator.js +1 -1
  88. package/dist/src/channels/connection-probe.d.ts +23 -0
  89. package/dist/src/channels/connection-probe.js +98 -0
  90. package/dist/src/channels/manager.d.ts +2 -0
  91. package/dist/src/channels/manager.js +5 -0
  92. package/dist/src/channels/message-journal.d.ts +25 -0
  93. package/dist/src/channels/message-journal.js +79 -0
  94. package/dist/src/channels/outbound-sender.d.ts +8 -0
  95. package/dist/src/channels/outbound-sender.js +60 -1
  96. package/dist/src/channels/plugins/types.adapters.d.ts +4 -0
  97. package/dist/src/channels/verified-inbound.js +20 -14
  98. package/dist/src/gateway/hono/routes/channels.js +23 -10
  99. package/dist/src/gateway/hono/routes/home.js +1 -1
  100. package/dist/src/gateway/hono/routes/user-model.js +48 -20
  101. package/dist/src/gateway/service.js +5 -5
  102. package/dist/src/home-intelligence/host.js +5 -5
  103. package/dist/src/infra/bus/index.d.ts +1 -1
  104. package/dist/src/infra/bus/queue.d.ts +16 -3
  105. package/dist/src/infra/bus/queue.js +74 -3
  106. package/dist/src/infra/debounce.d.ts +1 -0
  107. package/dist/src/infra/debounce.js +40 -35
  108. package/dist/src/knowledge-memory/index.js +2 -2
  109. package/dist/src/knowledge-memory/repository.d.ts +9 -0
  110. package/dist/src/knowledge-memory/repository.js +12 -2
  111. package/dist/src/runtime-tools/types.d.ts +1 -1
  112. package/package.json +5 -6
  113. package/dist/gateway/static/root/assets/channels-DvB2fwPI.js +0 -1
  114. package/dist/gateway/static/root/assets/extension-settings-page-DKAJE4h9.js +0 -1
  115. package/dist/gateway/static/root/assets/index-BGA-G-Bp.css +0 -1
  116. package/dist/gateway/static/root/assets/index-pmlYYCCU.js +0 -11
  117. package/dist/gateway/static/root/assets/schema-form-C9TYGa0_.js +0 -1
  118. package/dist/gateway/static/root/assets/understanding-refresh-store-Cf0DUO_C.js +0 -1
  119. package/dist/gateway/static/root/assets/user-model-page-CdB9qH57.js +0 -2
@@ -4,6 +4,7 @@ import { resolveRoute } from "../../../src/routing/resolve-route.js";
4
4
  import { checkMentionInTranscription } from "../../../src/voice/stt/mention.js";
5
5
  import { normalizeTelegramCommandName, parseSlashCommand } from "../../../src/chat-commands/command-parse.js";
6
6
  import { answerClarificationTextFromChannel } from "../../../src/gateway/clarify-runtime.js";
7
+ import { telegramInboundScope } from "./update-offset-store.js";
7
8
  import { buildTelegramUpdateKey, telegramUpdateDedupe } from "./dedupe.js";
8
9
  import "../../../src/routing/index.js";
9
10
  import { resolveTelegramGroupContext } from "./group-config-resolver.js";
@@ -365,7 +366,10 @@ function createInboundProcessor(deps) {
365
366
  transcribedVoice: !!transcribedText || void 0
366
367
  },
367
368
  attachments: attachments.length > 0 ? attachments : void 0
368
- });
369
+ }, bot?.token ? {
370
+ scope: telegramInboundScope(accountId, bot.token),
371
+ id: JSON.stringify([chatId, message.message_id])
372
+ } : void 0);
369
373
  };
370
374
  return (ctx, accountId) => {
371
375
  const message = ctx.message;
@@ -1,12 +1,13 @@
1
1
  import { createLogger } from "../../../src/utils/logger/index.js";
2
2
  import { init_logger } from "../../../src/utils/logger.js";
3
- import { createRetryRunner, isRecoverableNetworkError } from "../../../src/infra/retry.js";
3
+ import { createRetryRunner } from "../../../src/infra/retry.js";
4
4
  import { buildSendOptions, parseDataUrl, resolveMediaMethod } from "./send-options.js";
5
5
  import { splitTelegramCaption } from "./caption.js";
6
6
  import { markdownToTelegramChunks, renderTelegramHtmlText } from "./format.js";
7
7
  import { sentMessageCache } from "./sent-cache.js";
8
+ import { sendTelegramRichMessage } from "./rich-message.js";
8
9
  import { isTelegramHtmlParseError } from "./errors.js";
9
- import { InputFile } from "grammy";
10
+ import { GrammyError, InputFile } from "grammy";
10
11
  //#region extensions/telegram/src/outbound-sender.ts
11
12
  init_logger();
12
13
  const log = createLogger("TelegramOutboundSender");
@@ -211,37 +212,29 @@ function createOutboundSender(deps) {
211
212
  attempts: 3,
212
213
  minDelayMs: 300,
213
214
  maxDelayMs: 5e3,
214
- shouldRetry: (err) => isRecoverableNetworkError(err, "send")
215
+ shouldRetry: (err) => err instanceof GrammyError && err.error_code === 429,
216
+ retryAfterMs: (err) => err instanceof GrammyError ? (err.parameters.retry_after ?? 0) * 1e3 : void 0
215
217
  });
216
- const sendFirstChunk = async () => {
218
+ const rich = await retryRunner(() => sendTelegramRichMessage(bot.api, chatId, content, options), "sendRichMessage");
219
+ if (rich !== void 0) return rich;
220
+ if (!chunks.length) return 0;
221
+ const sendChunk = async (chunk, replyToMessageId) => {
217
222
  const sendOptions = buildSendOptions({
218
- threadId: options?.threadId,
219
- replyToMessageId: options?.replyToMessageId,
220
- silent: options?.silent
223
+ ...options,
224
+ replyToMessageId
221
225
  });
222
226
  try {
223
- return (await bot.api.sendMessage(chatId, chunks[0].html, {
227
+ return (await bot.api.sendMessage(chatId, chunk.html, {
224
228
  ...sendOptions,
225
229
  parse_mode: "HTML"
226
230
  })).message_id;
227
231
  } catch (err) {
228
- if (isTelegramHtmlParseError(err)) {
229
- log.warn({
230
- chatId,
231
- err
232
- }, "HTML parse error, retrying with plain text");
233
- return (await bot.api.sendMessage(chatId, chunks[0].text, { reply_to_message_id: options?.replyToMessageId ? parseInt(options.replyToMessageId, 10) : void 0 })).message_id;
234
- }
235
- throw err;
232
+ if (!isTelegramHtmlParseError(err)) throw err;
233
+ return (await bot.api.sendMessage(chatId, chunk.text, sendOptions)).message_id;
236
234
  }
237
235
  };
238
- const firstMessageId = await retryRunner(sendFirstChunk, "sendMessage");
239
- for (let i = 1; i < chunks.length; i++) await retryRunner(async () => {
240
- await bot.api.sendMessage(chatId, chunks[i].html, {
241
- parse_mode: "HTML",
242
- reply_to_message_id: firstMessageId
243
- });
244
- }, `sendMessage-reply-${i}`);
236
+ const firstMessageId = await retryRunner(() => sendChunk(chunks[0], options?.replyToMessageId), "sendMessage");
237
+ for (const chunk of chunks.slice(1)) await retryRunner(() => sendChunk(chunk, String(firstMessageId)), "sendMessage");
245
238
  return firstMessageId;
246
239
  }
247
240
  return { send };
@@ -7,6 +7,7 @@ import { issuePairingChallenge } from "../../../src/channels/pairing/pairing-cha
7
7
  import { createStandardPairingAdapter } from "../../../src/channels/pairing/pairing-store-adapter.js";
8
8
  import { registerChannelExecApprovalHandler } from "../../../src/channels/exec-approval-runtime.js";
9
9
  import { generateConversationId } from "../../../src/chat-commands/session-key.js";
10
+ import { handleChannelConnectionProbe } from "../../../src/channels/connection-probe.js";
10
11
  import "./pairing-config-resolver.js";
11
12
  import { answerClarificationChoiceFromChannel, answerClarificationDecisionFromChannel } from "../../../src/gateway/clarify-runtime.js";
12
13
  import { createTimeoutAbortSignal } from "./timeout-abort.js";
@@ -15,6 +16,7 @@ import { getMimeType } from "../../../src/channels/media.js";
15
16
  import { TelegramAccountManager } from "./account-manager.js";
16
17
  import { createOutboundSender } from "./outbound-sender.js";
17
18
  import { createTelegramCommandHandler } from "./command-handler.js";
19
+ import { telegramInboundScope } from "./update-offset-store.js";
18
20
  import { handleTelegramFocusCommand } from "./focus-handler.js";
19
21
  import { createInboundProcessor } from "./inbound-processor.js";
20
22
  import { TELEGRAM_CHANNEL_DEFAULTS } from "./plugin-defaults.js";
@@ -30,12 +32,12 @@ import { createTelegramCommandAdapter } from "./adapters/command-adapter.js";
30
32
  import "./channel.js";
31
33
  import { normalizeTelegramDeliveryChatId } from "./delivery-chat-id.js";
32
34
  import { telegramOnboardAdapter } from "./adapters/onboard-cli.js";
35
+ import { createProxyFetch } from "./proxy-fetch.js";
33
36
  import { telegramGatewaySetupActions } from "./adapters/gateway-setup.js";
34
37
  import { normalizeTelegramApiRoot } from "./api-root.js";
35
38
  import { resolveTelegramBotToken } from "./token-resolver.js";
36
39
  import { formatTelegramStartupError, isTelegramUnauthorizedTokenError } from "./startup-errors.js";
37
40
  import { startTelegramPollingSession } from "./polling-session.js";
38
- import { createProxyFetch } from "./proxy-fetch.js";
39
41
  import { runTelegramDoctorChecks } from "./doctor.js";
40
42
  import { createTelegramInboundCoalescer } from "./inbound-coalescer.js";
41
43
  import { handleTelegramMessageReaction, sendTelegramAckReaction } from "./reactions.js";
@@ -320,7 +322,7 @@ var TelegramChannelPlugin = class {
320
322
  }
321
323
  }
322
324
  async startAccount(account) {
323
- if (this.accountManager.isRunning(account.accountId)) return;
325
+ if (this.accountManager.hasPollingSession(account.accountId) || this.accountManager.isStarting(account.accountId)) return;
324
326
  const resolved = resolveTelegramBotToken({
325
327
  botToken: account.botToken,
326
328
  tokenFile: account.tokenFile
@@ -361,24 +363,33 @@ var TelegramChannelPlugin = class {
361
363
  } finally {
362
364
  getMeSignal.dispose();
363
365
  }
366
+ bot.botInfo = me;
364
367
  this.accountManager.registerBot(account.accountId, bot);
365
368
  this.accountManager.setBotUsername(account.accountId, me.username);
366
369
  this.setupMessageHandler(account.accountId, bot);
370
+ this.bus.restoreDurableInbound?.(this.id, telegramInboundScope(account.accountId, resolved.token));
367
371
  const session = startTelegramPollingSession({
368
372
  accountId: account.accountId,
369
373
  botToken: resolved.token,
370
374
  bot,
371
375
  stallThresholdMs: account.pollingStallThresholdMs,
372
- onExit: () => {
373
- this.accountManager.stopRunner(account.accountId);
376
+ onPoll: () => this.accountManager.updateStatus({
377
+ accountId: account.accountId,
378
+ running: true,
379
+ mode: "polling"
380
+ }),
381
+ onExit: (err) => {
382
+ this.accountManager.stopRunner(account.accountId).then(() => {
383
+ this.accountManager.updateStatus({
384
+ accountId: account.accountId,
385
+ running: false,
386
+ mode: "stopped",
387
+ lastError: err instanceof Error ? err.message : "Telegram polling stopped"
388
+ });
389
+ });
374
390
  }
375
391
  });
376
392
  this.accountManager.registerPollingSession(account.accountId, session);
377
- this.accountManager.updateStatus({
378
- accountId: account.accountId,
379
- running: true,
380
- mode: "polling"
381
- });
382
393
  log.info({
383
394
  accountId: account.accountId,
384
395
  username: me.username
@@ -404,7 +415,34 @@ var TelegramChannelPlugin = class {
404
415
  setupMessageHandler(accountId, bot) {
405
416
  const account = this.config.resolveAccount(this.cfg, accountId);
406
417
  const handleInboundMessage = async (ctx) => {
407
- const command = (ctx.message?.text ?? ctx.message?.caption ?? ctx.channelPost?.text ?? ctx.channelPost?.caption ?? "").trim().split(" ")[0].split("@")[0].toLowerCase();
418
+ const text = ctx.message?.text ?? ctx.message?.caption ?? ctx.channelPost?.text ?? ctx.channelPost?.caption ?? "";
419
+ if (ctx.chat?.type === "private" && ctx.from && await handleChannelConnectionProbe({
420
+ channel: this.id,
421
+ accountId,
422
+ identity: String(ctx.me.id),
423
+ senderId: String(ctx.from.id),
424
+ text,
425
+ reply: (reply) => ctx.reply(reply)
426
+ })) return;
427
+ const command = text.trim().split(" ")[0].split("@")[0].toLowerCase();
428
+ if ([
429
+ "/models",
430
+ "/cleanup",
431
+ "/focus"
432
+ ].includes(command)) {
433
+ const current = this.config.resolveAccount(this.cfg, accountId);
434
+ const chat = ctx.chat;
435
+ if (!chat || !ctx.from || !this.security.checkAccess?.({
436
+ accountId,
437
+ chatId: String(chat.id),
438
+ senderId: String(ctx.from.id),
439
+ senderName: ctx.from.username,
440
+ isGroup: chat.type !== "private"
441
+ }, current, this.cfg)?.allowed) {
442
+ await ctx.reply("Not authorized");
443
+ return;
444
+ }
445
+ }
408
446
  if (command === "/models") {
409
447
  await this.commandHandler.handleModels(ctx);
410
448
  return;
@@ -432,61 +470,42 @@ var TelegramChannelPlugin = class {
432
470
  accountId,
433
471
  message,
434
472
  onReady: async (batch) => {
435
- for (const msg of batch.messages) {
436
- const batchCtx = batch.ctx;
437
- await this.debouncer.enqueue({
438
- ctx: contextWithMessage(batchCtx, msg),
439
- accountId: batch.accountId,
440
- message: msg
441
- });
442
- }
473
+ await Promise.all(batch.messages.map((msg) => this.debouncer.enqueueAndWait({
474
+ ctx: contextWithMessage(batch.ctx, msg),
475
+ accountId: batch.accountId,
476
+ message: msg
477
+ })));
443
478
  }
444
479
  });
445
480
  };
446
- bot.on("message", async (ctx) => {
447
- try {
448
- await handleInboundMessage(ctx);
449
- } catch (err) {
450
- log.error({
451
- accountId,
452
- err
453
- }, "Message handler error");
454
- }
455
- });
456
- bot.on("channel_post", async (ctx) => {
457
- try {
458
- await handleInboundMessage(ctx);
459
- } catch (err) {
460
- log.error({
461
- accountId,
462
- err
463
- }, "Channel post handler error");
464
- }
465
- });
481
+ bot.on("message", handleInboundMessage);
482
+ bot.on("channel_post", handleInboundMessage);
466
483
  bot.on("message_reaction", async (ctx) => {
467
- try {
468
- await handleTelegramMessageReaction({
469
- ctx,
470
- accountId,
471
- bus: this.bus,
472
- mode: account.reactionNotifications
473
- });
474
- } catch (err) {
475
- log.error({
476
- accountId,
477
- err
478
- }, "Message reaction handler error");
479
- }
484
+ await handleTelegramMessageReaction({
485
+ ctx,
486
+ accountId,
487
+ bus: this.bus,
488
+ mode: account.reactionNotifications
489
+ });
480
490
  });
481
491
  bot.on("callback_query:data", async (ctx) => {
492
+ const current = this.config.resolveAccount(this.cfg, accountId);
493
+ const chat = ctx.chat;
494
+ if (!chat || !this.security.checkAccess?.({
495
+ accountId,
496
+ chatId: String(chat.id),
497
+ senderId: String(ctx.from.id),
498
+ senderName: ctx.from.username,
499
+ isGroup: chat.type !== "private"
500
+ }, current, this.cfg)?.allowed) {
501
+ await ctx.answerCallbackQuery("Not authorized");
502
+ return;
503
+ }
482
504
  try {
483
505
  await this.handleCallbackQuery(ctx, accountId);
484
506
  } catch (err) {
485
- log.error({
486
- accountId,
487
- err
488
- }, "Callback query handler error");
489
507
  await ctx.answerCallbackQuery("An error occurred").catch(() => {});
508
+ throw err;
490
509
  }
491
510
  });
492
511
  }
@@ -554,8 +573,12 @@ var TelegramChannelPlugin = class {
554
573
  if (items.length === 0) return;
555
574
  const tgSection = this.cfg.channels?.telegram;
556
575
  if (!tgSection || tgSection.enabled !== true) return;
557
- const last = items[items.length - 1];
558
- const ctx = last.ctx;
576
+ const ordered = items.length > 1 ? [...items].sort((a, b) => a.message.message_id - b.message.message_id) : items;
577
+ const last = ordered.at(-1);
578
+ const ctx = ordered.length > 1 ? contextWithMessage(last.ctx, {
579
+ ...last.message,
580
+ text: ordered.map((item) => item.message.text ?? "").join("\n\n")
581
+ }) : last.ctx;
559
582
  const accountId = last.accountId;
560
583
  if (!this.accountManager.getAccount(accountId)) {
561
584
  log.warn({ accountId }, "Unknown account");
@@ -1,17 +1,14 @@
1
- import type { Bot } from 'grammy';
1
+ import { type Bot } from 'grammy';
2
2
  export declare function resolvePollingStallThresholdMs(value?: number): number;
3
3
  export interface TelegramPollingSessionOptions {
4
4
  accountId: string;
5
5
  botToken: string;
6
6
  bot: Bot;
7
7
  stallThresholdMs?: number;
8
- onExit?: (err?: unknown) => void;
8
+ onPoll?: () => void;
9
+ onExit?: (err: unknown) => void;
9
10
  }
10
11
  export interface TelegramPollingSession {
11
12
  stop: () => Promise<void>;
12
13
  }
13
- export declare function wireTelegramUpdateOffsetPersistence(bot: Bot, params: {
14
- accountId: string;
15
- botToken: string;
16
- }): void;
17
14
  export declare function startTelegramPollingSession(options: TelegramPollingSessionOptions): TelegramPollingSession;
@@ -1,110 +1,123 @@
1
1
  import { createLogger } from "../../../src/utils/logger/index.js";
2
2
  import { init_logger } from "../../../src/utils/logger.js";
3
- import { isRecoverableTelegramNetworkError } from "./network-errors.js";
4
- import { readTelegramUpdateOffset, writeTelegramUpdateOffset } from "./update-offset-store.js";
5
- import { run } from "@grammyjs/runner";
3
+ import { ChannelMessageJournal } from "../../../src/channels/message-journal.js";
4
+ import { createTimeoutAbortSignal } from "./timeout-abort.js";
5
+ import { readTelegramUpdateOffset, telegramInboundScope } from "./update-offset-store.js";
6
+ import { setTimeout } from "node:timers/promises";
7
+ import { GrammyError } from "grammy";
6
8
  //#region extensions/telegram/src/polling-session.ts
7
9
  init_logger();
8
10
  const log = createLogger("TelegramPolling");
9
- const DEFAULT_STALL_THRESHOLD_MS = 12e4;
10
- const MIN_STALL_THRESHOLD_MS = 3e4;
11
- const MAX_STALL_THRESHOLD_MS = 6e5;
12
- const WATCHDOG_INTERVAL_MS = 3e4;
11
+ const POLL_TIMEOUT_SECONDS = 25;
12
+ const OFFSET_MAX_IDLE_MS = 8640 * 6e4;
13
+ const ALLOWED_UPDATES = [
14
+ "message",
15
+ "channel_post",
16
+ "message_reaction",
17
+ "callback_query"
18
+ ];
13
19
  function resolvePollingStallThresholdMs(value) {
14
- if (value == null || !Number.isFinite(value)) return DEFAULT_STALL_THRESHOLD_MS;
15
- return Math.min(MAX_STALL_THRESHOLD_MS, Math.max(MIN_STALL_THRESHOLD_MS, Math.floor(value)));
16
- }
17
- function wireTelegramUpdateOffsetPersistence(bot, params) {
18
- const savedOffset = readTelegramUpdateOffset(params);
19
- if (savedOffset != null) {
20
- let restored = false;
21
- bot.api.config.use(async (prev, method, payload, signal) => {
22
- if (method === "getUpdates" && !restored) {
23
- restored = true;
24
- return prev(method, {
25
- ...payload,
26
- offset: savedOffset + 1
27
- }, signal);
28
- }
29
- return prev(method, payload, signal);
30
- });
31
- }
32
- bot.use(async (ctx, next) => {
33
- const updateId = ctx.update.update_id;
34
- if (Number.isSafeInteger(updateId)) writeTelegramUpdateOffset({
35
- ...params,
36
- lastUpdateId: updateId
37
- });
38
- await next();
39
- });
20
+ if (value == null || !Number.isFinite(value)) return 12e4;
21
+ return Math.min(6e5, Math.max(3e4, Math.floor(value)));
40
22
  }
41
23
  function startTelegramPollingSession(options) {
42
- const { accountId, botToken, bot } = options;
43
- const stallThresholdMs = resolvePollingStallThresholdMs(options.stallThresholdMs);
44
- wireTelegramUpdateOffsetPersistence(bot, {
45
- accountId,
46
- botToken
47
- });
48
- let lastUpdateAt = Date.now();
49
- bot.use(async (_ctx, next) => {
50
- lastUpdateAt = Date.now();
51
- await next();
24
+ const controller = new AbortController();
25
+ const task = poll(options, controller.signal).catch((err) => {
26
+ if (controller.signal.aborted) return;
27
+ const message = err instanceof Error ? err.message : String(err);
28
+ log.error({
29
+ accountId: options.accountId,
30
+ errorMessage: message
31
+ }, "Telegram polling stopped");
32
+ options.onExit?.(err);
52
33
  });
53
- const runner = run(bot, { runner: {
54
- fetch: { timeout: 30 },
55
- silent: true,
56
- maxRetryTime: Number.POSITIVE_INFINITY,
57
- retryInterval: "exponential"
58
- } });
59
- const watchdog = setInterval(() => {
60
- const idleMs = Date.now() - lastUpdateAt;
61
- if (idleMs < stallThresholdMs) return;
62
- log.warn({
63
- accountId,
64
- idleMs,
65
- stallThresholdMs
66
- }, "Telegram polling stall detected; restarting runner");
67
- lastUpdateAt = Date.now();
68
- restartRunner(runner, accountId).catch((err) => {
69
- log.error({
70
- err,
71
- accountId
72
- }, "Telegram polling restart failed");
73
- });
74
- }, WATCHDOG_INTERVAL_MS);
75
- watchdog.unref?.();
76
- attachRunnerExit(runner, accountId, options.onExit);
77
34
  return { stop: async () => {
78
- clearInterval(watchdog);
79
- await runner.stop();
35
+ controller.abort();
36
+ await task;
80
37
  } };
81
38
  }
82
- async function restartRunner(runner, accountId) {
83
- try {
84
- await runner.stop();
85
- runner.start();
86
- log.info({ accountId }, "Telegram polling runner restarted");
87
- } catch (err) {
88
- if (isRecoverableTelegramNetworkError(err)) {
89
- log.warn({
90
- err,
91
- accountId
92
- }, "Telegram polling restart hit network error");
93
- return;
39
+ async function poll(options, signal) {
40
+ const { accountId, bot, botToken } = options;
41
+ const journal = new ChannelMessageJournal("telegram", telegramInboundScope(accountId, botToken));
42
+ const interrupted = journal.recoverInterrupted();
43
+ if (interrupted) log.warn({
44
+ accountId,
45
+ interrupted
46
+ }, "Telegram updates interrupted during dispatch");
47
+ let cursor = journal.cursor();
48
+ const legacyOffset = cursor === void 0 ? readTelegramUpdateOffset(options) : void 0;
49
+ if (legacyOffset !== void 0) cursor = {
50
+ updateId: legacyOffset,
51
+ receivedAt: Date.now()
52
+ };
53
+ let failures = 0;
54
+ while (!signal.aborted) {
55
+ const pending = journal.pending();
56
+ if (pending.length) {
57
+ const dispatched = await Promise.all(pending.map(async ({ id, payload }) => {
58
+ const message = payload.message ?? payload.channel_post;
59
+ const text = message?.text ?? message?.caption;
60
+ const replayable = Boolean(message && !text?.trimStart().startsWith("/"));
61
+ if (signal.aborted || !journal.begin(id, replayable)) return;
62
+ try {
63
+ await bot.handleUpdate(payload);
64
+ return {
65
+ id,
66
+ outcome: "completed"
67
+ };
68
+ } catch (err) {
69
+ log.error({
70
+ accountId,
71
+ updateId: id,
72
+ errorMessage: err instanceof Error ? err.name : typeof err
73
+ }, "Telegram update dispatch interrupted");
74
+ return {
75
+ id,
76
+ outcome: "interrupted"
77
+ };
78
+ }
79
+ }));
80
+ journal.finishBatch(dispatched.filter((entry) => entry !== void 0));
81
+ continue;
82
+ }
83
+ const timeout = createTimeoutAbortSignal(resolvePollingStallThresholdMs(options.stallThresholdMs), signal);
84
+ try {
85
+ const offset = cursor && Date.now() - cursor.receivedAt < OFFSET_MAX_IDLE_MS ? cursor.updateId + 1 : void 0;
86
+ const updates = await bot.api.getUpdates({
87
+ timeout: POLL_TIMEOUT_SECONDS,
88
+ ...offset === void 0 ? {} : { offset },
89
+ allowed_updates: [...ALLOWED_UPDATES]
90
+ }, timeout.signal);
91
+ if (signal.aborted) return;
92
+ if (updates.length) {
93
+ const next = {
94
+ updateId: Math.max(...updates.map((update) => update.update_id)),
95
+ receivedAt: Date.now()
96
+ };
97
+ journal.accept(updates.map((update) => ({
98
+ id: String(update.update_id),
99
+ payload: update
100
+ })), next);
101
+ cursor = next;
102
+ }
103
+ failures = 0;
104
+ options.onPoll?.();
105
+ } catch (err) {
106
+ if (signal.aborted) return;
107
+ if (err instanceof GrammyError && err.error_code === 409) throw new Error("Telegram Bot is already being polled or has a webhook configured");
108
+ if (err instanceof GrammyError && err.error_code >= 400 && err.error_code < 500 && err.error_code !== 429) throw new Error(`Telegram rejected polling (HTTP ${err.error_code})`);
109
+ failures += 1;
110
+ const retryAfter = err instanceof GrammyError ? err.parameters.retry_after ?? 0 : 0;
111
+ const retryMs = Math.max(retryAfter * 1e3, Math.min(3e4, 1e3 * 2 ** Math.min(5, failures - 1)));
112
+ if (failures === 1) log.warn({
113
+ accountId,
114
+ retryMs
115
+ }, "Telegram polling failed; retrying");
116
+ await setTimeout(retryMs, void 0, { signal });
117
+ } finally {
118
+ timeout.dispose();
94
119
  }
95
- throw err;
96
120
  }
97
121
  }
98
- async function attachRunnerExit(runner, accountId, onExit) {
99
- const task = runner.task();
100
- if (!task) return;
101
- task.catch((err) => {
102
- log.error({
103
- err,
104
- accountId
105
- }, "Telegram polling runner exited");
106
- onExit?.(err);
107
- });
108
- }
109
122
  //#endregion
110
- export { resolvePollingStallThresholdMs, startTelegramPollingSession, wireTelegramUpdateOffsetPersistence };
123
+ export { resolvePollingStallThresholdMs, startTelegramPollingSession };
@@ -0,0 +1,4 @@
1
+ import { type Bot } from 'grammy';
2
+ import { buildSendOptions } from './send-options.js';
3
+ export declare function prefersTelegramRichMessage(text: string): boolean;
4
+ export declare function sendTelegramRichMessage(api: Bot['api'], chatId: string, content: string, options?: Parameters<typeof buildSendOptions>[0]): Promise<number | undefined>;
@@ -0,0 +1,23 @@
1
+ import { buildSendOptions } from "./send-options.js";
2
+ import { GrammyError } from "grammy";
3
+ //#region extensions/telegram/src/rich-message.ts
4
+ const unavailable = /* @__PURE__ */ new WeakSet();
5
+ const RICH_BLOCK_PATTERN = /^(?: {0,3}(?:```|~~~|>\s?)|\s*\|.+\|\s*$)/m;
6
+ function prefersTelegramRichMessage(text) {
7
+ return text.length <= 16e3 && RICH_BLOCK_PATTERN.test(text);
8
+ }
9
+ async function sendTelegramRichMessage(api, chatId, content, options) {
10
+ if (unavailable.has(api) || typeof api.sendRichMessage !== "function" || !prefersTelegramRichMessage(content)) return;
11
+ try {
12
+ return (await api.sendRichMessage(chatId, { markdown: content }, buildSendOptions(options ?? {}))).message_id;
13
+ } catch (err) {
14
+ if (err instanceof GrammyError && err.error_code === 404) {
15
+ unavailable.add(api);
16
+ return;
17
+ }
18
+ if (err instanceof GrammyError && err.error_code === 400) return;
19
+ throw err;
20
+ }
21
+ }
22
+ //#endregion
23
+ export { prefersTelegramRichMessage, sendTelegramRichMessage };
@@ -1,6 +1,6 @@
1
1
  import { AbortController } from 'abort-controller';
2
2
  /** grammY `Api` expects `abort-controller` signals, not Node/DOM `AbortSignal.timeout()`. */
3
- export declare function createTimeoutAbortSignal(ms: number): {
3
+ export declare function createTimeoutAbortSignal(ms: number, parent?: AbortSignal): {
4
4
  signal: InstanceType<typeof AbortController>['signal'];
5
5
  dispose: () => void;
6
6
  };
@@ -1,12 +1,18 @@
1
1
  import { AbortController } from "abort-controller";
2
2
  //#region extensions/telegram/src/timeout-abort.ts
3
3
  /** grammY `Api` expects `abort-controller` signals, not Node/DOM `AbortSignal.timeout()`. */
4
- function createTimeoutAbortSignal(ms) {
4
+ function createTimeoutAbortSignal(ms, parent) {
5
5
  const ac = new AbortController();
6
- const t = setTimeout(() => ac.abort(), ms);
6
+ const abort = () => ac.abort();
7
+ const t = setTimeout(abort, ms);
8
+ if (parent?.aborted) abort();
9
+ else parent?.addEventListener("abort", abort, { once: true });
7
10
  return {
8
11
  signal: ac.signal,
9
- dispose: () => clearTimeout(t)
12
+ dispose: () => {
13
+ clearTimeout(t);
14
+ parent?.removeEventListener("abort", abort);
15
+ }
10
16
  };
11
17
  }
12
18
  //#endregion
@@ -7,3 +7,4 @@ export declare function writeTelegramUpdateOffset(params: {
7
7
  botToken?: string;
8
8
  lastUpdateId: number;
9
9
  }): void;
10
+ export declare function telegramInboundScope(accountId: string, token: string): string;
@@ -1,4 +1,5 @@
1
1
  import { DurableState } from "../../../src/storage/sqlite/durable-state.js";
2
+ import { createHash } from "node:crypto";
2
3
  //#region extensions/telegram/src/update-offset-store.ts
3
4
  const state = new DurableState("telegram-offsets");
4
5
  function accountKey(accountId) {
@@ -23,5 +24,9 @@ function writeTelegramUpdateOffset(params) {
23
24
  result: void 0
24
25
  }));
25
26
  }
27
+ function telegramInboundScope(accountId, token) {
28
+ const identity = botId(token) ?? createHash("sha256").update(token).digest("hex");
29
+ return JSON.stringify([accountKey(accountId), identity]);
30
+ }
26
31
  //#endregion
27
- export { readTelegramUpdateOffset, writeTelegramUpdateOffset };
32
+ export { readTelegramUpdateOffset, telegramInboundScope, writeTelegramUpdateOffset };
@@ -2,7 +2,7 @@
2
2
  "id": "telegram",
3
3
  "name": "Telegram Channel",
4
4
  "description": "Bundled Telegram Bot channel (private workspace sources; ships inside @xopcai/xopc dist/)",
5
- "version": "0.0.464",
5
+ "version": "0.0.465",
6
6
  "kind": "channel",
7
7
  "main": "src/index.js",
8
8
  "channels": [
@@ -19,6 +19,7 @@ export declare function apiGetFetch(params: {
19
19
  timeoutMs?: number;
20
20
  label: string;
21
21
  routeTag?: string;
22
+ abortSignal?: AbortSignal;
22
23
  }): Promise<string>;
23
24
  /**
24
25
  * Long-poll getUpdates. Server should hold the request until new messages or timeout.