@asabot/core 0.1.0 → 0.2.1

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 (170) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +93 -14
  3. package/asabot.config.example.yaml +47 -29
  4. package/dist/adapters/feishu/adapter.d.ts +19 -0
  5. package/dist/adapters/feishu/adapter.js +621 -0
  6. package/dist/adapters/feishu/api.d.ts +142 -0
  7. package/dist/adapters/feishu/api.js +306 -0
  8. package/dist/adapters/feishu/bot.d.ts +95 -0
  9. package/dist/adapters/feishu/bot.js +539 -0
  10. package/dist/adapters/feishu/cards.d.ts +93 -0
  11. package/dist/adapters/feishu/cards.js +106 -0
  12. package/dist/adapters/feishu/config.d.ts +13 -0
  13. package/dist/adapters/feishu/config.js +36 -0
  14. package/dist/adapters/feishu/events.d.ts +33 -0
  15. package/dist/adapters/feishu/events.js +14 -0
  16. package/dist/adapters/feishu/index.d.ts +8 -0
  17. package/dist/adapters/feishu/index.js +5 -0
  18. package/dist/adapters/feishu/message.d.ts +64 -0
  19. package/dist/adapters/feishu/message.js +197 -0
  20. package/dist/adapters/feishu/transport.d.ts +34 -0
  21. package/dist/adapters/feishu/transport.js +110 -0
  22. package/dist/adapters/index.d.ts +1 -7
  23. package/dist/adapters/index.js +75 -6
  24. package/dist/adapters/loader.d.ts +6 -0
  25. package/dist/adapters/loader.js +73 -0
  26. package/dist/adapters/media-source.d.ts +7 -0
  27. package/dist/adapters/media-source.js +137 -0
  28. package/dist/adapters/onebot11/adapter.d.ts +5 -0
  29. package/dist/adapters/onebot11/adapter.js +23 -11
  30. package/dist/adapters/onebot11/api.d.ts +4 -1
  31. package/dist/adapters/onebot11/api.js +21 -8
  32. package/dist/adapters/onebot11/errors.d.ts +3 -0
  33. package/dist/adapters/onebot11/errors.js +6 -0
  34. package/dist/adapters/virtual/index.js +7 -1
  35. package/dist/adapters/wecom/adapter.d.ts +14 -0
  36. package/dist/adapters/wecom/adapter.js +220 -0
  37. package/dist/adapters/wecom/bot.d.ts +71 -0
  38. package/dist/adapters/wecom/bot.js +312 -0
  39. package/dist/adapters/wecom/cards.d.ts +37 -0
  40. package/dist/adapters/wecom/cards.js +30 -0
  41. package/dist/adapters/wecom/config.d.ts +8 -0
  42. package/dist/adapters/wecom/config.js +10 -0
  43. package/dist/adapters/wecom/events.d.ts +93 -0
  44. package/dist/adapters/wecom/events.js +46 -0
  45. package/dist/adapters/wecom/index.d.ts +7 -0
  46. package/dist/adapters/wecom/index.js +21 -0
  47. package/dist/adapters/wecom/media.d.ts +50 -0
  48. package/dist/adapters/wecom/media.js +149 -0
  49. package/dist/adapters/wecom/message.d.ts +151 -0
  50. package/dist/adapters/wecom/message.js +116 -0
  51. package/dist/adapters/wecom/transport.d.ts +39 -0
  52. package/dist/adapters/wecom/transport.js +116 -0
  53. package/dist/adapters/weixin-clawbot/adapter.d.ts +16 -0
  54. package/dist/adapters/weixin-clawbot/adapter.js +173 -0
  55. package/dist/adapters/weixin-clawbot/bot.d.ts +41 -0
  56. package/dist/adapters/weixin-clawbot/bot.js +254 -0
  57. package/dist/adapters/weixin-clawbot/index.d.ts +2 -0
  58. package/dist/adapters/weixin-clawbot/index.js +19 -0
  59. package/dist/adapters/weixin-clawbot/media.d.ts +57 -0
  60. package/dist/adapters/weixin-clawbot/media.js +196 -0
  61. package/dist/adapters/weixin-clawbot/message.d.ts +12 -0
  62. package/dist/adapters/weixin-clawbot/message.js +79 -0
  63. package/dist/adapters/weixin-clawbot/protocol.d.ts +145 -0
  64. package/dist/adapters/weixin-clawbot/protocol.js +178 -0
  65. package/dist/adapters/weixin-clawbot/setup.d.ts +2 -0
  66. package/dist/adapters/weixin-clawbot/setup.js +121 -0
  67. package/dist/bootstrap.d.ts +5 -0
  68. package/dist/bootstrap.js +5 -20
  69. package/dist/cli.js +9 -3
  70. package/dist/core/adapter.d.ts +69 -3
  71. package/dist/core/adapter.js +11 -1
  72. package/dist/core/app.d.ts +12 -9
  73. package/dist/core/app.js +50 -51
  74. package/dist/core/bot-accounts.d.ts +28 -0
  75. package/dist/core/bot-accounts.js +78 -0
  76. package/dist/core/bot-policies.d.ts +30 -0
  77. package/dist/core/bot-policies.js +112 -0
  78. package/dist/core/bot.d.ts +19 -1
  79. package/dist/core/bot.js +13 -0
  80. package/dist/core/capabilities.d.ts +54 -0
  81. package/dist/core/capabilities.js +25 -0
  82. package/dist/core/config/schema.d.ts +61 -8
  83. package/dist/core/config/schema.js +15 -3
  84. package/dist/core/config/write.js +5 -1
  85. package/dist/core/connections.d.ts +84 -0
  86. package/dist/core/connections.js +326 -0
  87. package/dist/core/delivery.d.ts +53 -0
  88. package/dist/core/delivery.js +115 -0
  89. package/dist/core/dispatch/api.d.ts +3 -1
  90. package/dist/core/dispatch/api.js +12 -5
  91. package/dist/core/dispatch/dispatcher.d.ts +1 -0
  92. package/dist/core/dispatch/dispatcher.js +35 -15
  93. package/dist/core/dispatch/outgoing.d.ts +1 -0
  94. package/dist/core/dispatch/outgoing.js +5 -3
  95. package/dist/core/dispatch/trace.d.ts +2 -0
  96. package/dist/core/dispatch/types.d.ts +6 -0
  97. package/dist/core/dispatch/types.js +1 -2
  98. package/dist/core/errors.d.ts +4 -1
  99. package/dist/core/errors.js +7 -1
  100. package/dist/core/event/session.d.ts +3 -1
  101. package/dist/core/event/session.js +7 -4
  102. package/dist/core/event/types.d.ts +5 -1
  103. package/dist/core/identity.d.ts +18 -0
  104. package/dist/core/identity.js +31 -0
  105. package/dist/core/logger.js +9 -2
  106. package/dist/core/message/segment.js +3 -13
  107. package/dist/core/message/types.d.ts +2 -0
  108. package/dist/core/permission.d.ts +2 -1
  109. package/dist/core/permission.js +7 -2
  110. package/dist/core/plugin/context.d.ts +17 -11
  111. package/dist/core/plugin/context.js +48 -21
  112. package/dist/core/plugin/definition.d.ts +7 -0
  113. package/dist/core/plugin/execution.d.ts +3 -0
  114. package/dist/core/plugin/execution.js +3 -0
  115. package/dist/core/plugin/icon.d.ts +2 -0
  116. package/dist/core/plugin/icon.js +14 -0
  117. package/dist/core/plugin/manager.d.ts +26 -7
  118. package/dist/core/plugin/manager.js +179 -56
  119. package/dist/core/plugin/packages.d.ts +4 -0
  120. package/dist/core/plugin/packages.js +39 -9
  121. package/dist/core/plugin/tasks.d.ts +131 -24
  122. package/dist/core/plugin/tasks.js +517 -117
  123. package/dist/core/plugin/types.d.ts +14 -0
  124. package/dist/core/ratelimit.js +6 -1
  125. package/dist/core/storage/index.d.ts +3 -1
  126. package/dist/core/storage/index.js +52 -2
  127. package/dist/core/target.d.ts +24 -6
  128. package/dist/core/target.js +26 -6
  129. package/dist/core/utils/merge.d.ts +3 -0
  130. package/dist/core/utils/merge.js +18 -0
  131. package/dist/core/utils/redact.d.ts +6 -0
  132. package/dist/core/utils/redact.js +76 -0
  133. package/dist/index.d.ts +14 -6
  134. package/dist/index.js +7 -2
  135. package/dist/plugins/admin.js +30 -3
  136. package/dist/plugins/help.js +1 -0
  137. package/dist/plugins/history.d.ts +4 -0
  138. package/dist/plugins/history.js +13 -3
  139. package/dist/plugins/http.js +1 -0
  140. package/dist/plugins/long-message.js +20 -12
  141. package/dist/plugins/status.js +1 -0
  142. package/dist/server/auth.d.ts +5 -1
  143. package/dist/server/auth.js +11 -7
  144. package/dist/server/connection-setups.d.ts +126 -0
  145. package/dist/server/connection-setups.js +188 -0
  146. package/dist/server/groups.d.ts +1 -0
  147. package/dist/server/groups.js +8 -8
  148. package/dist/server/index.d.ts +1 -0
  149. package/dist/server/index.js +230 -29
  150. package/dist/server/schemas.d.ts +6 -2
  151. package/dist/server/settings.d.ts +66 -20
  152. package/dist/server/settings.js +158 -61
  153. package/dist/server/views.d.ts +97 -17
  154. package/dist/server/views.js +48 -13
  155. package/dist/testing/create-test-app.js +2 -2
  156. package/dist/testing/dispatch-fixture.js +2 -1
  157. package/dist/testing/fake-bot.d.ts +2 -1
  158. package/dist/testing/fake-bot.js +4 -1
  159. package/docs/DEPLOY.md +211 -0
  160. package/docs/FEISHU.md +170 -0
  161. package/docs/WECOM.md +107 -0
  162. package/docs/WEIXIN-CLAWBOT.md +56 -0
  163. package/package.json +29 -3
  164. package/web/dist/assets/index-ogXTSYEt.css +2 -0
  165. package/web/dist/assets/index-r9XycpMd.js +51 -0
  166. package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-CIohfKSa.js} +3 -3
  167. package/web/dist/index.html +2 -2
  168. package/web/dist/plugin-pages/_sdk.js +26 -1
  169. package/web/dist/assets/index-BI5GCpiI.css +0 -2
  170. package/web/dist/assets/index-C-rshHwD.js +0 -51
