@aka_openclaw_plugin/mychat 0.1.5 → 0.1.7

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.
@@ -0,0 +1,948 @@
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.endsWith("/ws/bot")) {} else if (url.pathname.endsWith("/ws/")) url.pathname += "bot";
210
+ else if (url.pathname.endsWith("/ws")) url.pathname += "/bot";
211
+ else url.pathname = url.pathname.replace(/\/+$/, "") + "/ws/bot";
212
+ return url.toString();
213
+ }
214
+ function scheduleReconnect() {
215
+ if (reconnectTimer) return;
216
+ reconnectTimer = setTimeout(() => {
217
+ reconnectTimer = null;
218
+ currentDelay = Math.min(currentDelay * backoffMultiplier, maxDelay);
219
+ connect();
220
+ }, currentDelay);
221
+ }
222
+ function connect() {
223
+ if (ws) return;
224
+ try {
225
+ const url = buildUrl();
226
+ const urlWithToken = new URL(url);
227
+ urlWithToken.searchParams.set("token", token);
228
+ console.log(`[mychat] WS connecting to ${urlWithToken.origin}${urlWithToken.pathname}`);
229
+ ws = new WebSocket(urlWithToken.toString());
230
+ ws.onopen = () => {
231
+ connected = true;
232
+ currentDelay = initialDelay;
233
+ if (botSelfId) ws?.send(JSON.stringify({
234
+ type: "subscribe",
235
+ body: { subscribe: { conversationId: botSelfId } }
236
+ }));
237
+ };
238
+ ws.onmessage = (event) => {
239
+ try {
240
+ const message = JSON.parse(event.data);
241
+ for (const handler of handlers) handler(message);
242
+ } catch {}
243
+ };
244
+ ws.onclose = () => {
245
+ connected = false;
246
+ ws = null;
247
+ scheduleReconnect();
248
+ };
249
+ ws.onerror = (event) => {
250
+ console.error(`[mychat] WS error:`, event);
251
+ ws?.close();
252
+ };
253
+ } catch {
254
+ scheduleReconnect();
255
+ }
256
+ }
257
+ function disconnect() {
258
+ if (reconnectTimer) {
259
+ clearTimeout(reconnectTimer);
260
+ reconnectTimer = null;
261
+ }
262
+ connected = false;
263
+ ws?.close();
264
+ ws = null;
265
+ }
266
+ return {
267
+ connect,
268
+ disconnect,
269
+ onMessage(handler) {
270
+ handlers.add(handler);
271
+ return () => {
272
+ handlers.delete(handler);
273
+ };
274
+ },
275
+ isConnected() {
276
+ return connected;
277
+ }
278
+ };
279
+ }
280
+ //#endregion
281
+ //#region src/logger.ts
282
+ const PREFIX = "mychat";
283
+ function mychatLogPrefix(feature) {
284
+ return `[${PREFIX}:${feature}]`;
285
+ }
286
+ function getMychatLogger() {
287
+ try {
288
+ const logger = ((init_runtime(), __toCommonJS(runtime_exports)).tryGetMychatRuntime?.())?.logger;
289
+ if (!logger) return null;
290
+ return {
291
+ debug: (m) => logger.debug?.(m),
292
+ info: (m) => logger.info(m),
293
+ warn: (m) => logger.warn(m),
294
+ error: (m) => logger.error(m)
295
+ };
296
+ } catch {
297
+ return null;
298
+ }
299
+ }
300
+ //#endregion
301
+ //#region src/monitor/listeners.ts
302
+ function createMychatMessageListener(params) {
303
+ const { handler } = params;
304
+ return { handle(message) {
305
+ handler.handleMessage(message).catch(() => {});
306
+ } };
307
+ }
308
+ function createMychatReactionListener(params) {
309
+ const logger = getMychatLogger();
310
+ const prefix = mychatLogPrefix("reaction");
311
+ return { handle(message) {
312
+ const emoji = message.body?.reaction;
313
+ const action = message.body?.action ?? "add";
314
+ const target = message.body?.target;
315
+ const senderId = message.from?.id;
316
+ if (logger) logger.debug(`${prefix} ${action} ${emoji} on ${target} by ${senderId}`);
317
+ } };
318
+ }
319
+ function createMychatTypingListener(params) {
320
+ const logger = getMychatLogger();
321
+ const prefix = mychatLogPrefix("typing");
322
+ return { handle(message) {
323
+ const senderId = message.from?.id;
324
+ if (senderId === params.account.accountId) return;
325
+ if (logger) logger.debug(`${prefix} from ${senderId}`);
326
+ } };
327
+ }
328
+ //#endregion
329
+ //#region src/monitor/provider.startup.ts
330
+ function createMychatProviderClients(account, botSelfId) {
331
+ return { wsClient: createMychatWsClient({
332
+ wsUrl: account.wsUrl,
333
+ token: account.token,
334
+ botSelfId,
335
+ reconnect: account.reconnect
336
+ }) };
337
+ }
338
+ function registerMychatMonitorListeners(params) {
339
+ const { account, handler, wsClient } = params;
340
+ const messageListener = createMychatMessageListener({
341
+ account,
342
+ handler
343
+ });
344
+ const reactionListener = createMychatReactionListener({ account });
345
+ const typingListener = createMychatTypingListener({ account });
346
+ wsClient.onMessage((message) => {
347
+ switch (message.type) {
348
+ case "message":
349
+ case "stream":
350
+ messageListener.handle(message);
351
+ break;
352
+ case "reaction":
353
+ reactionListener.handle(message);
354
+ break;
355
+ case "typing":
356
+ typingListener.handle(message);
357
+ break;
358
+ default: break;
359
+ }
360
+ });
361
+ }
362
+ //#endregion
363
+ //#region src/monitor/provider.lifecycle.ts
364
+ const DEFAULT_READY_TIMEOUT_MS = 15e3;
365
+ function createMychatProviderLifecycle(params) {
366
+ const { httpClient, wsClient, readyTimeoutMs = DEFAULT_READY_TIMEOUT_MS } = params;
367
+ const logger = getMychatLogger();
368
+ const prefix = mychatLogPrefix("lifecycle");
369
+ return {
370
+ async waitForReady() {
371
+ const start = Date.now();
372
+ wsClient.connect();
373
+ while (Date.now() - start < readyTimeoutMs) {
374
+ if (wsClient.isConnected()) {
375
+ const botSelf = await httpClient.getSelf();
376
+ if (botSelf) {
377
+ logger?.info(`${prefix} bot connected botId=${botSelf.botId}`);
378
+ return botSelf;
379
+ }
380
+ logger?.warn(`${prefix} ws connected but getSelf() failed`);
381
+ }
382
+ await new Promise((r) => setTimeout(r, 500));
383
+ }
384
+ const wsConnected = wsClient.isConnected();
385
+ logger?.warn(`${prefix} ready timeout wsConnected=${wsConnected} elapsedMs=${Date.now() - start}`);
386
+ return null;
387
+ },
388
+ shutdown() {
389
+ wsClient.disconnect();
390
+ logger?.info(`${prefix} shutdown`);
391
+ }
392
+ };
393
+ }
394
+ //#endregion
395
+ //#region src/monitor/inbound-dedupe.ts
396
+ const MAX_CACHE_SIZE = 500;
397
+ function createMychatInboundDedupe() {
398
+ const seen = /* @__PURE__ */ new Set();
399
+ return { isDuplicate(messageId) {
400
+ if (seen.has(messageId)) return true;
401
+ seen.add(messageId);
402
+ if (seen.size > MAX_CACHE_SIZE) {
403
+ const first = seen.values().next().value;
404
+ if (first !== void 0) seen.delete(first);
405
+ }
406
+ return false;
407
+ } };
408
+ }
409
+ //#endregion
410
+ //#region src/monitor/message-text.ts
411
+ /** Extract plain text from a WebSocket message body. */
412
+ function extractMychatMessageText(message) {
413
+ return message.body?.text ?? "";
414
+ }
415
+ /** Extract mention user IDs from a message. */
416
+ function extractMentionUserIds(message) {
417
+ return (message.body?.mentions ?? []).map((m) => m.userId).filter(Boolean);
418
+ }
419
+ /** Check if the bot is mentioned in a message. */
420
+ function isBotMentioned(message, botUserId) {
421
+ if (!botUserId) return false;
422
+ if (extractMentionUserIds(message).includes(botUserId)) return true;
423
+ return (message.body?.text ?? "").includes(`@${botUserId}`);
424
+ }
425
+ //#endregion
426
+ //#region src/monitor/message-handler.preflight.ts
427
+ /** Check if an inbound message should be accepted. */
428
+ function mychatPreflight(message, account) {
429
+ const senderId = message.from?.id;
430
+ if (!senderId) return {
431
+ allowed: false,
432
+ reason: "no-sender"
433
+ };
434
+ if (senderId === account.accountId) return {
435
+ allowed: false,
436
+ reason: "self"
437
+ };
438
+ const toKind = message.to?.kind ?? "direct";
439
+ if (toKind === "direct" || toKind === "channel") {
440
+ if (account.dmPolicy === "disabled") return {
441
+ allowed: false,
442
+ reason: "dm-disabled"
443
+ };
444
+ if (account.dmPolicy === "allowlist" && account.allowFrom.length > 0) {
445
+ if (!account.allowFrom.includes(senderId)) return {
446
+ allowed: false,
447
+ reason: "dm-not-allowed"
448
+ };
449
+ }
450
+ }
451
+ if (toKind === "group") {
452
+ if (account.groupPolicy === "disabled") return {
453
+ allowed: false,
454
+ reason: "group-disabled"
455
+ };
456
+ if (account.groupPolicy === "allowlist" && account.groupAllowFrom.length > 0) {
457
+ if (!account.groupAllowFrom.includes(senderId)) return {
458
+ allowed: false,
459
+ reason: "group-not-allowed"
460
+ };
461
+ }
462
+ const groupId = message.to?.id;
463
+ if (groupId && account.groups[groupId]) {
464
+ const groupConfig = account.groups[groupId];
465
+ if (groupConfig.enabled === false) return {
466
+ allowed: false,
467
+ reason: "group-disabled"
468
+ };
469
+ if (groupConfig.requireMention && !isBotMentioned(message, account.accountId)) return {
470
+ allowed: false,
471
+ reason: "mention-required"
472
+ };
473
+ }
474
+ if (account.requireMention && !isBotMentioned(message, account.accountId)) return {
475
+ allowed: false,
476
+ reason: "mention-required"
477
+ };
478
+ }
479
+ return { allowed: true };
480
+ }
481
+ //#endregion
482
+ //#region src/monitor/inbound-context.ts
483
+ function buildMychatInboundContext(message, account) {
484
+ if (message.type !== "message" && message.type !== "stream") return null;
485
+ const senderId = message.from?.id;
486
+ if (!senderId) return null;
487
+ const text = message.body?.text ?? "";
488
+ const toKind = message.to?.kind ?? "direct";
489
+ const chatType = toKind === "group" || toKind === "channel" ? "group" : "direct";
490
+ return {
491
+ messageId: message.id,
492
+ text,
493
+ senderId,
494
+ senderName: message.from?.name,
495
+ chatType,
496
+ conversationId: message.to?.id ?? message.body?.conversationId,
497
+ threadId: message.body?.parentId,
498
+ replyTo: message.body?.parentId,
499
+ mentions: message.body?.mentions ?? [],
500
+ attachments: message.body?.attachments ?? [],
501
+ timestamp: message.timestamp
502
+ };
503
+ }
504
+ //#endregion
505
+ //#region src/monitor/message-media.ts
506
+ /** Resolve media attachments from an inbound message. */
507
+ function resolveMychatMediaAttachments(message) {
508
+ return (message.body?.attachments ?? []).filter((a) => a.url && (a.mimeType.startsWith("image/") || a.mimeType.startsWith("video/") || a.mimeType.startsWith("audio/") || a.mimeType === "application/pdf"));
509
+ }
510
+ //#endregion
511
+ //#region src/monitor/message-handler.process.ts
512
+ /** Process an inbound message into a structured result. */
513
+ function processMychatInbound(message, account) {
514
+ const context = buildMychatInboundContext(message, account);
515
+ if (!context) return null;
516
+ return {
517
+ context,
518
+ text: extractMychatMessageText(message),
519
+ media: resolveMychatMediaAttachments(message)
520
+ };
521
+ }
522
+ //#endregion
523
+ //#region src/monitor/message-handler.ts
524
+ function createMychatMessageHandler(params) {
525
+ const { account, onInbound } = params;
526
+ const dedupe = createMychatInboundDedupe();
527
+ const logger = getMychatLogger();
528
+ const prefix = mychatLogPrefix("handler");
529
+ return { async handleMessage(message) {
530
+ if (dedupe.isDuplicate(message.id)) return;
531
+ const preflight = mychatPreflight(message, account);
532
+ if (!preflight.allowed) {
533
+ if (logger) logger.debug(`${prefix} message rejected reason=${preflight.reason} messageId=${message.id}`);
534
+ return;
535
+ }
536
+ const result = processMychatInbound(message, account);
537
+ if (!result) return;
538
+ if (logger) logger.debug(`${prefix} message accepted messageId=${result.context.messageId} chatType=${result.context.chatType}`);
539
+ await onInbound(result);
540
+ } };
541
+ }
542
+ //#endregion
543
+ //#region src/monitor/provider.ts
544
+ async function monitorMychatProvider(ctx) {
545
+ const { account, setStatus } = ctx;
546
+ const logger = getMychatLogger();
547
+ const prefix = mychatLogPrefix("provider");
548
+ if (logger) logger.info(`${prefix} starting accountId=${account.accountId}`);
549
+ setStatus({
550
+ connected: false,
551
+ mode: "websocket"
552
+ });
553
+ const httpClient = createMychatHttpClient({
554
+ baseUrl: account.baseUrl,
555
+ token: account.token
556
+ });
557
+ const botSelf = await httpClient.getSelf();
558
+ if (!botSelf) {
559
+ const error = "MyChat provider failed to get bot identity";
560
+ if (logger) logger.error(`${prefix} ${error}`);
561
+ setStatus({
562
+ connected: false,
563
+ lastError: error
564
+ });
565
+ throw new Error(error);
566
+ }
567
+ const health = await httpClient.healthCheck();
568
+ if (!health.ok) {
569
+ if (logger) logger.warn(`${prefix} health check failed latencyMs=${health.latencyMs}`);
570
+ }
571
+ const { wsClient } = createMychatProviderClients(account, botSelf.botId);
572
+ const rt = ctx.runtime;
573
+ rt.mychat = {
574
+ accountId: account.accountId,
575
+ httpClient,
576
+ wsClient,
577
+ botSelf
578
+ };
579
+ try {
580
+ setMychatRuntime(ctx.runtime);
581
+ } catch {}
582
+ registerMychatMonitorListeners({
583
+ account,
584
+ handler: createMychatMessageHandler({
585
+ account,
586
+ onInbound: async (result) => {
587
+ await dispatchMychatInbound(ctx, httpClient, result);
588
+ }
589
+ }),
590
+ wsClient
591
+ });
592
+ const lifecycle = createMychatProviderLifecycle({
593
+ httpClient,
594
+ wsClient
595
+ });
596
+ const readyBotSelf = await lifecycle.waitForReady();
597
+ if (!readyBotSelf) {
598
+ const error = "MyChat provider failed to connect";
599
+ if (logger) logger.error(`${prefix} ${error}`);
600
+ setStatus({
601
+ connected: false,
602
+ lastError: error
603
+ });
604
+ lifecycle.shutdown();
605
+ throw new Error(error);
606
+ }
607
+ setStatus({
608
+ connected: true,
609
+ lastConnectedAt: Date.now(),
610
+ lastEventAt: Date.now(),
611
+ mode: "websocket",
612
+ lastError: null
613
+ });
614
+ if (logger) logger.info(`${prefix} bot connected botId=${readyBotSelf.botId}`);
615
+ ctx.abortSignal?.addEventListener("abort", () => {
616
+ if (logger) logger.info(`${prefix} abort signal received, shutting down`);
617
+ lifecycle.shutdown();
618
+ setStatus({ connected: false });
619
+ });
620
+ return { unsubscribe() {
621
+ lifecycle.shutdown();
622
+ setStatus({ connected: false });
623
+ } };
624
+ }
625
+ /** Dispatch an inbound message through the OpenClaw turn runtime. */
626
+ async function dispatchMychatInbound(ctx, httpClient, result) {
627
+ const { runtime, cfg, account } = ctx;
628
+ const logger = getMychatLogger();
629
+ const prefix = mychatLogPrefix("dispatch");
630
+ const rt = runtime;
631
+ if (!rt.channel?.turn?.run) {
632
+ if (logger) logger.warn(`${prefix} channel turn runtime not available, skipping inbound`);
633
+ return;
634
+ }
635
+ const conversationId = result.context.conversationId ?? result.context.senderId;
636
+ const senderId = result.context.senderId;
637
+ const chatType = result.context.chatType;
638
+ const messageId = result.context.messageId;
639
+ await rt.channel.turn.run({
640
+ channel: "mychat",
641
+ accountId: account.accountId,
642
+ raw: result,
643
+ adapter: {
644
+ ingest: () => ({
645
+ id: messageId,
646
+ timestamp: result.context.timestamp,
647
+ rawText: result.text,
648
+ textForAgent: result.text,
649
+ textForCommands: result.text,
650
+ raw: result
651
+ }),
652
+ resolveTurn: (input) => {
653
+ const msgCtx = rt.channel.turn.buildContext({
654
+ channel: "mychat",
655
+ accountId: account.accountId,
656
+ timestamp: input.timestamp,
657
+ from: `mychat:user:${senderId}`,
658
+ sender: {
659
+ id: senderId,
660
+ name: result.context.senderName
661
+ },
662
+ conversation: {
663
+ kind: chatType,
664
+ id: conversationId,
665
+ label: result.context.senderName ?? senderId,
666
+ routePeer: {
667
+ kind: chatType,
668
+ id: conversationId
669
+ }
670
+ },
671
+ route: {
672
+ agentId: void 0,
673
+ accountId: account.accountId
674
+ },
675
+ reply: {
676
+ to: `mychat:${conversationId}`,
677
+ originatingTo: `mychat:${conversationId}`
678
+ },
679
+ message: {
680
+ rawBody: input.rawText,
681
+ commandBody: input.textForCommands,
682
+ bodyForAgent: input.textForAgent,
683
+ envelopeFrom: result.context.senderName
684
+ }
685
+ });
686
+ return {
687
+ cfg,
688
+ channel: "mychat",
689
+ accountId: account.accountId,
690
+ ctxPayload: msgCtx,
691
+ dispatchReplyWithBufferedBlockDispatcher: rt.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
692
+ delivery: { deliver: async (payload) => {
693
+ const text = payload.text?.trim();
694
+ if (!text) return;
695
+ const sendResult = await httpClient.sendMessage({
696
+ to: conversationId,
697
+ text,
698
+ type: chatType === "group" ? "group" : "direct"
699
+ });
700
+ if (logger) logger.debug(`${prefix} reply sent to=${conversationId} ok=${Boolean(sendResult)}`);
701
+ } }
702
+ };
703
+ }
704
+ }
705
+ });
706
+ }
707
+ //#endregion
708
+ //#region src/shared.ts
709
+ function createMychatPluginBase() {
710
+ return {
711
+ ...createChannelPluginBase({
712
+ id: "mychat",
713
+ setup: { applyAccountConfig(params) {
714
+ return params.cfg;
715
+ } },
716
+ meta: {
717
+ label: "MyChat",
718
+ docsPath: "docs/plugins/mychat",
719
+ blurb: "Connect to MyChat server via bot token",
720
+ aliases: ["mychat"]
721
+ },
722
+ capabilities: {
723
+ chatTypes: [
724
+ "direct",
725
+ "group",
726
+ "thread"
727
+ ],
728
+ reactions: true,
729
+ media: true,
730
+ threads: true
731
+ },
732
+ reload: { configPrefixes: ["channels.mychat"] },
733
+ configSchema: mychatConfigSchema,
734
+ config: {
735
+ listAccountIds(cfg) {
736
+ return resolveMychatAccounts(cfg).map((a) => a.accountId);
737
+ },
738
+ resolveAccount(cfg, accountId) {
739
+ return resolveMychatAccount({
740
+ cfg,
741
+ accountId
742
+ });
743
+ },
744
+ async inspectAccount(account) {
745
+ return {
746
+ accountId: account.accountId,
747
+ enabled: account.enabled,
748
+ label: account.name ?? account.baseUrl
749
+ };
750
+ }
751
+ }
752
+ }),
753
+ gateway: { async startAccount(ctx) {
754
+ const setStatus = createAccountStatusSink({
755
+ accountId: ctx.accountId,
756
+ setStatus: ctx.setStatus
757
+ });
758
+ return { unsubscribe: (await monitorMychatProvider({
759
+ cfg: ctx.cfg,
760
+ runtime: ctx.runtime,
761
+ account: ctx.account,
762
+ setStatus,
763
+ abortSignal: ctx.abortSignal,
764
+ log: ctx.log
765
+ })).unsubscribe };
766
+ } }
767
+ };
768
+ }
769
+ //#endregion
770
+ //#region src/outbound/outbound-payload.ts
771
+ async function sendMychatOutboundPayload(ctx, body) {
772
+ const logger = getMychatLogger();
773
+ const prefix = mychatLogPrefix("outbound");
774
+ try {
775
+ const result = await ctx.httpClient.sendMessage(body);
776
+ if (result) {
777
+ if (logger) logger.debug(`${prefix} message sent id=${result.id} status=${result.status}`);
778
+ return {
779
+ messageId: result.id,
780
+ ok: true
781
+ };
782
+ }
783
+ return { ok: false };
784
+ } catch (error) {
785
+ if (logger) logger.error(`${prefix} send failed error=${error instanceof Error ? error.message : String(error)}`);
786
+ return { ok: false };
787
+ }
788
+ }
789
+ //#endregion
790
+ //#region src/outbound/outbound-send-context.ts
791
+ function createMychatOutboundSendContext(params) {
792
+ return {
793
+ account: params.account,
794
+ httpClient: params.httpClient
795
+ };
796
+ }
797
+ //#endregion
798
+ //#region src/outbound/outbound-adapter.ts
799
+ init_runtime();
800
+ const TEXT_CHUNK_LIMIT = 4e3;
801
+ function chunkText(text, limit) {
802
+ if (text.length <= limit) return [text];
803
+ const chunks = [];
804
+ let remaining = text;
805
+ while (remaining.length > 0) {
806
+ chunks.push(remaining.slice(0, limit));
807
+ remaining = remaining.slice(limit);
808
+ }
809
+ return chunks;
810
+ }
811
+ const mychatOutbound = {
812
+ deliveryMode: "direct",
813
+ textChunkLimit: TEXT_CHUNK_LIMIT,
814
+ async sendText(params) {
815
+ const logger = getMychatLogger();
816
+ const account = getMychatRuntime().mychat;
817
+ if (!account) {
818
+ if (logger) logger.error(`${mychatLogPrefix("outbound")} no runtime account`);
819
+ return {
820
+ channel: "mychat",
821
+ messageId: "",
822
+ ok: false
823
+ };
824
+ }
825
+ const ctx = createMychatOutboundSendContext({
826
+ account: params.account ?? {},
827
+ httpClient: account.httpClient
828
+ });
829
+ const chunks = chunkText(params.text, TEXT_CHUNK_LIMIT);
830
+ let lastOk = false;
831
+ let lastMessageId = "";
832
+ for (const chunk of chunks) {
833
+ const result = await sendMychatOutboundPayload(ctx, {
834
+ to: params.target ?? "",
835
+ text: chunk,
836
+ type: params.chatType,
837
+ replyTo: params.replyTo
838
+ });
839
+ lastOk = result.ok;
840
+ if (result.messageId) lastMessageId = result.messageId;
841
+ }
842
+ return {
843
+ channel: "mychat",
844
+ messageId: lastMessageId,
845
+ ok: lastOk
846
+ };
847
+ },
848
+ async sendMedia(params) {
849
+ const logger = getMychatLogger();
850
+ const account = getMychatRuntime().mychat;
851
+ if (!account) {
852
+ if (logger) logger.error(`${mychatLogPrefix("outbound")} no runtime account`);
853
+ return {
854
+ channel: "mychat",
855
+ messageId: "",
856
+ ok: false
857
+ };
858
+ }
859
+ if (params.media) {
860
+ const uploadResult = await account.httpClient.uploadFile({
861
+ file: params.media,
862
+ filename: params.filename ?? "upload",
863
+ mimeType: params.mimeType ?? "application/octet-stream"
864
+ });
865
+ if (uploadResult) {
866
+ const result = await sendMychatOutboundPayload(createMychatOutboundSendContext({
867
+ account: params.account ?? {},
868
+ httpClient: account.httpClient
869
+ }), {
870
+ to: params.target ?? "",
871
+ text: params.text ?? "",
872
+ type: params.chatType,
873
+ attachments: [uploadResult.attachment]
874
+ });
875
+ return {
876
+ channel: "mychat",
877
+ messageId: result.messageId ?? "",
878
+ ok: result.ok
879
+ };
880
+ }
881
+ }
882
+ return {
883
+ channel: "mychat",
884
+ messageId: "",
885
+ ok: false
886
+ };
887
+ },
888
+ async sendPayload(params) {
889
+ const logger = getMychatLogger();
890
+ const account = getMychatRuntime().mychat;
891
+ if (!account) {
892
+ if (logger) logger.error(`${mychatLogPrefix("outbound")} no runtime account`);
893
+ return {
894
+ channel: "mychat",
895
+ messageId: "",
896
+ ok: false
897
+ };
898
+ }
899
+ const result = await sendMychatOutboundPayload(createMychatOutboundSendContext({
900
+ account: params.account ?? {},
901
+ httpClient: account.httpClient
902
+ }), {
903
+ to: params.target ?? "",
904
+ text: params.text ?? "",
905
+ type: params.chatType,
906
+ replyTo: params.replyTo
907
+ });
908
+ return {
909
+ channel: "mychat",
910
+ messageId: result.messageId ?? "",
911
+ ok: result.ok
912
+ };
913
+ }
914
+ };
915
+ //#endregion
916
+ //#region src/channel.ts
917
+ const mychatPlugin = createChatChannelPlugin({
918
+ base: createMychatPluginBase(),
919
+ security: { dm: {
920
+ channelKey: "dmPolicy",
921
+ resolvePolicy(account) {
922
+ return account.dmPolicy ?? "open";
923
+ },
924
+ resolveAllowFrom(account) {
925
+ return account.allowFrom;
926
+ }
927
+ } },
928
+ pairing: { text: {
929
+ idLabel: "MyChat Username",
930
+ message: "To connect to MyChat, configure your bot token and server URL in the channel config.",
931
+ notify() {}
932
+ } },
933
+ threading: {
934
+ replyToMode: "always",
935
+ resolveReplyTo(params) {
936
+ return {
937
+ threadId: params.inbound?.threadId ?? params.inbound?.conversationId,
938
+ replyTo: params.inbound?.messageId
939
+ };
940
+ },
941
+ sanitizeThreadName(name) {
942
+ return name.slice(0, 100).replace(/[^\w\s-]/g, "");
943
+ }
944
+ },
945
+ outbound: mychatOutbound
946
+ });
947
+ //#endregion
948
+ export { mychatPlugin as t };