@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.
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/extensions/feishu/src/adapters/cli-login.js +23 -49
- package/dist/extensions/feishu/src/adapters/gateway-setup.d.ts +3 -0
- package/dist/extensions/feishu/src/adapters/gateway-setup.js +180 -128
- package/dist/extensions/feishu/src/adapters/onboard-cli.d.ts +1 -1
- package/dist/extensions/feishu/src/adapters/onboard-cli.js +27 -15
- package/dist/extensions/feishu/src/auth/app-registration.d.ts +1 -0
- package/dist/extensions/feishu/src/auth/app-registration.js +12 -9
- package/dist/extensions/feishu/src/outbound/outbound-adapter.js +40 -16
- package/dist/extensions/feishu/src/plugin.d.ts +2 -0
- package/dist/extensions/feishu/src/plugin.js +37 -23
- package/dist/extensions/feishu/src/status/status-adapter.d.ts +1 -1
- package/dist/extensions/feishu/src/status/status-adapter.js +8 -5
- package/dist/extensions/feishu/src/streaming/streaming-adapter.js +97 -69
- package/dist/extensions/feishu/src/transport/client/bot-info.d.ts +10 -0
- package/dist/extensions/feishu/src/transport/client/bot-info.js +34 -0
- package/dist/extensions/feishu/src/transport/client/client.d.ts +7 -1
- package/dist/extensions/feishu/src/transport/client/client.js +6 -5
- package/dist/extensions/feishu/src/transport/client/install-sdk.d.ts +2 -0
- package/dist/extensions/feishu/src/transport/client/install-sdk.js +77 -0
- package/dist/extensions/feishu/src/transport/client/lark-sdk.d.ts +2 -0
- package/dist/extensions/feishu/src/transport/client/lark-sdk.js +27 -3
- package/dist/extensions/feishu/src/transport/client/sdk-catalog.d.ts +1 -0
- package/dist/extensions/feishu/src/transport/client/sdk-catalog.js +317 -0
- package/dist/extensions/feishu/src/transport/reliability/inbound-pipeline.d.ts +1 -1
- package/dist/extensions/feishu/src/transport/reliability/inbound-pipeline.js +13 -5
- package/dist/extensions/feishu/src/transport/reliability/message-ingress.d.ts +21 -0
- package/dist/extensions/feishu/src/transport/reliability/message-ingress.js +313 -0
- package/dist/extensions/feishu/src/transport/socket-mode/monitor.d.ts +1 -0
- package/dist/extensions/feishu/src/transport/socket-mode/monitor.js +56 -171
- package/dist/extensions/feishu/src/transport/webhook/monitor.d.ts +1 -0
- package/dist/extensions/feishu/src/transport/webhook/monitor.js +10 -102
- package/dist/extensions/telegram/src/account-manager.d.ts +1 -0
- package/dist/extensions/telegram/src/account-manager.js +3 -0
- package/dist/extensions/telegram/src/adapters/debounce-keys.js +7 -2
- package/dist/extensions/telegram/src/adapters/gateway-setup.js +113 -63
- package/dist/extensions/telegram/src/adapters/streaming-adapter.js +8 -4
- package/dist/extensions/telegram/src/doctor.js +1 -1
- package/dist/extensions/telegram/src/inbound-coalescer.d.ts +8 -6
- package/dist/extensions/telegram/src/inbound-coalescer.js +47 -88
- package/dist/extensions/telegram/src/inbound-processor.js +5 -1
- package/dist/extensions/telegram/src/outbound-sender.js +16 -23
- package/dist/extensions/telegram/src/plugin.js +80 -57
- package/dist/extensions/telegram/src/polling-session.d.ts +3 -6
- package/dist/extensions/telegram/src/polling-session.js +107 -94
- package/dist/extensions/telegram/src/rich-message.d.ts +4 -0
- package/dist/extensions/telegram/src/rich-message.js +23 -0
- package/dist/extensions/telegram/src/timeout-abort.d.ts +1 -1
- package/dist/extensions/telegram/src/timeout-abort.js +9 -3
- package/dist/extensions/telegram/src/update-offset-store.d.ts +1 -0
- package/dist/extensions/telegram/src/update-offset-store.js +6 -1
- package/dist/extensions/telegram/xopc.extension.json +1 -1
- package/dist/extensions/weixin/src/api/api.d.ts +1 -0
- package/dist/extensions/weixin/src/api/api.js +12 -6
- package/dist/extensions/weixin/src/api/types.d.ts +5 -2
- package/dist/extensions/weixin/src/auth/login-qr.d.ts +7 -1
- package/dist/extensions/weixin/src/auth/login-qr.js +48 -13
- package/dist/extensions/weixin/src/cdn/pic-decrypt.d.ts +2 -2
- package/dist/extensions/weixin/src/cdn/pic-decrypt.js +37 -25
- package/dist/extensions/weixin/src/cli/gateway-qr-login.d.ts +8 -0
- package/dist/extensions/weixin/src/cli/gateway-qr-login.js +45 -6
- package/dist/extensions/weixin/src/cli/qr-login.d.ts +1 -1
- package/dist/extensions/weixin/src/cli/qr-login.js +9 -3
- package/dist/extensions/weixin/src/media/media-download.d.ts +1 -0
- package/dist/extensions/weixin/src/media/media-download.js +4 -5
- package/dist/extensions/weixin/src/messaging/process-message.d.ts +2 -0
- package/dist/extensions/weixin/src/messaging/process-message.js +90 -65
- package/dist/extensions/weixin/src/messaging/quote-cache.d.ts +10 -0
- package/dist/extensions/weixin/src/messaging/quote-cache.js +46 -0
- package/dist/extensions/weixin/src/monitor/monitor.d.ts +3 -3
- package/dist/extensions/weixin/src/monitor/monitor.js +108 -104
- package/dist/extensions/weixin/src/plugin.d.ts +5 -1
- package/dist/extensions/weixin/src/plugin.js +138 -42
- package/dist/gateway/static/root/assets/{capabilities-page-rTjkjo71.js → capabilities-page-U_hQx5ou.js} +2 -2
- package/dist/gateway/static/root/assets/channels-BUzno8Pi.js +1 -0
- package/dist/gateway/static/root/assets/extension-settings-page-BvUtZGLT.js +1 -0
- package/dist/gateway/static/root/assets/index-Cdo4_zon.js +11 -0
- package/dist/gateway/static/root/assets/index-DYTktubl.css +1 -0
- package/dist/gateway/static/root/assets/{route-preload-5iwjWERk.js → route-preload-ClsAFFQc.js} +2 -2
- package/dist/gateway/static/root/assets/schema-form-BxBDgLrg.js +1 -0
- package/dist/gateway/static/root/assets/{settings-page-DNiRlM5x.js → settings-page-M6XwzIyu.js} +1 -1
- package/dist/gateway/static/root/assets/understanding-refresh-store-CM6bUcaJ.js +1 -0
- package/dist/gateway/static/root/assets/user-model-page-CBcGMhrR.js +2 -0
- package/dist/gateway/static/root/index.html +4 -4
- package/dist/package.js +1 -1
- package/dist/src/agent/inbound/inbound-loop.js +14 -0
- package/dist/src/agent/messaging/outbound-coordinator.js +1 -1
- package/dist/src/channels/connection-probe.d.ts +23 -0
- package/dist/src/channels/connection-probe.js +98 -0
- package/dist/src/channels/manager.d.ts +2 -0
- package/dist/src/channels/manager.js +5 -0
- package/dist/src/channels/message-journal.d.ts +25 -0
- package/dist/src/channels/message-journal.js +79 -0
- package/dist/src/channels/outbound-sender.d.ts +8 -0
- package/dist/src/channels/outbound-sender.js +60 -1
- package/dist/src/channels/plugins/types.adapters.d.ts +4 -0
- package/dist/src/channels/verified-inbound.js +20 -14
- package/dist/src/gateway/hono/routes/channels.js +23 -10
- package/dist/src/gateway/hono/routes/home.js +1 -1
- package/dist/src/gateway/hono/routes/user-model.js +48 -20
- package/dist/src/gateway/service.js +5 -5
- package/dist/src/home-intelligence/host.js +5 -5
- package/dist/src/infra/bus/index.d.ts +1 -1
- package/dist/src/infra/bus/queue.d.ts +16 -3
- package/dist/src/infra/bus/queue.js +74 -3
- package/dist/src/infra/debounce.d.ts +1 -0
- package/dist/src/infra/debounce.js +40 -35
- package/dist/src/knowledge-memory/index.js +2 -2
- package/dist/src/knowledge-memory/repository.d.ts +9 -0
- package/dist/src/knowledge-memory/repository.js +12 -2
- package/dist/src/runtime-tools/types.d.ts +1 -1
- package/package.json +5 -6
- package/dist/gateway/static/root/assets/channels-DvB2fwPI.js +0 -1
- package/dist/gateway/static/root/assets/extension-settings-page-DKAJE4h9.js +0 -1
- package/dist/gateway/static/root/assets/index-BGA-G-Bp.css +0 -1
- package/dist/gateway/static/root/assets/index-pmlYYCCU.js +0 -11
- package/dist/gateway/static/root/assets/schema-form-C9TYGa0_.js +0 -1
- package/dist/gateway/static/root/assets/understanding-refresh-store-Cf0DUO_C.js +0 -1
- 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
|
|
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) =>
|
|
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
|
|
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
|
-
|
|
219
|
-
replyToMessageId
|
|
220
|
-
silent: options?.silent
|
|
223
|
+
...options,
|
|
224
|
+
replyToMessageId
|
|
221
225
|
});
|
|
222
226
|
try {
|
|
223
|
-
return (await bot.api.sendMessage(chatId,
|
|
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
|
-
|
|
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(
|
|
239
|
-
for (
|
|
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.
|
|
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
|
-
|
|
373
|
-
|
|
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
|
|
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
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
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",
|
|
447
|
-
|
|
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
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
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
|
|
558
|
-
const
|
|
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
|
|
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
|
-
|
|
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 {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
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
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
|
|
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
|
|
15
|
-
return Math.min(
|
|
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
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
|
|
79
|
-
await
|
|
35
|
+
controller.abort();
|
|
36
|
+
await task;
|
|
80
37
|
} };
|
|
81
38
|
}
|
|
82
|
-
async function
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
|
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
|
|
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: () =>
|
|
12
|
+
dispose: () => {
|
|
13
|
+
clearTimeout(t);
|
|
14
|
+
parent?.removeEventListener("abort", abort);
|
|
15
|
+
}
|
|
10
16
|
};
|
|
11
17
|
}
|
|
12
18
|
//#endregion
|
|
@@ -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.
|
|
5
|
+
"version": "0.0.465",
|
|
6
6
|
"kind": "channel",
|
|
7
7
|
"main": "src/index.js",
|
|
8
8
|
"channels": [
|