@@ -0,0 +1,116 @@
1
+ import { WSAuthFailureError, WSClient, WSReconnectExhaustedError, WsCmd, } from '@wecom/aibot-node-sdk';
2
+ import { z } from 'zod';
3
+ const sdkLogger = {
4
+ debug() { },
5
+ info() { },
6
+ warn() { },
7
+ error() { },
8
+ };
9
+ const ackSchema = z.object({ errcode: z.number().int() });
10
+ const messageAck = z.object({ body: z.object({ msgid: z.string().min(1) }) });
11
+ const uploadAck = z.object({ media_id: z.string().min(1) });
12
+ class WecomRequestError extends Error {
13
+ code;
14
+ platformCode;
15
+ constructor(message, code, platformCode) {
16
+ super(message);
17
+ this.name = 'WecomRequestError';
18
+ this.code = code;
19
+ this.platformCode = platformCode;
20
+ }
21
+ }
22
+ export function classifyWecomSend(error) {
23
+ if (error instanceof WecomRequestError)
24
+ return { code: error.code, platformCode: error.platformCode };
25
+ }
26
+ async function request(operation, execute) {
27
+ try {
28
+ return await execute();
29
+ }
30
+ catch (error) {
31
+ const ack = ackSchema.safeParse(error);
32
+ if (ack.success && ack.data.errcode !== 0) {
33
+ const code = ack.data.errcode;
34
+ throw new WecomRequestError(`企业微信${operation}被拒绝(错误码 ${code})`, code === 45009 || code === 45011 ? 'RATE_LIMITED' : 'DELIVERY_REJECTED', code);
35
+ }
36
+ // The SDK exposes typed server frames, but these transport failures are plain Error objects.
37
+ const message = error instanceof Error ? error.message : '';
38
+ if (/^Reply ack timeout \(\d+ms\) for reqId: /.test(message))
39
+ throw new WecomRequestError('企业微信等待发送回执超时', 'DELIVERY_TIMEOUT');
40
+ if (/^Reply queue for reqId .+ exceeds max size \(\d+\)$/.test(message))
41
+ throw new WecomRequestError('企业微信回复队列已满', 'RATE_LIMITED');
42
+ if (message === 'WebSocket not connected, unable to send data')
43
+ throw new WecomRequestError('企业微信未上线', 'NO_BOT_ONLINE');
44
+ throw new WecomRequestError(`企业微信${operation}未收到有效回执`, 'DELIVERY_UNCONFIRMED');
45
+ }
46
+ }
47
+ function acknowledged(frame) {
48
+ const ack = ackSchema.parse(frame);
49
+ if (ack.errcode !== 0)
50
+ throw ack;
51
+ return messageAck.safeParse(frame).data?.body.msgid;
52
+ }
53
+ export class SDKTransport {
54
+ #client;
55
+ #subscribeTimeout;
56
+ #reconnectInterval;
57
+ #timer;
58
+ constructor(config, { wsUrl, subscribeTimeout = 10_000, reconnectInterval = 1_000, } = {}) {
59
+ this.#subscribeTimeout = subscribeTimeout;
60
+ this.#reconnectInterval = reconnectInterval;
61
+ this.#client = new WSClient({
62
+ botId: config.botId,
63
+ secret: config.secret,
64
+ wsUrl,
65
+ wsOptions: { handshakeTimeout: 10_000, maxPayload: 1024 * 1024 },
66
+ logger: sdkLogger,
67
+ reconnectInterval,
68
+ maxReconnectAttempts: -1,
69
+ maxAuthFailureAttempts: 0,
70
+ maxReplyQueueSize: 32,
71
+ });
72
+ }
73
+ start(handlers) {
74
+ this.#client
75
+ .on('connected', () => {
76
+ handlers.connecting();
77
+ this.#timer = setTimeout(() => handlers.failed('企业微信订阅超时,请检查网络后手动重连'), this.#subscribeTimeout).unref();
78
+ })
79
+ .on('authenticated', () => {
80
+ clearTimeout(this.#timer);
81
+ handlers.ready();
82
+ })
83
+ .on('disconnected', () => {
84
+ clearTimeout(this.#timer);
85
+ handlers.disconnected();
86
+ })
87
+ .on('reconnecting', (attempt) => handlers.retrying(Math.min(this.#reconnectInterval * 2 ** (attempt - 1), 30_000)))
88
+ .on('error', (error) => {
89
+ if (error instanceof WSAuthFailureError)
90
+ handlers.failed('企业微信认证失败,请核对 BotID 和 Secret 后手动重连');
91
+ else if (error instanceof WSReconnectExhaustedError)
92
+ handlers.failed('企业微信重连失败,请检查网络后手动重连');
93
+ })
94
+ .on('event.disconnected_event', () => handlers.failed('此 BotID 已在另一实例上线,请停止另一实例后手动重连'))
95
+ .on('message', handlers.message)
96
+ .on('event.enter_chat', handlers.event)
97
+ .on('event.template_card_event', handlers.event)
98
+ .on('event.feedback_event', handlers.event)
99
+ .connect();
100
+ }
101
+ close() {
102
+ clearTimeout(this.#timer);
103
+ this.#client.removeAllListeners();
104
+ this.#client.disconnect();
105
+ }
106
+ send(target, body) {
107
+ const payload = { ...body, chat_type: target.type === 'private' ? 1 : 2 };
108
+ return request('主动发送', async () => acknowledged(await this.#client.sendMessage(target.id, payload)));
109
+ }
110
+ reply(reqId, body, command = WsCmd.RESPONSE) {
111
+ return request('回调回复', async () => acknowledged(await this.#client.reply({ headers: { req_id: reqId } }, body, command)));
112
+ }
113
+ upload(bytes, options) {
114
+ return request('上传媒体', async () => uploadAck.parse(await this.#client.uploadMedia(bytes, options)).media_id);
115
+ }
116
+ }
@@ -0,0 +1,16 @@
1
+ import type { Adapter, AdapterHost } from '../../core/adapter.ts';
2
+ import { type Account } from './protocol.ts';
3
+ export declare class WeixinAdapter implements Adapter {
4
+ readonly platform = "weixin-clawbot";
5
+ private config;
6
+ private readonly host;
7
+ private readonly connection;
8
+ private running?;
9
+ constructor(config: Account, host: AdapterHost);
10
+ start(): Promise<void>;
11
+ stop(): Promise<void>;
12
+ reconfigure(config: unknown): Promise<void>;
13
+ private poll;
14
+ private notify;
15
+ private receive;
16
+ }
@@ -0,0 +1,173 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { setTimeout as sleep } from 'node:timers/promises';
3
+ import { createSession } from '../../core/event/index.js';
4
+ import { LruSet } from '../../core/utils/lru.js';
5
+ import { contextKey, WeixinBot } from './bot.js';
6
+ import { accountSchema, errorSchema, IlinkError, ilink, ilinkOrigin, itemSchema, platform, readInbound, updatesSchema, } from './protocol.js';
7
+ const cursorKey = 'updates';
8
+ const expiredMessage = '微信授权已失效,请重新扫码';
9
+ export class WeixinAdapter {
10
+ platform = platform;
11
+ config;
12
+ host;
13
+ connection;
14
+ running;
15
+ constructor(config, host) {
16
+ if (!host.connection)
17
+ throw new Error('微信 ClawBot 需要独立的连接');
18
+ this.connection = host.connection;
19
+ this.config = config;
20
+ this.host = host;
21
+ }
22
+ async start() {
23
+ if (this.running)
24
+ return;
25
+ const { selfId, token, apiBaseUrl } = this.config;
26
+ const origin = ilinkOrigin(apiBaseUrl);
27
+ const controller = new AbortController();
28
+ const { signal } = controller;
29
+ const store = this.connection.store;
30
+ const cursor = store.get(cursorKey) ?? '';
31
+ let expired = false;
32
+ const request = async (operation, schema, data, timeout, operationSignal) => {
33
+ try {
34
+ return await ilink(new URL(`/ilink/bot/${operation}`, origin), operation, schema, operationSignal ? AbortSignal.any([signal, operationSignal]) : signal, { data, token, timeout });
35
+ }
36
+ catch (error) {
37
+ if (!signal.aborted && error instanceof IlinkError && error.expired) {
38
+ expired = true;
39
+ controller.abort();
40
+ bot.setStatus('offline');
41
+ this.connection.update({ state: 'reauthorize', error: expiredMessage, nextRetryAt: undefined });
42
+ }
43
+ throw error;
44
+ }
45
+ };
46
+ const bot = new WeixinBot(selfId, this.host, store, request, signal);
47
+ this.host.registerBot(bot);
48
+ this.host.setBotInfo(bot, { connection: 'iLink HTTPS 长轮询' });
49
+ this.connection.update({ state: 'connecting' });
50
+ this.running = {
51
+ bot,
52
+ controller,
53
+ poll: this.poll(bot, store, request, signal, cursor),
54
+ notifyStop: async () => {
55
+ if (!expired)
56
+ await this.notify('notifystop', bot, () => ilink(new URL('/ilink/bot/msg/notifystop', origin), '停止通知', errorSchema, AbortSignal.timeout(2000), { data: {}, token, timeout: 2000 }));
57
+ },
58
+ };
59
+ }
60
+ async stop() {
61
+ const running = this.running;
62
+ if (!running)
63
+ return;
64
+ running.controller.abort();
65
+ running.bot.setStatus('offline');
66
+ try {
67
+ await running.poll;
68
+ await running.notifyStop();
69
+ }
70
+ finally {
71
+ this.host.unregisterBot(running.bot);
72
+ this.running = undefined;
73
+ }
74
+ }
75
+ async reconfigure(config) {
76
+ const next = accountSchema.parse(config);
77
+ await this.stop();
78
+ this.config = next;
79
+ await this.start();
80
+ }
81
+ async poll(bot, store, request, signal, initialCursor) {
82
+ await this.notify('notifystart', bot, () => request('msg/notifystart', errorSchema, {}, 3000), signal);
83
+ let cursor = initialCursor;
84
+ let timeout = 40_000;
85
+ let failures = 0;
86
+ const seen = new LruSet(2048);
87
+ while (!signal.aborted) {
88
+ const startedAt = Date.now();
89
+ let delay;
90
+ try {
91
+ const updates = await request('getupdates', updatesSchema, { get_updates_buf: cursor }, timeout);
92
+ if (signal.aborted)
93
+ return;
94
+ bot.setStatus('online');
95
+ for (const payload of updates.msgs ?? [])
96
+ this.receive(bot, store, seen, payload);
97
+ if (updates.get_updates_buf && updates.get_updates_buf !== cursor) {
98
+ store.set(cursorKey, updates.get_updates_buf);
99
+ cursor = updates.get_updates_buf;
100
+ }
101
+ if (updates.longpolling_timeout_ms)
102
+ timeout = Math.min(updates.longpolling_timeout_ms + 5000, 120_000);
103
+ failures = 0;
104
+ delay = Math.max(0, 250 - (Date.now() - startedAt));
105
+ }
106
+ catch (error) {
107
+ if (signal.aborted)
108
+ return;
109
+ bot.setStatus('offline');
110
+ const reason = error instanceof IlinkError
111
+ ? error.message
112
+ : error instanceof DOMException && error.name === 'TimeoutError'
113
+ ? '微信长轮询超时'
114
+ : '微信消息同步失败';
115
+ delay = Math.min(1000 * 2 ** failures++, 30_000);
116
+ this.connection.update({ state: 'retrying', error: reason, nextRetryAt: Date.now() + delay });
117
+ this.host.logger.warn({ selfId: bot.selfId, reason }, 'Weixin ClawBot polling failed');
118
+ }
119
+ if (delay) {
120
+ try {
121
+ await sleep(delay, undefined, { signal, ref: false });
122
+ }
123
+ catch (error) {
124
+ if (!signal.aborted)
125
+ throw error;
126
+ }
127
+ }
128
+ }
129
+ }
130
+ async notify(operation, bot, send, signal) {
131
+ try {
132
+ await send();
133
+ }
134
+ catch {
135
+ if (!signal?.aborted)
136
+ this.host.logger.debug({ selfId: bot.selfId, operation }, 'Weixin ClawBot lifecycle notification failed');
137
+ }
138
+ }
139
+ receive(bot, store, seen, payload) {
140
+ const inbound = readInbound(payload);
141
+ const userId = inbound?.from_user_id;
142
+ if (!userId || (this.host.ignoreSelf && userId === bot.selfId))
143
+ return;
144
+ const items = (inbound.item_list ?? []).flatMap((item) => {
145
+ const parsed = itemSchema.safeParse(item);
146
+ return parsed.success ? [parsed.data] : [];
147
+ });
148
+ const messageId = inbound.message_id ?? items.find((item) => item.msg_id)?.msg_id ?? randomUUID();
149
+ const key = JSON.stringify([userId, messageId]);
150
+ if (seen.has(key))
151
+ return;
152
+ if (inbound.context_token)
153
+ store.set(contextKey(userId), inbound.context_token);
154
+ const message = bot.incoming(userId, messageId, items);
155
+ if (message.length) {
156
+ const actor = { platform, selfId: bot.selfId, userId };
157
+ this.host.emit(createSession({
158
+ ...actor,
159
+ id: randomUUID(),
160
+ bot,
161
+ time: inbound.create_time_ms || Date.now(),
162
+ raw: undefined,
163
+ messageId,
164
+ messageType: 'private',
165
+ message,
166
+ sender: { userId, nickname: userId },
167
+ isSuperuser: this.host.isSuperuser(actor),
168
+ isBotAdmin: this.host.isBotAdmin(actor),
169
+ }, this.host.sessionServices));
170
+ }
171
+ seen.add(key);
172
+ }
173
+ }
@@ -0,0 +1,41 @@
1
+ import type { AdapterHost } from '../../core/adapter.ts';
2
+ import type { Bot, BotCapabilities, SendResult } from '../../core/bot.ts';
3
+ import { type Sendable } from '../../core/message/index.ts';
4
+ import { WeixinMessages } from './message.ts';
5
+ import { type IlinkRequest } from './protocol.ts';
6
+ export declare const weixinCapabilities: BotCapabilities;
7
+ export type ConnectionStore = NonNullable<AdapterHost['connection']>['store'];
8
+ export declare const contextKey: (userId: string) => string;
9
+ export declare class WeixinBot implements Bot {
10
+ #private;
11
+ readonly platform = "weixin-clawbot";
12
+ readonly capabilities: BotCapabilities;
13
+ readonly selfId: string;
14
+ constructor(selfId: string, host: AdapterHost, store: ConnectionStore, request: IlinkRequest, signal: AbortSignal);
15
+ readonly weixin: {
16
+ downloadMedia: (file: string, format?: 'original' | 'wav') => Promise<Buffer>;
17
+ setTyping: (userId: string, typing?: boolean) => Promise<void>;
18
+ };
19
+ incoming(...args: Parameters<WeixinMessages['incoming']>): import("../../core/message/types.ts").Message;
20
+ get status(): Bot['status'];
21
+ setStatus(status: 'online' | 'offline'): void;
22
+ sendPrivate(userId: string, content: Sendable): Promise<SendResult>;
23
+ getSelf(): Promise<{
24
+ userId: string;
25
+ nickname: string;
26
+ }>;
27
+ sendGroup(): Promise<never>;
28
+ sendForward(): Promise<never>;
29
+ getForward(): Promise<never>;
30
+ deleteMessage(): Promise<never>;
31
+ getMessage(): Promise<never>;
32
+ getGroupList(): Promise<never>;
33
+ getGroupMember(): Promise<never>;
34
+ getGroupMembers(): Promise<never>;
35
+ muteMember(): Promise<never>;
36
+ kickMember(): Promise<never>;
37
+ setMemberCard(): Promise<never>;
38
+ getFriendList(): Promise<never>;
39
+ call(action: string): Promise<never>;
40
+ }
41
+ export declare function isWeixinClawBot(bot: Bot): bot is WeixinBot;
@@ -0,0 +1,254 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { DeliveryAttempt, DeliveryError } from '../../core/delivery.js';
4
+ import { dispatchContext } from '../../core/dispatch/trace.js';
5
+ import { NotConnectedError, UnsupportedError } from '../../core/errors.js';
6
+ import { isSegment, normalizeSendable, seg } from '../../core/message/index.js';
7
+ import { WeixinMedia } from './media.js';
8
+ import { WeixinMessages } from './message.js';
9
+ import { errorSchema, IlinkError, platform, sentSchema, typingSchema } from './protocol.js';
10
+ export const weixinCapabilities = {
11
+ segments: ['text', 'image', 'video', 'file'],
12
+ textStyles: [],
13
+ actions: ['sendPrivate', 'getSelf', 'weixin-clawbot.downloadMedia', 'weixin-clawbot.setTyping'],
14
+ };
15
+ const maxText = 4000;
16
+ const formatSchema = z.enum(['original', 'wav']).default('original');
17
+ const downloadArgs = z.tuple([z.string().min(1), formatSchema]);
18
+ const typingArgs = z.tuple([z.string().regex(/^\S+$/).max(512), z.boolean()]);
19
+ export const contextKey = (userId) => `context:${userId}`;
20
+ function classifyIlinkSend(error) {
21
+ if (error instanceof DOMException && error.name === 'TimeoutError')
22
+ return { code: 'DELIVERY_TIMEOUT' };
23
+ if (!(error instanceof IlinkError))
24
+ return undefined;
25
+ const { httpStatus, platformCode } = error;
26
+ if (error.expired)
27
+ return { code: 'NO_BOT_ONLINE', platformCode, message: '微信 ClawBot 授权已失效,请重新扫码' };
28
+ if (httpStatus === 429)
29
+ return { code: 'RATE_LIMITED' };
30
+ if (httpStatus === 408 || httpStatus === 504)
31
+ return { code: 'DELIVERY_TIMEOUT' };
32
+ if (platformCode !== undefined || (httpStatus !== undefined && httpStatus >= 400 && httpStatus < 500))
33
+ return { code: 'DELIVERY_REJECTED', platformCode };
34
+ }
35
+ function* splitText(text) {
36
+ let offset = 0;
37
+ let part = '';
38
+ for (const point of text) {
39
+ if (offset + point.length > maxText) {
40
+ yield part;
41
+ offset = 0;
42
+ part = '';
43
+ }
44
+ part += point;
45
+ offset += point.length;
46
+ }
47
+ if (part)
48
+ yield part;
49
+ }
50
+ export class WeixinBot {
51
+ platform = platform;
52
+ capabilities = weixinCapabilities;
53
+ selfId;
54
+ #status = 'connecting';
55
+ #host;
56
+ #request;
57
+ #store;
58
+ #media;
59
+ #messages;
60
+ #tickets = new Map();
61
+ constructor(selfId, host, store, request, signal) {
62
+ this.selfId = selfId;
63
+ this.#host = host;
64
+ this.#store = store;
65
+ this.#request = request;
66
+ this.#media = new WeixinMedia(signal);
67
+ this.#messages = new WeixinMessages(this.#media);
68
+ }
69
+ weixin = {
70
+ downloadMedia: async (file, format = 'original') => {
71
+ const result = await this.#host.invokeApi({ bot: this, method: 'weixin-clawbot.downloadMedia', args: [file, format] }, async (args) => {
72
+ const [handle, output] = downloadArgs.parse(args);
73
+ return this.#media.download(handle, output);
74
+ });
75
+ if (!Buffer.isBuffer(result))
76
+ throw new TypeError('媒体下载必须返回 Buffer');
77
+ return result;
78
+ },
79
+ setTyping: async (userId, typing = true) => {
80
+ await this.#host.invokeApi({ bot: this, method: 'weixin-clawbot.setTyping', args: [userId, typing] }, async (args) => {
81
+ const [peer, active] = typingArgs.parse(args);
82
+ await this.#setTyping(peer, active);
83
+ });
84
+ },
85
+ };
86
+ incoming(...args) {
87
+ return this.#messages.incoming(...args);
88
+ }
89
+ get status() {
90
+ return this.#status;
91
+ }
92
+ setStatus(status) {
93
+ if (this.#status === status)
94
+ return;
95
+ this.#status = status;
96
+ const fields = {
97
+ id: randomUUID(),
98
+ platform,
99
+ selfId: this.selfId,
100
+ time: Date.now(),
101
+ raw: undefined,
102
+ kind: 'internal',
103
+ bot: this,
104
+ };
105
+ this.#host.emit(status === 'online'
106
+ ? { ...fields, name: 'bot.online', status }
107
+ : { ...fields, name: 'bot.offline', status });
108
+ }
109
+ sendPrivate(userId, content) {
110
+ const attempt = new DeliveryAttempt(this, { type: 'private', id: userId });
111
+ return attempt.run(() => this.#send(attempt, userId, content));
112
+ }
113
+ async #send(attempt, userId, content) {
114
+ this.#assertOnline();
115
+ const prepared = await this.#host.prepareOutgoing({
116
+ bot: this,
117
+ target: { type: 'private', id: userId },
118
+ message: normalizeSendable(content),
119
+ });
120
+ if (!Array.isArray(prepared))
121
+ return prepared.sent;
122
+ const contextToken = this.#context(userId);
123
+ let last;
124
+ for (const segment of prepared) {
125
+ if (isSegment(segment, 'text')) {
126
+ for (const text of splitText(segment.data.text)) {
127
+ last = await this.#deliver(attempt, userId, contextToken, { type: 1, text_item: { text } }, seg.text(text));
128
+ }
129
+ }
130
+ else if (isSegment(segment, 'image') || isSegment(segment, 'video') || isSegment(segment, 'file')) {
131
+ const uploaded = await this.#media.upload(userId, segment, this.#request);
132
+ last = await this.#deliver(attempt, userId, contextToken, uploaded.item, uploaded.segment);
133
+ }
134
+ }
135
+ if (!last)
136
+ throw new Error('没有可发送的消息内容');
137
+ return last;
138
+ }
139
+ async #deliver(attempt, userId, contextToken, item, segment) {
140
+ this.#assertOnline();
141
+ const clientId = randomUUID();
142
+ const response = await attempt.request(() => this.#request('sendmessage', sentSchema, {
143
+ msg: {
144
+ from_user_id: '',
145
+ to_user_id: userId,
146
+ client_id: clientId,
147
+ message_type: 2,
148
+ message_state: 2,
149
+ context_token: contextToken,
150
+ item_list: [item],
151
+ },
152
+ }), classifyIlinkSend);
153
+ const messageId = response.message_id ?? clientId;
154
+ const sent = attempt.confirm({ messageId });
155
+ this.#messages.remember(userId, messageId, [segment]);
156
+ const context = dispatchContext.getStore();
157
+ this.#host.emit({
158
+ id: randomUUID(),
159
+ kind: 'internal',
160
+ name: 'bot.message.sent',
161
+ time: Date.now(),
162
+ raw: undefined,
163
+ bot: this,
164
+ platform,
165
+ selfId: this.selfId,
166
+ messageId,
167
+ messageType: 'private',
168
+ userId,
169
+ ...(context?.active.value && { eventId: context.eventId }),
170
+ message: [segment],
171
+ });
172
+ return sent;
173
+ }
174
+ async #setTyping(userId, active) {
175
+ this.#assertOnline();
176
+ const context = this.#context(userId);
177
+ const previous = this.#tickets.get(userId);
178
+ let ticket;
179
+ if (previous && previous.expiresAt > Date.now() && (!active || previous.context === context)) {
180
+ ticket = previous.ticket;
181
+ }
182
+ else {
183
+ const result = await this.#request('getconfig', typingSchema, { ilink_user_id: userId, context_token: context }, 10_000);
184
+ ticket = result.typing_ticket;
185
+ this.#tickets.delete(userId);
186
+ this.#tickets.set(userId, { ticket, context, expiresAt: Date.now() + 60_000 });
187
+ const first = this.#tickets.keys().next();
188
+ if (this.#tickets.size > 256 && !first.done)
189
+ this.#tickets.delete(first.value);
190
+ }
191
+ await this.#request('sendtyping', errorSchema, { ilink_user_id: userId, typing_ticket: ticket, status: active ? 1 : 2 }, 10_000);
192
+ }
193
+ #assertOnline() {
194
+ if (this.#status !== 'online')
195
+ throw new NotConnectedError('微信 ClawBot 未上线');
196
+ }
197
+ #context(userId) {
198
+ const token = this.#store.get(contextKey(userId));
199
+ if (!token)
200
+ throw new DeliveryError({ platform, selfId: this.selfId, type: 'private', id: userId }, {
201
+ code: 'CONVERSATION_UNAVAILABLE',
202
+ message: '请先让对方给这台微信 ClawBot 发送一条消息',
203
+ });
204
+ return token;
205
+ }
206
+ async getSelf() {
207
+ return { userId: this.selfId, nickname: this.selfId };
208
+ }
209
+ async sendGroup() {
210
+ return this.#unsupported('sendGroup');
211
+ }
212
+ async sendForward() {
213
+ return this.#unsupported('sendForward');
214
+ }
215
+ async getForward() {
216
+ return this.#unsupported('getForward');
217
+ }
218
+ async deleteMessage() {
219
+ return this.#unsupported('deleteMessage');
220
+ }
221
+ async getMessage() {
222
+ return this.#unsupported('getMessage');
223
+ }
224
+ async getGroupList() {
225
+ return this.#unsupported('getGroupList');
226
+ }
227
+ async getGroupMember() {
228
+ return this.#unsupported('getGroupMember');
229
+ }
230
+ async getGroupMembers() {
231
+ return this.#unsupported('getGroupMembers');
232
+ }
233
+ async muteMember() {
234
+ return this.#unsupported('muteMember');
235
+ }
236
+ async kickMember() {
237
+ return this.#unsupported('kickMember');
238
+ }
239
+ async setMemberCard() {
240
+ return this.#unsupported('setMemberCard');
241
+ }
242
+ async getFriendList() {
243
+ return this.#unsupported('getFriendList');
244
+ }
245
+ async call(action) {
246
+ return this.#unsupported(action);
247
+ }
248
+ #unsupported(action) {
249
+ throw new UnsupportedError(platform, action);
250
+ }
251
+ }
252
+ export function isWeixinClawBot(bot) {
253
+ return bot instanceof WeixinBot;
254
+ }
@@ -0,0 +1,2 @@
1
+ export { isWeixinClawBot, type WeixinBot } from './bot.ts';
2
+ export declare const weixinClawbot: import("../../core/adapter.ts").AdapterDefinition;
@@ -0,0 +1,19 @@
1
+ import { defineAdapter } from '../../core/adapter.js';
2
+ import { WeixinAdapter } from './adapter.js';
3
+ import { weixinCapabilities } from './bot.js';
4
+ import { accountSchema, platform } from './protocol.js';
5
+ import { weixinSetup } from './setup.js';
6
+ export { isWeixinClawBot } from './bot.js';
7
+ export const weixinClawbot = defineAdapter({
8
+ id: platform,
9
+ platform,
10
+ name: '微信 ClawBot',
11
+ version: '0.1.0',
12
+ description: '用微信扫码授权,通过 iLink 长轮询收发私聊消息。',
13
+ connectionTypes: ['long-polling'],
14
+ capabilities: weixinCapabilities,
15
+ configSchema: accountSchema,
16
+ accountId: (config) => config.selfId,
17
+ setup: weixinSetup,
18
+ create: (config, host) => new WeixinAdapter(config, host),
19
+ });
@@ -0,0 +1,57 @@
1
+ import type { z } from 'zod';
2
+ import { seg } from '../../core/message/index.ts';
3
+ import { type cdnSchema, type IlinkRequest } from './protocol.ts';
4
+ type CdnMedia = z.output<typeof cdnSchema>;
5
+ type MediaKind = 'image' | 'video' | 'file' | 'audio';
6
+ type MediaSegment = ReturnType<(typeof seg)[MediaKind]>;
7
+ type OutboundMedia = Exclude<MediaSegment, {
8
+ type: 'audio';
9
+ }>;
10
+ export declare class WeixinMedia {
11
+ #private;
12
+ constructor(shutdown: AbortSignal);
13
+ remember(kind: MediaKind, ref: CdnMedia, name?: string, imageKey?: string): MediaSegment | undefined;
14
+ download(handle: string, format: 'original' | 'wav', signal?: AbortSignal): Promise<Buffer>;
15
+ upload(userId: string, segment: OutboundMedia, request: IlinkRequest): Promise<{
16
+ item: {
17
+ type: number;
18
+ image_item: {
19
+ media: {
20
+ encrypt_query_param: string;
21
+ aes_key: string;
22
+ encrypt_type: number;
23
+ };
24
+ mid_size: number;
25
+ };
26
+ video_item?: undefined;
27
+ file_item?: undefined;
28
+ } | {
29
+ image_item?: undefined;
30
+ type: number;
31
+ video_item: {
32
+ media: {
33
+ encrypt_query_param: string;
34
+ aes_key: string;
35
+ encrypt_type: number;
36
+ };
37
+ video_size: number;
38
+ };
39
+ file_item?: undefined;
40
+ } | {
41
+ image_item?: undefined;
42
+ video_item?: undefined;
43
+ type: number;
44
+ file_item: {
45
+ media: {
46
+ encrypt_query_param: string;
47
+ aes_key: string;
48
+ encrypt_type: number;
49
+ };
50
+ file_name: string | undefined;
51
+ len: string;
52
+ };
53
+ };
54
+ segment: MediaSegment;
55
+ }>;
56
+ }
57
+ export {};