@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
@@ -1,12 +1,8 @@
1
1
  import { createLogger } from "../../../../../src/utils/logger/index.js";
2
2
  import { init_logger } from "../../../../../src/utils/logger.js";
3
- import { generateConversationId } from "../../../../../src/chat-commands/session-key.js";
4
- import { recordFeishuMessageBinding } from "../../state/message-bindings.js";
5
3
  import { loadFeishuLarkSdk } from "../client/lark-sdk.js";
6
4
  import { createFeishuLarkSdkPinoLogger } from "../client/lark-sdk-logger.js";
7
- import { sendFeishuPairingPromptIfNeeded } from "../../pairing/feishu-pairing-prompt.js";
8
- import { createFeishuDedupe } from "../reliability/dedupe.js";
9
- import { stripFeishuMentions } from "../text/mentions.js";
5
+ import { createFeishuMessageIngress } from "../reliability/message-ingress.js";
10
6
  import crypto from "node:crypto";
11
7
  import * as http$1 from "node:http";
12
8
  //#region extensions/feishu/src/transport/webhook/monitor.ts
@@ -124,8 +120,8 @@ function text(res, status, body) {
124
120
  res.end(body);
125
121
  }
126
122
  function createFeishuWebhookMonitor(deps) {
127
- const { account, abortSignal, security, enqueueInbound, inboundDebounceDefaultMs } = deps;
128
- const dedupe = createFeishuDedupe();
123
+ const { account, abortSignal } = deps;
124
+ const ingress = createFeishuMessageIngress(deps);
129
125
  const encryptKey = (account.encryptKey ?? "").trim();
130
126
  const verificationToken = (account.verificationToken ?? "").trim();
131
127
  if (!encryptKey) throw new Error("Feishu webhook mode requires encryptKey");
@@ -135,86 +131,6 @@ function createFeishuWebhookMonitor(deps) {
135
131
  const path = (account.webhookPath ?? "/feishu/events").trim() || "/feishu/events";
136
132
  const l = loadFeishuLarkSdk();
137
133
  const sdkLogger = createFeishuLarkSdkPinoLogger(account.accountId);
138
- function resolveTextDebounceMs() {
139
- if (typeof account.inboundDebounceMs === "number" && Number.isFinite(account.inboundDebounceMs)) return Math.max(0, Math.trunc(account.inboundDebounceMs));
140
- return Math.max(0, Math.trunc(inboundDebounceDefaultMs));
141
- }
142
- async function pushText(inbound) {
143
- const debounceMs = resolveTextDebounceMs();
144
- await enqueueInbound({
145
- kind: "text",
146
- accountId: account.accountId,
147
- chatId: inbound.chat_id,
148
- debounceMs,
149
- inbound
150
- });
151
- }
152
- async function handleMessageReceive(event) {
153
- const msg = event?.event?.message ?? event?.message ?? event?.data?.message;
154
- const sender = event?.event?.sender ?? event?.sender ?? event?.data?.sender;
155
- const chatId = msg?.chat_id ?? msg?.chatId ?? "";
156
- const messageId = msg?.message_id ?? msg?.messageId ?? "";
157
- const chatType = msg?.chat_type ?? msg?.chatType ?? "";
158
- const senderId = sender?.sender_id?.open_id ?? sender?.sender_id?.user_id ?? sender?.open_id ?? sender?.user_id ?? "";
159
- const senderName = sender?.sender_id?.name ?? sender?.sender_name ?? void 0;
160
- if (!chatId || !messageId || !senderId) return;
161
- if (!dedupe.claim(messageId)) return;
162
- const isGroup = chatType === "group" || chatType === "chat";
163
- const normalizedText = stripFeishuMentions((msg?.content && typeof msg.content === "string" ? safeJsonText(msg.content) : safeJsonText(msg?.body?.content)) ?? "").trim();
164
- if (!normalizedText) return;
165
- const threadId = msg?.thread_id ?? msg?.threadId ?? void 0;
166
- const conversationId = generateConversationId({
167
- source: "feishu",
168
- chatId,
169
- senderId,
170
- isGroup,
171
- threadId: typeof threadId === "string" && threadId.trim() ? threadId : void 0,
172
- accountId: account.accountId
173
- });
174
- recordFeishuMessageBinding({
175
- messageId,
176
- conversationId,
177
- accountId: account.accountId,
178
- chatId,
179
- senderId,
180
- isGroup,
181
- threadId: typeof threadId === "string" && threadId.trim() ? threadId : void 0
182
- });
183
- const access = security.checkAccess({
184
- accountId: account.accountId,
185
- chatId,
186
- senderId,
187
- senderName,
188
- isGroup,
189
- threadId
190
- });
191
- if (access && !access.allowed) {
192
- if (!isGroup && access.reason === "pairing-required") await sendFeishuPairingPromptIfNeeded({
193
- account,
194
- messageId,
195
- threadId: typeof threadId === "string" && threadId.trim() ? threadId : void 0,
196
- senderId,
197
- senderName,
198
- isGroup
199
- });
200
- return;
201
- }
202
- await pushText({
203
- channel: "feishu",
204
- sender_id: senderId,
205
- chat_id: chatId,
206
- content: normalizedText,
207
- metadata: {
208
- conversationId,
209
- accountId: account.accountId,
210
- messageId,
211
- threadId,
212
- isGroup,
213
- feishuEventType: "im.message.receive_v1",
214
- raw: event
215
- }
216
- });
217
- }
218
134
  const dispatcher = new l.EventDispatcher({
219
135
  verifyChallenge: false,
220
136
  encryptKey,
@@ -222,7 +138,7 @@ function createFeishuWebhookMonitor(deps) {
222
138
  logger: sdkLogger,
223
139
  loggerLevel: l.LoggerLevel.info
224
140
  });
225
- dispatcher.register({ "im.message.receive_v1": async (data) => await handleMessageReceive(data) });
141
+ dispatcher.register({ "im.message.receive_v1": async (data) => ingress.accept(data) });
226
142
  const server = http$1.createServer();
227
143
  async function handleRequest(req, res) {
228
144
  if (req.method !== "POST") return text(res, 405, "Method Not Allowed");
@@ -248,6 +164,7 @@ function createFeishuWebhookMonitor(deps) {
248
164
  if (!res.headersSent) return json(res, 200, out);
249
165
  }
250
166
  async function run() {
167
+ ingress.start();
251
168
  await new Promise((resolve, reject) => {
252
169
  server.on("request", (req, res) => {
253
170
  handleRequest(req, res).catch((err) => {
@@ -261,6 +178,7 @@ function createFeishuWebhookMonitor(deps) {
261
178
  server.on("error", (err) => reject(err));
262
179
  server.listen(port, host, () => resolve());
263
180
  });
181
+ deps.onState?.("online");
264
182
  log.info({
265
183
  accountId: account.accountId,
266
184
  host,
@@ -269,26 +187,16 @@ function createFeishuWebhookMonitor(deps) {
269
187
  }, "Feishu webhook server listening");
270
188
  await new Promise((resolve) => {
271
189
  if (abortSignal.aborted) {
272
- server.close();
273
- return resolve();
190
+ server.close(() => resolve());
191
+ return;
274
192
  }
275
193
  abortSignal.addEventListener("abort", () => {
276
- server.close();
277
- resolve();
194
+ server.close(() => resolve());
278
195
  }, { once: true });
279
196
  });
197
+ await ingress.settled();
280
198
  }
281
199
  return { run };
282
200
  }
283
- function safeJsonText(raw) {
284
- if (typeof raw !== "string" || !raw.trim()) return void 0;
285
- try {
286
- const parsed = JSON.parse(raw);
287
- const t = typeof parsed?.text === "string" ? parsed.text : typeof parsed?.content === "string" ? parsed.content : typeof parsed?.title === "string" ? parsed.title : void 0;
288
- return typeof t === "string" ? t : raw;
289
- } catch {
290
- return raw;
291
- }
292
- }
293
201
  //#endregion
294
202
  export { createFeishuWebhookMonitor };
@@ -28,6 +28,7 @@ export declare class TelegramAccountManager {
28
28
  getBot(accountId: string): Bot | undefined;
29
29
  registerPollingSession(accountId: string, session: TelegramPollingSession): void;
30
30
  stopRunner(accountId: string): Promise<void>;
31
+ hasPollingSession(accountId: string): boolean;
31
32
  isStarting(accountId: string): boolean;
32
33
  markStarting(accountId: string): void;
33
34
  markStartComplete(accountId: string): void;
@@ -56,6 +56,9 @@ var TelegramAccountManager = class {
56
56
  mode: "stopped"
57
57
  });
58
58
  }
59
+ hasPollingSession(accountId) {
60
+ return this.pollingSessions.has(accountId);
61
+ }
59
62
  isStarting(accountId) {
60
63
  return this.startingAccounts.has(accountId);
61
64
  }
@@ -5,12 +5,17 @@ function telegramDebouncerKeyPolicy() {
5
5
  const chatId = item.ctx.chat?.id?.toString();
6
6
  const userId = item.ctx.from?.id?.toString();
7
7
  if (!chatId || !userId) return void 0;
8
- return `telegram:${item.accountId}:${chatId}:${userId}`;
8
+ return JSON.stringify([
9
+ item.accountId,
10
+ chatId,
11
+ item.message.message_thread_id,
12
+ userId
13
+ ]);
9
14
  },
10
15
  shouldDebounce: (item) => {
11
16
  const text = item.message.text ?? item.message.caption ?? "";
12
17
  if (text.startsWith("/")) return false;
13
- if (item.message.photo || item.message.document || item.message.video) return false;
18
+ if (!item.message.text || item.message.photo || item.message.document || item.message.video) return false;
14
19
  return text.length < 100;
15
20
  }
16
21
  };
@@ -1,3 +1,8 @@
1
+ import { mergeDistinctSenderIds } from "../../../../src/channels/pairing/preseed-allow-from.js";
2
+ import { cancelChannelConnectionProbe, confirmChannelConnectionProbe, getChannelConnectionClaimant, getChannelConnectionProbe, startChannelConnectionProbe } from "../../../../src/channels/connection-probe.js";
3
+ import { createTimeoutAbortSignal } from "../timeout-abort.js";
4
+ import { createProxyFetch } from "../proxy-fetch.js";
5
+ import { Bot } from "grammy";
1
6
  //#region extensions/telegram/src/adapters/gateway-setup.ts
2
7
  function isZh(locale) {
3
8
  return locale?.toLowerCase().startsWith("zh") === true;
@@ -11,18 +16,19 @@ function pickString(input) {
11
16
  function pickDmPolicy(input) {
12
17
  return input === "open" || input === "pairing" || input === "allowlist" || input === "disabled" ? input : "pairing";
13
18
  }
14
- function existingDefaultAccount(config) {
15
- const account = ((config.channels?.telegram)?.accounts)?.default;
19
+ function existingAccount(config, accountId) {
20
+ const accounts = (config.channels?.telegram)?.accounts;
21
+ const account = accounts && Object.hasOwn(accounts, accountId) ? accounts[accountId] : void 0;
16
22
  return account && typeof account === "object" && !Array.isArray(account) ? account : {};
17
23
  }
18
24
  function existingDefaults(config) {
19
25
  const defaults = (config.channels?.telegram)?.defaults;
20
26
  return defaults && typeof defaults === "object" && !Array.isArray(defaults) ? defaults : {};
21
27
  }
22
- function buildTelegramConfig(config, input) {
28
+ function buildTelegramConfig(config, input, accountId) {
23
29
  const existing = config.channels?.telegram ?? {};
24
30
  const existingAccounts = existing.accounts ?? {};
25
- const previousDefault = existingDefaultAccount(config);
31
+ const previousDefault = existingAccount(config, accountId);
26
32
  const previousDefaults = existingDefaults(config);
27
33
  const botToken = pickString(input.botToken) || pickString(previousDefault.botToken);
28
34
  const apiRoot = pickString(input.apiRoot);
@@ -37,13 +43,13 @@ function buildTelegramConfig(config, input) {
37
43
  textChunkLimit: previousDefaults.textChunkLimit ?? 4e3,
38
44
  streaming: previousDefaults.streaming ?? { mode: "partial" }
39
45
  };
40
- if (apiRoot) defaults.apiRoot = apiRoot;
41
- if (proxy) defaults.proxy = proxy;
42
- const defaultAccount = {
46
+ const configuredAccount = {
43
47
  ...previousDefault,
44
- accountId: "default",
48
+ accountId,
45
49
  enabled: true,
46
50
  botToken,
51
+ ...apiRoot ? { apiRoot } : {},
52
+ ...proxy ? { proxy } : {},
47
53
  dmPolicy,
48
54
  allowFrom: dmPolicy === "open" ? ["*"] : previousDefault.allowFrom ?? []
49
55
  };
@@ -57,89 +63,133 @@ function buildTelegramConfig(config, input) {
57
63
  defaults,
58
64
  accounts: {
59
65
  ...existingAccounts,
60
- default: defaultAccount
66
+ [accountId]: configuredAccount
61
67
  }
62
68
  }
63
69
  }
64
70
  };
65
71
  }
66
- function formPayload(config, locale) {
67
- const zh = isZh(locale);
68
- const account = existingDefaultAccount(config);
69
- const defaults = existingDefaults(config);
72
+ function formPayload(locale) {
70
73
  return {
71
74
  type: "form",
72
75
  submitAction: "setup.save",
73
- message: zh ? "填写 Bot Token 后保存即可启用 Telegram。默认私聊策略为 pairing;允许列表在账号配置里维护。" : "Enter a Bot Token and save. The default DM policy is pairing; manage allow lists on the account configuration.",
76
+ message: isZh(locale) ? "粘贴 BotFather 给你的 Bot Token。" : "Paste the Bot Token provided by BotFather.",
74
77
  schema: {
75
78
  type: "object",
76
- properties: {
77
- botToken: {
78
- type: "string",
79
- title: zh ? "Bot Token" : "Bot Token",
80
- format: "password"
81
- },
82
- dmPolicy: {
83
- type: "string",
84
- title: zh ? "私聊访问" : "Private chat access",
85
- enum: [
86
- "open",
87
- "pairing",
88
- "allowlist",
89
- "disabled"
90
- ],
91
- default: "open"
92
- },
93
- apiRoot: {
94
- type: "string",
95
- title: zh ? "API Root(可选)" : "API root (optional)",
96
- placeholder: "https://api.telegram.org"
97
- },
98
- proxy: {
99
- type: "string",
100
- title: zh ? "代理(可选)" : "Proxy (optional)",
101
- placeholder: "http://127.0.0.1:7897"
102
- }
103
- },
79
+ properties: { botToken: {
80
+ type: "string",
81
+ title: "Bot Token",
82
+ format: "password"
83
+ } },
104
84
  required: ["botToken"]
105
85
  },
106
- values: {
107
- botToken: pickString(account.botToken),
108
- dmPolicy: pickDmPolicy(account.dmPolicy ?? defaults.dmPolicy ?? "pairing"),
109
- apiRoot: pickString(account.apiRoot ?? defaults.apiRoot),
110
- proxy: pickString(account.proxy ?? defaults.proxy)
111
- }
86
+ values: {}
112
87
  };
113
88
  }
114
- const telegramGatewaySetupActions = { async runAction({ actionId, input, locale }) {
89
+ const telegramGatewaySetupActions = { async runAction({ cfg, actionId, input, locale, accountId: requestedAccountId }) {
115
90
  const zh = isZh(locale);
116
- if (actionId === "setup.start") {
117
- const { loadConfig } = await import("../../../../src/config/loader.js");
91
+ const accountId = requestedAccountId || "default";
92
+ const raw = readInput(input);
93
+ const conversationId = pickString(raw.conversationId);
94
+ if (actionId === "setup.start") return {
95
+ ok: true,
96
+ payload: formPayload(locale)
97
+ };
98
+ if (actionId === "setup.verify.status") return {
99
+ ok: true,
100
+ payload: getChannelConnectionProbe("telegram", accountId, conversationId, zh)
101
+ };
102
+ if (actionId === "setup.verify.cancel") {
103
+ cancelChannelConnectionProbe("telegram", accountId, conversationId);
118
104
  return {
119
105
  ok: true,
120
- payload: formPayload(loadConfig(), locale)
106
+ payload: { type: "ok" }
121
107
  };
122
108
  }
123
- if (actionId === "setup.save") {
124
- const raw = readInput(input);
125
- if (!pickString(raw.botToken)) return {
109
+ if (actionId === "setup.verify.confirm") {
110
+ const current = existingAccount(cfg, accountId);
111
+ const dmPolicy = pickDmPolicy(current.dmPolicy ?? existingDefaults(cfg).dmPolicy);
112
+ const senderId = getChannelConnectionClaimant("telegram", accountId, conversationId, pickString(current.botToken).split(":")[0]);
113
+ if (!senderId) return {
126
114
  ok: false,
127
- message: zh ? "Bot Token 为必填项。" : "Bot Token is required."
115
+ message: zh ? "验证已结束,请重新连接。" : "Verification ended. Connect again."
116
+ };
117
+ const complete = () => {
118
+ confirmChannelConnectionProbe("telegram", accountId, conversationId);
119
+ return getChannelConnectionProbe("telegram", accountId, conversationId, zh);
120
+ };
121
+ if (dmPolicy !== "pairing") return {
122
+ ok: true,
123
+ payload: complete()
128
124
  };
129
- const { loadConfig, saveConfig } = await import("../../../../src/config/loader.js");
130
- await saveConfig(buildTelegramConfig(loadConfig(), raw));
125
+ const section = cfg.channels?.telegram;
126
+ const accounts = section.accounts;
127
+ const allowFrom = mergeDistinctSenderIds(Array.isArray(current.allowFrom) ? current.allowFrom : [], [senderId]);
131
128
  return {
132
129
  ok: true,
133
- payload: {
134
- type: "ok",
135
- message: zh ? "Telegram 配置已保存。私聊将按 pairing/允许列表策略放行。" : "Telegram configuration saved. Private chat now follows the pairing/allow-list policy.",
130
+ nextConfig: {
131
+ ...cfg,
132
+ channels: {
133
+ ...cfg.channels,
134
+ telegram: {
135
+ ...section,
136
+ accounts: {
137
+ ...accounts,
138
+ [accountId]: {
139
+ ...current,
140
+ allowFrom
141
+ }
142
+ }
143
+ }
144
+ }
145
+ },
146
+ onConfigSaved: () => ({
147
+ ...complete(),
136
148
  configChanged: true
137
- }
149
+ })
138
150
  };
139
151
  }
152
+ if (actionId === "setup.save") {
153
+ const botToken = pickString(raw.botToken);
154
+ if (!/^\d+:[a-zA-Z0-9_-]+$/.test(botToken)) return {
155
+ ok: false,
156
+ message: zh ? "请输入有效的 Bot Token。" : "Enter a valid Bot Token."
157
+ };
158
+ const previous = existingAccount(cfg, accountId);
159
+ const defaults = existingDefaults(cfg);
160
+ const apiRoot = pickString(raw.apiRoot ?? previous.apiRoot ?? defaults.apiRoot);
161
+ const proxy = pickString(raw.proxy ?? previous.proxy ?? defaults.proxy);
162
+ const timeout = createTimeoutAbortSignal(1e4);
163
+ try {
164
+ const me = await new Bot(botToken, { client: {
165
+ ...apiRoot ? { apiRoot } : {},
166
+ ...proxy ? { fetch: createProxyFetch(proxy) } : {}
167
+ } }).api.getMe(timeout.signal);
168
+ return {
169
+ ok: true,
170
+ nextConfig: buildTelegramConfig(cfg, raw, accountId),
171
+ onConfigSaved: () => startChannelConnectionProbe({
172
+ channel: "telegram",
173
+ accountId,
174
+ identity: String(me.id),
175
+ botUsername: me.username,
176
+ confirmOwner: true,
177
+ zh,
178
+ configChanged: true
179
+ })
180
+ };
181
+ } catch {
182
+ return {
183
+ ok: false,
184
+ message: zh ? "无法验证 Bot Token。请检查 Token、网络和代理。" : "Could not verify the Bot Token. Check the token, network and proxy."
185
+ };
186
+ } finally {
187
+ timeout.dispose();
188
+ }
189
+ }
140
190
  return {
141
191
  ok: false,
142
- message: `${zh ? "不支持的 Telegram 操作" : "Unsupported Telegram action"}: ${actionId}`
192
+ message: zh ? "不支持的 Telegram 操作。" : "Unsupported Telegram action."
143
193
  };
144
194
  } };
145
195
  //#endregion
@@ -2,6 +2,7 @@ import { createLogger } from "../../../../src/utils/logger/index.js";
2
2
  import { init_logger } from "../../../../src/utils/logger.js";
3
3
  import { init_config_schema, resolveTelegramStreamingMode } from "../config-schema.js";
4
4
  import { renderTelegramHtmlText } from "../format.js";
5
+ import { prefersTelegramRichMessage } from "../rich-message.js";
5
6
  import { telegramReplyTracker } from "../reply-params.js";
6
7
  import { createTelegramDraftStream } from "../draft-stream.js";
7
8
  //#region extensions/telegram/src/adapters/streaming-adapter.ts
@@ -44,7 +45,7 @@ function createTelegramStreamingAdapter(deps) {
44
45
  const replyParsed = replyToMessageId ? parseInt(replyToMessageId, 10) : NaN;
45
46
  const replyId = Number.isFinite(replyParsed) ? replyParsed : void 0;
46
47
  const isPrivate = isProbablyPrivateChat(chatId);
47
- const previewTransport = isPrivate ? "message" : "auto";
48
+ const previewTransport = isPrivate ? "auto" : "message";
48
49
  const blockCoalesce = account?.streaming?.block?.coalesce;
49
50
  const throttleMs = streamMode === "block" ? Math.max(250, blockCoalesce?.idleMs ?? BLOCK_DEFAULT_COALESCE.idleMs) : void 0;
50
51
  const draft = createTelegramDraftStream({
@@ -80,6 +81,7 @@ function createTelegramStreamingAdapter(deps) {
80
81
  blockFlushTimer.unref?.();
81
82
  };
82
83
  let skipFinalOutbound = false;
84
+ let lastText = "";
83
85
  const end = async () => {
84
86
  if (streamMode === "block") {
85
87
  if (blockFlushTimer) {
@@ -92,13 +94,14 @@ function createTelegramStreamingAdapter(deps) {
92
94
  await reasoningDraft.stop();
93
95
  reasoningDraft = null;
94
96
  }
95
- if (draft.previewMode?.() === "draft" && typeof draft.materialize === "function") {
96
- skipFinalOutbound = typeof await draft.materialize() === "number";
97
+ if (prefersTelegramRichMessage(lastText) || draft.previewMode?.() === "draft") {
98
+ await draft.clear();
97
99
  return;
98
100
  }
99
101
  await draft.flush();
100
102
  await draft.stop();
101
- skipFinalOutbound = typeof draft.messageId() === "number";
103
+ skipFinalOutbound = typeof draft.messageId() === "number" && draft.lastDeliveredText?.() === lastText.trimEnd();
104
+ if (!skipFinalOutbound) await draft.clear();
102
105
  };
103
106
  const abort = async () => {
104
107
  if (blockFlushTimer) {
@@ -114,6 +117,7 @@ function createTelegramStreamingAdapter(deps) {
114
117
  skipFinalOutbound = false;
115
118
  };
116
119
  const update = (text) => {
120
+ lastText = text;
117
121
  if (streamMode === "block") {
118
122
  pendingBlockBuffer = text;
119
123
  if (text.length >= blockMinChars) {
@@ -1,7 +1,7 @@
1
+ import { createProxyFetch } from "./proxy-fetch.js";
1
2
  import { hasTelegramBotEndpointApiRoot, normalizeTelegramApiRoot } from "./api-root.js";
2
3
  import { resolveTelegramBotToken } from "./token-resolver.js";
3
4
  import { isTelegramUnauthorizedTokenError } from "./startup-errors.js";
4
- import { createProxyFetch } from "./proxy-fetch.js";
5
5
  //#region extensions/telegram/src/doctor.ts
6
6
  const TELEGRAM_DOCTOR_GETME_TIMEOUT_MS = 1e4;
7
7
  function collectTokens(cfg) {
@@ -5,11 +5,13 @@ export type TelegramCoalescedInbound = {
5
5
  accountId: string;
6
6
  messages: Message[];
7
7
  };
8
+ type Input = {
9
+ ctx: Context;
10
+ accountId: string;
11
+ message: Message;
12
+ onReady: (batch: TelegramCoalescedInbound) => Promise<void>;
13
+ };
8
14
  export declare function createTelegramInboundCoalescer(): {
9
- enqueue(params: {
10
- ctx: Context;
11
- accountId: string;
12
- message: Message;
13
- onReady: (batch: TelegramCoalescedInbound) => Promise<void>;
14
- }): Promise<void>;
15
+ enqueue({ ctx, accountId, message, onReady }: Input): Promise<void>;
15
16
  };
17
+ export {};
@@ -4,102 +4,61 @@ const MEDIA_GROUP_GAP_MS = 800;
4
4
  const MAX_TEXT_FRAGMENTS = 12;
5
5
  const MAX_TEXT_FRAGMENT_CHARS = 5e4;
6
6
  function createTelegramInboundCoalescer() {
7
- const textFragments = /* @__PURE__ */ new Map();
8
- const mediaGroups = /* @__PURE__ */ new Map();
9
- return { async enqueue(params) {
10
- const { ctx, accountId, message, onReady } = params;
11
- const mediaGroupId = message.media_group_id;
12
- if (mediaGroupId) {
13
- await enqueueMediaGroup({
14
- key: `${accountId}:${ctx.chat?.id}:${mediaGroupId}`,
7
+ const groups = /* @__PURE__ */ new Map();
8
+ return { async enqueue({ ctx, accountId, message, onReady }) {
9
+ const album = message.media_group_id;
10
+ const fragment = (message.text?.length ?? 0) >= 3500;
11
+ if (!album && !fragment) {
12
+ await onReady({
15
13
  ctx,
16
14
  accountId,
17
- message,
18
- onReady,
19
- mediaGroups
15
+ messages: [message]
20
16
  });
21
17
  return;
22
18
  }
23
- if (message.text && message.message_id) {
24
- await enqueueTextFragment({
25
- key: `${accountId}:${ctx.chat?.id}:${ctx.from?.id}:${message.message_id}`,
26
- ctx,
27
- accountId,
28
- message,
29
- onReady,
30
- textFragments
31
- });
32
- return;
33
- }
34
- await onReady({
35
- ctx,
19
+ const key = JSON.stringify([
36
20
  accountId,
37
- messages: [message]
21
+ ctx.chat?.id,
22
+ message.message_thread_id,
23
+ ctx.from?.id,
24
+ album ?? "text"
25
+ ]);
26
+ const group = groups.get(key) ?? {
27
+ messages: [],
28
+ waiters: [],
29
+ size: 0
30
+ };
31
+ groups.set(key, group);
32
+ group.messages.push(message);
33
+ group.size += message.text?.length ?? 0;
34
+ if (group.timer) clearTimeout(group.timer);
35
+ await new Promise((resolve, reject) => {
36
+ group.waiters.push({
37
+ resolve,
38
+ reject
39
+ });
40
+ const flush = () => {
41
+ groups.delete(key);
42
+ const messages = [...group.messages].sort((a, b) => a.message_id - b.message_id);
43
+ const last = messages.at(-1);
44
+ const readyMessages = album ? messages : [{
45
+ ...last,
46
+ text: messages.map((item) => item.text ?? "").join("")
47
+ }];
48
+ Promise.resolve().then(() => onReady({
49
+ ctx,
50
+ accountId,
51
+ messages: readyMessages
52
+ })).then(() => {
53
+ for (const waiter of group.waiters) waiter.resolve();
54
+ }, (err) => {
55
+ for (const waiter of group.waiters) waiter.reject(err);
56
+ });
57
+ };
58
+ if (group.messages.length >= MAX_TEXT_FRAGMENTS || group.size >= MAX_TEXT_FRAGMENT_CHARS) flush();
59
+ else group.timer = setTimeout(flush, album ? MEDIA_GROUP_GAP_MS : TEXT_FRAGMENT_GAP_MS);
38
60
  });
39
61
  } };
40
62
  }
41
- async function enqueueMediaGroup(params) {
42
- const entry = params.mediaGroups.get(params.key) ?? {
43
- key: params.key,
44
- messages: []
45
- };
46
- entry.messages.push(params.message);
47
- if (entry.timer) clearTimeout(entry.timer);
48
- entry.timer = setTimeout(async () => {
49
- params.mediaGroups.delete(params.key);
50
- await params.onReady({
51
- ctx: params.ctx,
52
- accountId: params.accountId,
53
- messages: entry.messages
54
- });
55
- }, MEDIA_GROUP_GAP_MS);
56
- entry.timer.unref?.();
57
- params.mediaGroups.set(params.key, entry);
58
- }
59
- async function enqueueTextFragment(params) {
60
- if (!((params.message.text ?? "").length >= 3500)) {
61
- await params.onReady({
62
- ctx: params.ctx,
63
- accountId: params.accountId,
64
- messages: [params.message]
65
- });
66
- return;
67
- }
68
- const baseKey = `${params.accountId}:${params.ctx.chat?.id}:${params.ctx.from?.id}`;
69
- const entry = [...params.textFragments.values()].find((e) => e.key.startsWith(baseKey)) ?? {
70
- key: `${baseKey}:${params.message.message_id}`,
71
- messages: []
72
- };
73
- if (entry.messages.length >= MAX_TEXT_FRAGMENTS) {
74
- await flushTextFragment(entry, params);
75
- return;
76
- }
77
- entry.messages.push(params.message);
78
- if (entry.messages.reduce((n, m) => n + (m.text?.length ?? 0), 0) > MAX_TEXT_FRAGMENT_CHARS) {
79
- await flushTextFragment(entry, params);
80
- return;
81
- }
82
- if (entry.timer) clearTimeout(entry.timer);
83
- entry.timer = setTimeout(async () => {
84
- await flushTextFragment(entry, params);
85
- }, TEXT_FRAGMENT_GAP_MS);
86
- entry.timer.unref?.();
87
- params.textFragments.set(entry.key, entry);
88
- }
89
- async function flushTextFragment(entry, params) {
90
- params.textFragments.delete(entry.key);
91
- if (entry.timer) clearTimeout(entry.timer);
92
- if (entry.messages.length === 0) return;
93
- const mergedText = entry.messages.map((m) => m.text ?? "").join("");
94
- const merged = {
95
- ...entry.messages[entry.messages.length - 1],
96
- text: mergedText
97
- };
98
- await params.onReady({
99
- ctx: params.ctx,
100
- accountId: params.accountId,
101
- messages: [merged]
102
- });
103
- }
104
63
  //#endregion
105
64
  export { createTelegramInboundCoalescer };