@aka_openclaw_plugin/mychat 0.1.4 → 0.1.5

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.
@@ -1,946 +0,0 @@
1
- import { i as setMychatRuntime, n as init_runtime, o as __toCommonJS, r as runtime_exports, t as getMychatRuntime } from "./runtime-7z_VfQ27.js";
2
- import { t as mychatConfigSchema } from "./config-schema-C42X7OSY.js";
3
- import { createChannelPluginBase, createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
4
- import { createAccountStatusSink } from "openclaw/plugin-sdk/channel-lifecycle";
5
- import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "openclaw/plugin-sdk/channel-plugin-common";
6
- //#region src/accounts.ts
7
- const DEFAULT_DM_POLICY = "open";
8
- const DEFAULT_GROUP_POLICY = "open";
9
- const DEFAULT_HISTORY_LIMIT = 50;
10
- const DEFAULT_MEDIA_MAX_MB = 10;
11
- function resolveWsUrl(baseUrl) {
12
- const url = new URL(baseUrl);
13
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
14
- url.pathname = url.pathname.replace(/\/+$/, "") + "/ws/bot";
15
- return url.toString();
16
- }
17
- function mergeAccountConfig(channel, account) {
18
- if (!account) return channel;
19
- return {
20
- ...channel,
21
- ...account,
22
- actions: {
23
- messages: account.actions?.messages ?? channel.actions?.messages ?? true,
24
- threads: account.actions?.threads ?? channel.actions?.threads ?? true,
25
- reactions: account.actions?.reactions ?? channel.actions?.reactions ?? true
26
- },
27
- groups: {
28
- ...channel.groups ?? {},
29
- ...account.groups ?? {}
30
- },
31
- reconnect: account.reconnect ?? channel.reconnect
32
- };
33
- }
34
- function resolveMychatAccounts(cfg) {
35
- const mychatConfig = cfg.channels?.mychat;
36
- if (!mychatConfig) return [];
37
- const accounts = mychatConfig.accounts ?? {};
38
- const accountIds = Object.keys(accounts);
39
- if (accountIds.length === 0) {
40
- const resolved = resolveSingleAccount({
41
- accountId: DEFAULT_ACCOUNT_ID,
42
- config: mychatConfig
43
- });
44
- return resolved ? [resolved] : [];
45
- }
46
- return accountIds.map((id) => {
47
- return resolveSingleAccount({
48
- accountId: id,
49
- config: mergeAccountConfig(mychatConfig, accounts[id])
50
- });
51
- }).filter(Boolean);
52
- }
53
- function resolveSingleAccount(params) {
54
- const { accountId, config } = params;
55
- const enabled = config.enabled ?? true;
56
- if (!enabled) return null;
57
- const token = resolveToken(config);
58
- if (!token) return null;
59
- const baseUrl = config.baseUrl.replace(/\/+$/, "");
60
- const wsUrl = config.wsUrl ?? resolveWsUrl(baseUrl);
61
- return {
62
- accountId: normalizeAccountId(accountId),
63
- enabled,
64
- name: config.name,
65
- baseUrl,
66
- wsUrl,
67
- token,
68
- defaultTo: config.defaultTo,
69
- dmPolicy: config.dmPolicy ?? DEFAULT_DM_POLICY,
70
- groupPolicy: config.groupPolicy ?? DEFAULT_GROUP_POLICY,
71
- allowFrom: config.allowFrom ?? [],
72
- groupAllowFrom: config.groupAllowFrom ?? [],
73
- requireMention: config.requireMention ?? false,
74
- historyLimit: config.historyLimit ?? DEFAULT_HISTORY_LIMIT,
75
- mediaMaxMb: config.mediaMaxMb ?? DEFAULT_MEDIA_MAX_MB,
76
- actions: {
77
- messages: config.actions?.messages ?? true,
78
- threads: config.actions?.threads ?? true,
79
- reactions: config.actions?.reactions ?? true
80
- },
81
- groups: config.groups ?? {},
82
- reconnect: config.reconnect ?? {}
83
- };
84
- }
85
- function resolveToken(config) {
86
- if (config.token) return config.token;
87
- if (typeof process !== "undefined") {
88
- const envToken = process.env.MYCHAT_BOT_TOKEN;
89
- if (envToken) return envToken;
90
- }
91
- return null;
92
- }
93
- function resolveMychatAccount(params) {
94
- const accounts = resolveMychatAccounts(params.cfg);
95
- if (accounts.length === 0) return null;
96
- if (!params.accountId) return accounts[0];
97
- return accounts.find((a) => a.accountId === params.accountId) ?? accounts[0] ?? null;
98
- }
99
- //#endregion
100
- //#region src/client/http-client.ts
101
- function createMychatHttpClient(params) {
102
- const { baseUrl, token } = params;
103
- const base = baseUrl.replace(/\/+$/, "");
104
- async function request(method, path, body) {
105
- try {
106
- const headers = { authorization: `Bearer ${token}` };
107
- if (body !== void 0) headers["content-type"] = "application/json";
108
- const response = await fetch(`${base}${path}`, {
109
- method,
110
- headers,
111
- body: body !== void 0 ? JSON.stringify(body) : void 0
112
- });
113
- if (!response.ok) {
114
- console.error(`[mychat] HTTP ${method} ${path} failed: ${response.status} ${response.statusText}`);
115
- return null;
116
- }
117
- return await response.json();
118
- } catch (err) {
119
- console.error(`[mychat] HTTP ${method} ${path} error:`, err);
120
- return null;
121
- }
122
- }
123
- return {
124
- async getSelf() {
125
- return request("GET", "/api/bot/self");
126
- },
127
- async getMe() {
128
- return request("GET", "/api/auth/me");
129
- },
130
- async sendMessage(body) {
131
- return request("POST", "/api/bot/messages", body);
132
- },
133
- async listMessages(params) {
134
- const searchParams = new URLSearchParams();
135
- if (params.conversationId) searchParams.set("conversationId", params.conversationId);
136
- if (params.limit) searchParams.set("limit", String(params.limit));
137
- if (params.after) searchParams.set("after", String(params.after));
138
- const qs = searchParams.toString();
139
- return (await request("GET", `/api/bot/messages${qs ? `?${qs}` : ""}`))?.messages ?? [];
140
- },
141
- async addReaction(messageId, body) {
142
- return request("POST", `/api/bot/messages/${messageId}/reactions`, body);
143
- },
144
- async removeReaction(messageId, emoji) {
145
- return request("POST", `/api/bot/messages/${messageId}/reactions`, {
146
- emoji,
147
- action: "remove"
148
- });
149
- },
150
- async uploadFile(params) {
151
- try {
152
- const formData = new FormData();
153
- let blob;
154
- if (params.file instanceof Blob) blob = params.file;
155
- else {
156
- const bytes = new Uint8Array(params.file.buffer, params.file.byteOffset, params.file.byteLength);
157
- blob = new Blob([bytes], { type: params.mimeType });
158
- }
159
- formData.append("file", blob, params.filename);
160
- if (params.scopeKind) formData.append("scopeKind", params.scopeKind);
161
- if (params.scopeId) formData.append("scopeId", params.scopeId);
162
- const response = await fetch(`${base}/api/bot/uploads`, {
163
- method: "POST",
164
- headers: { authorization: `Bearer ${token}` },
165
- body: formData
166
- });
167
- if (!response.ok) return null;
168
- return await response.json();
169
- } catch {
170
- return null;
171
- }
172
- },
173
- async healthCheck() {
174
- const start = Date.now();
175
- try {
176
- const response = await fetch(`${base}/health`);
177
- const latencyMs = Date.now() - start;
178
- return {
179
- ok: response.ok,
180
- latencyMs
181
- };
182
- } catch {
183
- return {
184
- ok: false,
185
- latencyMs: Date.now() - start
186
- };
187
- }
188
- }
189
- };
190
- }
191
- //#endregion
192
- //#region src/client/ws-client.ts
193
- init_runtime();
194
- const DEFAULT_INITIAL_DELAY_MS = 1e3;
195
- const DEFAULT_MAX_DELAY_MS = 3e4;
196
- const DEFAULT_BACKOFF_MULTIPLIER = 2;
197
- function createMychatWsClient(params) {
198
- const { wsUrl, token, botSelfId, reconnect } = params;
199
- const initialDelay = reconnect?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
200
- const maxDelay = reconnect?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
201
- const backoffMultiplier = reconnect?.backoffMultiplier ?? DEFAULT_BACKOFF_MULTIPLIER;
202
- let ws = null;
203
- let connected = false;
204
- let reconnectTimer = null;
205
- let currentDelay = initialDelay;
206
- const handlers = /* @__PURE__ */ new Set();
207
- function buildUrl() {
208
- const url = new URL(wsUrl);
209
- if (!url.pathname.includes("/ws/bot")) url.pathname = url.pathname.replace(/\/+$/, "") + "/ws/bot";
210
- return url.toString();
211
- }
212
- function scheduleReconnect() {
213
- if (reconnectTimer) return;
214
- reconnectTimer = setTimeout(() => {
215
- reconnectTimer = null;
216
- currentDelay = Math.min(currentDelay * backoffMultiplier, maxDelay);
217
- connect();
218
- }, currentDelay);
219
- }
220
- function connect() {
221
- if (ws) return;
222
- try {
223
- const url = buildUrl();
224
- const urlWithToken = new URL(url);
225
- urlWithToken.searchParams.set("token", token);
226
- console.log(`[mychat] WS connecting to ${urlWithToken.origin}${urlWithToken.pathname}`);
227
- ws = new WebSocket(urlWithToken.toString());
228
- ws.onopen = () => {
229
- connected = true;
230
- currentDelay = initialDelay;
231
- if (botSelfId) ws?.send(JSON.stringify({
232
- type: "subscribe",
233
- body: { subscribe: { conversationId: botSelfId } }
234
- }));
235
- };
236
- ws.onmessage = (event) => {
237
- try {
238
- const message = JSON.parse(event.data);
239
- for (const handler of handlers) handler(message);
240
- } catch {}
241
- };
242
- ws.onclose = () => {
243
- connected = false;
244
- ws = null;
245
- scheduleReconnect();
246
- };
247
- ws.onerror = (event) => {
248
- console.error(`[mychat] WS error:`, event);
249
- ws?.close();
250
- };
251
- } catch {
252
- scheduleReconnect();
253
- }
254
- }
255
- function disconnect() {
256
- if (reconnectTimer) {
257
- clearTimeout(reconnectTimer);
258
- reconnectTimer = null;
259
- }
260
- connected = false;
261
- ws?.close();
262
- ws = null;
263
- }
264
- return {
265
- connect,
266
- disconnect,
267
- onMessage(handler) {
268
- handlers.add(handler);
269
- return () => {
270
- handlers.delete(handler);
271
- };
272
- },
273
- isConnected() {
274
- return connected;
275
- }
276
- };
277
- }
278
- //#endregion
279
- //#region src/logger.ts
280
- const PREFIX = "mychat";
281
- function mychatLogPrefix(feature) {
282
- return `[${PREFIX}:${feature}]`;
283
- }
284
- function getMychatLogger() {
285
- try {
286
- const logger = ((init_runtime(), __toCommonJS(runtime_exports)).tryGetMychatRuntime?.())?.logger;
287
- if (!logger) return null;
288
- return {
289
- debug: (m) => logger.debug?.(m),
290
- info: (m) => logger.info(m),
291
- warn: (m) => logger.warn(m),
292
- error: (m) => logger.error(m)
293
- };
294
- } catch {
295
- return null;
296
- }
297
- }
298
- //#endregion
299
- //#region src/monitor/listeners.ts
300
- function createMychatMessageListener(params) {
301
- const { handler } = params;
302
- return { handle(message) {
303
- handler.handleMessage(message).catch(() => {});
304
- } };
305
- }
306
- function createMychatReactionListener(params) {
307
- const logger = getMychatLogger();
308
- const prefix = mychatLogPrefix("reaction");
309
- return { handle(message) {
310
- const emoji = message.body?.reaction;
311
- const action = message.body?.action ?? "add";
312
- const target = message.body?.target;
313
- const senderId = message.from?.id;
314
- if (logger) logger.debug(`${prefix} ${action} ${emoji} on ${target} by ${senderId}`);
315
- } };
316
- }
317
- function createMychatTypingListener(params) {
318
- const logger = getMychatLogger();
319
- const prefix = mychatLogPrefix("typing");
320
- return { handle(message) {
321
- const senderId = message.from?.id;
322
- if (senderId === params.account.accountId) return;
323
- if (logger) logger.debug(`${prefix} from ${senderId}`);
324
- } };
325
- }
326
- //#endregion
327
- //#region src/monitor/provider.startup.ts
328
- function createMychatProviderClients(account, botSelfId) {
329
- return { wsClient: createMychatWsClient({
330
- wsUrl: account.wsUrl,
331
- token: account.token,
332
- botSelfId,
333
- reconnect: account.reconnect
334
- }) };
335
- }
336
- function registerMychatMonitorListeners(params) {
337
- const { account, handler, wsClient } = params;
338
- const messageListener = createMychatMessageListener({
339
- account,
340
- handler
341
- });
342
- const reactionListener = createMychatReactionListener({ account });
343
- const typingListener = createMychatTypingListener({ account });
344
- wsClient.onMessage((message) => {
345
- switch (message.type) {
346
- case "message":
347
- case "stream":
348
- messageListener.handle(message);
349
- break;
350
- case "reaction":
351
- reactionListener.handle(message);
352
- break;
353
- case "typing":
354
- typingListener.handle(message);
355
- break;
356
- default: break;
357
- }
358
- });
359
- }
360
- //#endregion
361
- //#region src/monitor/provider.lifecycle.ts
362
- const DEFAULT_READY_TIMEOUT_MS = 15e3;
363
- function createMychatProviderLifecycle(params) {
364
- const { httpClient, wsClient, readyTimeoutMs = DEFAULT_READY_TIMEOUT_MS } = params;
365
- const logger = getMychatLogger();
366
- const prefix = mychatLogPrefix("lifecycle");
367
- return {
368
- async waitForReady() {
369
- const start = Date.now();
370
- wsClient.connect();
371
- while (Date.now() - start < readyTimeoutMs) {
372
- if (wsClient.isConnected()) {
373
- const botSelf = await httpClient.getSelf();
374
- if (botSelf) {
375
- logger?.info(`${prefix} bot connected botId=${botSelf.botId}`);
376
- return botSelf;
377
- }
378
- logger?.warn(`${prefix} ws connected but getSelf() failed`);
379
- }
380
- await new Promise((r) => setTimeout(r, 500));
381
- }
382
- const wsConnected = wsClient.isConnected();
383
- logger?.warn(`${prefix} ready timeout wsConnected=${wsConnected} elapsedMs=${Date.now() - start}`);
384
- return null;
385
- },
386
- shutdown() {
387
- wsClient.disconnect();
388
- logger?.info(`${prefix} shutdown`);
389
- }
390
- };
391
- }
392
- //#endregion
393
- //#region src/monitor/inbound-dedupe.ts
394
- const MAX_CACHE_SIZE = 500;
395
- function createMychatInboundDedupe() {
396
- const seen = /* @__PURE__ */ new Set();
397
- return { isDuplicate(messageId) {
398
- if (seen.has(messageId)) return true;
399
- seen.add(messageId);
400
- if (seen.size > MAX_CACHE_SIZE) {
401
- const first = seen.values().next().value;
402
- if (first !== void 0) seen.delete(first);
403
- }
404
- return false;
405
- } };
406
- }
407
- //#endregion
408
- //#region src/monitor/message-text.ts
409
- /** Extract plain text from a WebSocket message body. */
410
- function extractMychatMessageText(message) {
411
- return message.body?.text ?? "";
412
- }
413
- /** Extract mention user IDs from a message. */
414
- function extractMentionUserIds(message) {
415
- return (message.body?.mentions ?? []).map((m) => m.userId).filter(Boolean);
416
- }
417
- /** Check if the bot is mentioned in a message. */
418
- function isBotMentioned(message, botUserId) {
419
- if (!botUserId) return false;
420
- if (extractMentionUserIds(message).includes(botUserId)) return true;
421
- return (message.body?.text ?? "").includes(`@${botUserId}`);
422
- }
423
- //#endregion
424
- //#region src/monitor/message-handler.preflight.ts
425
- /** Check if an inbound message should be accepted. */
426
- function mychatPreflight(message, account) {
427
- const senderId = message.from?.id;
428
- if (!senderId) return {
429
- allowed: false,
430
- reason: "no-sender"
431
- };
432
- if (senderId === account.accountId) return {
433
- allowed: false,
434
- reason: "self"
435
- };
436
- const toKind = message.to?.kind ?? "direct";
437
- if (toKind === "direct" || toKind === "channel") {
438
- if (account.dmPolicy === "disabled") return {
439
- allowed: false,
440
- reason: "dm-disabled"
441
- };
442
- if (account.dmPolicy === "allowlist" && account.allowFrom.length > 0) {
443
- if (!account.allowFrom.includes(senderId)) return {
444
- allowed: false,
445
- reason: "dm-not-allowed"
446
- };
447
- }
448
- }
449
- if (toKind === "group") {
450
- if (account.groupPolicy === "disabled") return {
451
- allowed: false,
452
- reason: "group-disabled"
453
- };
454
- if (account.groupPolicy === "allowlist" && account.groupAllowFrom.length > 0) {
455
- if (!account.groupAllowFrom.includes(senderId)) return {
456
- allowed: false,
457
- reason: "group-not-allowed"
458
- };
459
- }
460
- const groupId = message.to?.id;
461
- if (groupId && account.groups[groupId]) {
462
- const groupConfig = account.groups[groupId];
463
- if (groupConfig.enabled === false) return {
464
- allowed: false,
465
- reason: "group-disabled"
466
- };
467
- if (groupConfig.requireMention && !isBotMentioned(message, account.accountId)) return {
468
- allowed: false,
469
- reason: "mention-required"
470
- };
471
- }
472
- if (account.requireMention && !isBotMentioned(message, account.accountId)) return {
473
- allowed: false,
474
- reason: "mention-required"
475
- };
476
- }
477
- return { allowed: true };
478
- }
479
- //#endregion
480
- //#region src/monitor/inbound-context.ts
481
- function buildMychatInboundContext(message, account) {
482
- if (message.type !== "message" && message.type !== "stream") return null;
483
- const senderId = message.from?.id;
484
- if (!senderId) return null;
485
- const text = message.body?.text ?? "";
486
- const toKind = message.to?.kind ?? "direct";
487
- const chatType = toKind === "group" || toKind === "channel" ? "group" : "direct";
488
- return {
489
- messageId: message.id,
490
- text,
491
- senderId,
492
- senderName: message.from?.name,
493
- chatType,
494
- conversationId: message.to?.id ?? message.body?.conversationId,
495
- threadId: message.body?.parentId,
496
- replyTo: message.body?.parentId,
497
- mentions: message.body?.mentions ?? [],
498
- attachments: message.body?.attachments ?? [],
499
- timestamp: message.timestamp
500
- };
501
- }
502
- //#endregion
503
- //#region src/monitor/message-media.ts
504
- /** Resolve media attachments from an inbound message. */
505
- function resolveMychatMediaAttachments(message) {
506
- return (message.body?.attachments ?? []).filter((a) => a.url && (a.mimeType.startsWith("image/") || a.mimeType.startsWith("video/") || a.mimeType.startsWith("audio/") || a.mimeType === "application/pdf"));
507
- }
508
- //#endregion
509
- //#region src/monitor/message-handler.process.ts
510
- /** Process an inbound message into a structured result. */
511
- function processMychatInbound(message, account) {
512
- const context = buildMychatInboundContext(message, account);
513
- if (!context) return null;
514
- return {
515
- context,
516
- text: extractMychatMessageText(message),
517
- media: resolveMychatMediaAttachments(message)
518
- };
519
- }
520
- //#endregion
521
- //#region src/monitor/message-handler.ts
522
- function createMychatMessageHandler(params) {
523
- const { account, onInbound } = params;
524
- const dedupe = createMychatInboundDedupe();
525
- const logger = getMychatLogger();
526
- const prefix = mychatLogPrefix("handler");
527
- return { async handleMessage(message) {
528
- if (dedupe.isDuplicate(message.id)) return;
529
- const preflight = mychatPreflight(message, account);
530
- if (!preflight.allowed) {
531
- if (logger) logger.debug(`${prefix} message rejected reason=${preflight.reason} messageId=${message.id}`);
532
- return;
533
- }
534
- const result = processMychatInbound(message, account);
535
- if (!result) return;
536
- if (logger) logger.debug(`${prefix} message accepted messageId=${result.context.messageId} chatType=${result.context.chatType}`);
537
- await onInbound(result);
538
- } };
539
- }
540
- //#endregion
541
- //#region src/monitor/provider.ts
542
- async function monitorMychatProvider(ctx) {
543
- const { account, setStatus } = ctx;
544
- const logger = getMychatLogger();
545
- const prefix = mychatLogPrefix("provider");
546
- if (logger) logger.info(`${prefix} starting accountId=${account.accountId}`);
547
- setStatus({
548
- connected: false,
549
- mode: "websocket"
550
- });
551
- const httpClient = createMychatHttpClient({
552
- baseUrl: account.baseUrl,
553
- token: account.token
554
- });
555
- const botSelf = await httpClient.getSelf();
556
- if (!botSelf) {
557
- const error = "MyChat provider failed to get bot identity";
558
- if (logger) logger.error(`${prefix} ${error}`);
559
- setStatus({
560
- connected: false,
561
- lastError: error
562
- });
563
- throw new Error(error);
564
- }
565
- const health = await httpClient.healthCheck();
566
- if (!health.ok) {
567
- if (logger) logger.warn(`${prefix} health check failed latencyMs=${health.latencyMs}`);
568
- }
569
- const { wsClient } = createMychatProviderClients(account, botSelf.botId);
570
- const rt = ctx.runtime;
571
- rt.mychat = {
572
- accountId: account.accountId,
573
- httpClient,
574
- wsClient,
575
- botSelf
576
- };
577
- try {
578
- setMychatRuntime(ctx.runtime);
579
- } catch {}
580
- registerMychatMonitorListeners({
581
- account,
582
- handler: createMychatMessageHandler({
583
- account,
584
- onInbound: async (result) => {
585
- await dispatchMychatInbound(ctx, httpClient, result);
586
- }
587
- }),
588
- wsClient
589
- });
590
- const lifecycle = createMychatProviderLifecycle({
591
- httpClient,
592
- wsClient
593
- });
594
- const readyBotSelf = await lifecycle.waitForReady();
595
- if (!readyBotSelf) {
596
- const error = "MyChat provider failed to connect";
597
- if (logger) logger.error(`${prefix} ${error}`);
598
- setStatus({
599
- connected: false,
600
- lastError: error
601
- });
602
- lifecycle.shutdown();
603
- throw new Error(error);
604
- }
605
- setStatus({
606
- connected: true,
607
- lastConnectedAt: Date.now(),
608
- lastEventAt: Date.now(),
609
- mode: "websocket",
610
- lastError: null
611
- });
612
- if (logger) logger.info(`${prefix} bot connected botId=${readyBotSelf.botId}`);
613
- ctx.abortSignal?.addEventListener("abort", () => {
614
- if (logger) logger.info(`${prefix} abort signal received, shutting down`);
615
- lifecycle.shutdown();
616
- setStatus({ connected: false });
617
- });
618
- return { unsubscribe() {
619
- lifecycle.shutdown();
620
- setStatus({ connected: false });
621
- } };
622
- }
623
- /** Dispatch an inbound message through the OpenClaw turn runtime. */
624
- async function dispatchMychatInbound(ctx, httpClient, result) {
625
- const { runtime, cfg, account } = ctx;
626
- const logger = getMychatLogger();
627
- const prefix = mychatLogPrefix("dispatch");
628
- const rt = runtime;
629
- if (!rt.channel?.turn?.run) {
630
- if (logger) logger.warn(`${prefix} channel turn runtime not available, skipping inbound`);
631
- return;
632
- }
633
- const conversationId = result.context.conversationId ?? result.context.senderId;
634
- const senderId = result.context.senderId;
635
- const chatType = result.context.chatType;
636
- const messageId = result.context.messageId;
637
- await rt.channel.turn.run({
638
- channel: "mychat",
639
- accountId: account.accountId,
640
- raw: result,
641
- adapter: {
642
- ingest: () => ({
643
- id: messageId,
644
- timestamp: result.context.timestamp,
645
- rawText: result.text,
646
- textForAgent: result.text,
647
- textForCommands: result.text,
648
- raw: result
649
- }),
650
- resolveTurn: (input) => {
651
- const msgCtx = rt.channel.turn.buildContext({
652
- channel: "mychat",
653
- accountId: account.accountId,
654
- timestamp: input.timestamp,
655
- from: `mychat:user:${senderId}`,
656
- sender: {
657
- id: senderId,
658
- name: result.context.senderName
659
- },
660
- conversation: {
661
- kind: chatType,
662
- id: conversationId,
663
- label: result.context.senderName ?? senderId,
664
- routePeer: {
665
- kind: chatType,
666
- id: conversationId
667
- }
668
- },
669
- route: {
670
- agentId: void 0,
671
- accountId: account.accountId
672
- },
673
- reply: {
674
- to: `mychat:${conversationId}`,
675
- originatingTo: `mychat:${conversationId}`
676
- },
677
- message: {
678
- rawBody: input.rawText,
679
- commandBody: input.textForCommands,
680
- bodyForAgent: input.textForAgent,
681
- envelopeFrom: result.context.senderName
682
- }
683
- });
684
- return {
685
- cfg,
686
- channel: "mychat",
687
- accountId: account.accountId,
688
- ctxPayload: msgCtx,
689
- dispatchReplyWithBufferedBlockDispatcher: rt.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
690
- delivery: { deliver: async (payload) => {
691
- const text = payload.text?.trim();
692
- if (!text) return;
693
- const sendResult = await httpClient.sendMessage({
694
- to: conversationId,
695
- text,
696
- type: chatType === "group" ? "group" : "direct"
697
- });
698
- if (logger) logger.debug(`${prefix} reply sent to=${conversationId} ok=${Boolean(sendResult)}`);
699
- } }
700
- };
701
- }
702
- }
703
- });
704
- }
705
- //#endregion
706
- //#region src/shared.ts
707
- function createMychatPluginBase() {
708
- return {
709
- ...createChannelPluginBase({
710
- id: "mychat",
711
- setup: { applyAccountConfig(params) {
712
- return params.cfg;
713
- } },
714
- meta: {
715
- label: "MyChat",
716
- docsPath: "docs/plugins/mychat",
717
- blurb: "Connect to MyChat server via bot token",
718
- aliases: ["mychat"]
719
- },
720
- capabilities: {
721
- chatTypes: [
722
- "direct",
723
- "group",
724
- "thread"
725
- ],
726
- reactions: true,
727
- media: true,
728
- threads: true
729
- },
730
- reload: { configPrefixes: ["channels.mychat"] },
731
- configSchema: mychatConfigSchema,
732
- config: {
733
- listAccountIds(cfg) {
734
- return resolveMychatAccounts(cfg).map((a) => a.accountId);
735
- },
736
- resolveAccount(cfg, accountId) {
737
- return resolveMychatAccount({
738
- cfg,
739
- accountId
740
- });
741
- },
742
- async inspectAccount(account) {
743
- return {
744
- accountId: account.accountId,
745
- enabled: account.enabled,
746
- label: account.name ?? account.baseUrl
747
- };
748
- }
749
- }
750
- }),
751
- gateway: { async startAccount(ctx) {
752
- const setStatus = createAccountStatusSink({
753
- accountId: ctx.accountId,
754
- setStatus: ctx.setStatus
755
- });
756
- return { unsubscribe: (await monitorMychatProvider({
757
- cfg: ctx.cfg,
758
- runtime: ctx.runtime,
759
- account: ctx.account,
760
- setStatus,
761
- abortSignal: ctx.abortSignal,
762
- log: ctx.log
763
- })).unsubscribe };
764
- } }
765
- };
766
- }
767
- //#endregion
768
- //#region src/outbound/outbound-payload.ts
769
- async function sendMychatOutboundPayload(ctx, body) {
770
- const logger = getMychatLogger();
771
- const prefix = mychatLogPrefix("outbound");
772
- try {
773
- const result = await ctx.httpClient.sendMessage(body);
774
- if (result) {
775
- if (logger) logger.debug(`${prefix} message sent id=${result.id} status=${result.status}`);
776
- return {
777
- messageId: result.id,
778
- ok: true
779
- };
780
- }
781
- return { ok: false };
782
- } catch (error) {
783
- if (logger) logger.error(`${prefix} send failed error=${error instanceof Error ? error.message : String(error)}`);
784
- return { ok: false };
785
- }
786
- }
787
- //#endregion
788
- //#region src/outbound/outbound-send-context.ts
789
- function createMychatOutboundSendContext(params) {
790
- return {
791
- account: params.account,
792
- httpClient: params.httpClient
793
- };
794
- }
795
- //#endregion
796
- //#region src/outbound/outbound-adapter.ts
797
- init_runtime();
798
- const TEXT_CHUNK_LIMIT = 4e3;
799
- function chunkText(text, limit) {
800
- if (text.length <= limit) return [text];
801
- const chunks = [];
802
- let remaining = text;
803
- while (remaining.length > 0) {
804
- chunks.push(remaining.slice(0, limit));
805
- remaining = remaining.slice(limit);
806
- }
807
- return chunks;
808
- }
809
- const mychatOutbound = {
810
- deliveryMode: "direct",
811
- textChunkLimit: TEXT_CHUNK_LIMIT,
812
- async sendText(params) {
813
- const logger = getMychatLogger();
814
- const account = getMychatRuntime().mychat;
815
- if (!account) {
816
- if (logger) logger.error(`${mychatLogPrefix("outbound")} no runtime account`);
817
- return {
818
- channel: "mychat",
819
- messageId: "",
820
- ok: false
821
- };
822
- }
823
- const ctx = createMychatOutboundSendContext({
824
- account: params.account ?? {},
825
- httpClient: account.httpClient
826
- });
827
- const chunks = chunkText(params.text, TEXT_CHUNK_LIMIT);
828
- let lastOk = false;
829
- let lastMessageId = "";
830
- for (const chunk of chunks) {
831
- const result = await sendMychatOutboundPayload(ctx, {
832
- to: params.target ?? "",
833
- text: chunk,
834
- type: params.chatType,
835
- replyTo: params.replyTo
836
- });
837
- lastOk = result.ok;
838
- if (result.messageId) lastMessageId = result.messageId;
839
- }
840
- return {
841
- channel: "mychat",
842
- messageId: lastMessageId,
843
- ok: lastOk
844
- };
845
- },
846
- async sendMedia(params) {
847
- const logger = getMychatLogger();
848
- const account = getMychatRuntime().mychat;
849
- if (!account) {
850
- if (logger) logger.error(`${mychatLogPrefix("outbound")} no runtime account`);
851
- return {
852
- channel: "mychat",
853
- messageId: "",
854
- ok: false
855
- };
856
- }
857
- if (params.media) {
858
- const uploadResult = await account.httpClient.uploadFile({
859
- file: params.media,
860
- filename: params.filename ?? "upload",
861
- mimeType: params.mimeType ?? "application/octet-stream"
862
- });
863
- if (uploadResult) {
864
- const result = await sendMychatOutboundPayload(createMychatOutboundSendContext({
865
- account: params.account ?? {},
866
- httpClient: account.httpClient
867
- }), {
868
- to: params.target ?? "",
869
- text: params.text ?? "",
870
- type: params.chatType,
871
- attachments: [uploadResult.attachment]
872
- });
873
- return {
874
- channel: "mychat",
875
- messageId: result.messageId ?? "",
876
- ok: result.ok
877
- };
878
- }
879
- }
880
- return {
881
- channel: "mychat",
882
- messageId: "",
883
- ok: false
884
- };
885
- },
886
- async sendPayload(params) {
887
- const logger = getMychatLogger();
888
- const account = getMychatRuntime().mychat;
889
- if (!account) {
890
- if (logger) logger.error(`${mychatLogPrefix("outbound")} no runtime account`);
891
- return {
892
- channel: "mychat",
893
- messageId: "",
894
- ok: false
895
- };
896
- }
897
- const result = await sendMychatOutboundPayload(createMychatOutboundSendContext({
898
- account: params.account ?? {},
899
- httpClient: account.httpClient
900
- }), {
901
- to: params.target ?? "",
902
- text: params.text ?? "",
903
- type: params.chatType,
904
- replyTo: params.replyTo
905
- });
906
- return {
907
- channel: "mychat",
908
- messageId: result.messageId ?? "",
909
- ok: result.ok
910
- };
911
- }
912
- };
913
- //#endregion
914
- //#region src/channel.ts
915
- const mychatPlugin = createChatChannelPlugin({
916
- base: createMychatPluginBase(),
917
- security: { dm: {
918
- channelKey: "dmPolicy",
919
- resolvePolicy(account) {
920
- return account.dmPolicy ?? "open";
921
- },
922
- resolveAllowFrom(account) {
923
- return account.allowFrom;
924
- }
925
- } },
926
- pairing: { text: {
927
- idLabel: "MyChat Username",
928
- message: "To connect to MyChat, configure your bot token and server URL in the channel config.",
929
- notify() {}
930
- } },
931
- threading: {
932
- replyToMode: "always",
933
- resolveReplyTo(params) {
934
- return {
935
- threadId: params.inbound?.threadId ?? params.inbound?.conversationId,
936
- replyTo: params.inbound?.messageId
937
- };
938
- },
939
- sanitizeThreadName(name) {
940
- return name.slice(0, 100).replace(/[^\w\s-]/g, "");
941
- }
942
- },
943
- outbound: mychatOutbound
944
- });
945
- //#endregion
946
- export { mychatPlugin as t };