@zhin.js/adapter-napcat 1.0.0 → 1.1.0

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 (159) hide show
  1. package/CHANGELOG.md +674 -0
  2. package/README.md +60 -95
  3. package/adapters/napcat.js +47 -0
  4. package/adapters/napcat.ts +64 -0
  5. package/agent/PERMITS.md +19 -0
  6. package/{skills/napcat/SKILL.md → agent/skills/napcat.md} +6 -6
  7. package/agent/tools/ai_tts.ts +19 -0
  8. package/agent/tools/del_group_notice.ts +20 -0
  9. package/agent/tools/delete_essence_msg.ts +19 -0
  10. package/agent/tools/delete_friend.ts +18 -0
  11. package/agent/tools/download_file.ts +17 -0
  12. package/agent/tools/forward_single_msg.ts +28 -0
  13. package/agent/tools/get_ai_characters.ts +17 -0
  14. package/agent/tools/get_essence_list.ts +17 -0
  15. package/agent/tools/get_friend_msg_history.ts +18 -0
  16. package/agent/tools/get_group_file_url.ts +19 -0
  17. package/agent/tools/get_group_info_ex.ts +17 -0
  18. package/agent/tools/get_group_msg_history.ts +19 -0
  19. package/agent/tools/get_group_notice.ts +17 -0
  20. package/agent/tools/get_group_root_files.ts +17 -0
  21. package/agent/tools/get_group_shut_list.ts +17 -0
  22. package/agent/tools/get_mini_app_ark.ts +20 -0
  23. package/agent/tools/get_user_status.ts +16 -0
  24. package/agent/tools/group_sign.ts +18 -0
  25. package/agent/tools/mark_msg_as_read.ts +17 -0
  26. package/agent/tools/ocr_image.ts +16 -0
  27. package/agent/tools/send_forward_msg.ts +27 -0
  28. package/agent/tools/send_group_notice.ts +21 -0
  29. package/agent/tools/send_like.ts +18 -0
  30. package/agent/tools/send_poke.ts +18 -0
  31. package/agent/tools/set_avatar.ts +17 -0
  32. package/agent/tools/set_emoji_reaction.ts +18 -0
  33. package/agent/tools/set_essence_msg.ts +19 -0
  34. package/agent/tools/set_group_portrait.ts +20 -0
  35. package/agent/tools/set_online_status.ts +18 -0
  36. package/agent/tools/set_profile.ts +21 -0
  37. package/agent/tools/set_signature.ts +17 -0
  38. package/agent/tools/set_title.ts +21 -0
  39. package/agent/tools/translate.ts +16 -0
  40. package/agent/tools/upload_group_file.ts +21 -0
  41. package/commands/endpoint/add/[id].js +3 -0
  42. package/commands/endpoint/add/[id].ts +3 -0
  43. package/commands/endpoint/list.js +3 -0
  44. package/commands/endpoint/list.ts +3 -0
  45. package/commands/endpoint/remove/[id].js +3 -0
  46. package/commands/endpoint/remove/[id].ts +3 -0
  47. package/lib/client.d.ts +52 -0
  48. package/lib/client.js +62 -0
  49. package/lib/endpoint-management.d.ts +15 -0
  50. package/lib/endpoint-management.js +47 -0
  51. package/lib/http-endpoint.d.ts +27 -0
  52. package/lib/http-endpoint.js +177 -0
  53. package/lib/index.d.ts +11 -22
  54. package/lib/index.js +10 -58
  55. package/lib/napcat-endpoint-commands.d.ts +1 -0
  56. package/lib/napcat-endpoint-commands.js +28 -0
  57. package/lib/napcat-inbound.d.ts +12 -5
  58. package/lib/napcat-inbound.js +28 -13
  59. package/lib/napcat-runtime-state.d.ts +1 -0
  60. package/lib/napcat-runtime-state.js +6 -0
  61. package/lib/onebot-get-msg.d.ts +16 -3
  62. package/lib/onebot-get-msg.js +53 -1
  63. package/lib/protocol.d.ts +165 -0
  64. package/lib/protocol.js +305 -0
  65. package/lib/side-event-dispatch.d.ts +7 -0
  66. package/lib/side-event-dispatch.js +36 -0
  67. package/lib/webhook.d.ts +2 -0
  68. package/lib/webhook.js +14 -0
  69. package/lib/ws-endpoint.d.ts +27 -0
  70. package/lib/ws-endpoint.js +241 -0
  71. package/lib/ws-transport.d.ts +13 -0
  72. package/lib/ws-transport.js +75 -0
  73. package/lib/ws-types.d.ts +17 -0
  74. package/lib/ws-types.js +1 -0
  75. package/lib/wss-auth.d.ts +2 -0
  76. package/lib/wss-auth.js +16 -0
  77. package/lib/wss-endpoint.d.ts +26 -0
  78. package/lib/wss-endpoint.js +187 -0
  79. package/package.json +62 -30
  80. package/plugin.js +18 -0
  81. package/schema.json +110 -0
  82. package/src/client.ts +79 -0
  83. package/src/endpoint-management.ts +72 -0
  84. package/src/http-endpoint.ts +234 -0
  85. package/src/index.ts +63 -85
  86. package/src/napcat-endpoint-commands.ts +26 -0
  87. package/src/napcat-inbound.ts +34 -10
  88. package/src/napcat-runtime-state.ts +7 -0
  89. package/src/onebot-get-msg.ts +69 -5
  90. package/src/protocol.ts +468 -0
  91. package/src/side-event-dispatch.ts +48 -0
  92. package/src/webhook.ts +16 -0
  93. package/src/ws-endpoint.ts +301 -0
  94. package/src/ws-transport.ts +105 -0
  95. package/src/ws-types.ts +20 -0
  96. package/src/wss-auth.ts +17 -0
  97. package/src/wss-endpoint.ts +242 -0
  98. package/client/NapCatManagement.tsx +0 -113
  99. package/client/index.tsx +0 -11
  100. package/client/tsconfig.json +0 -7
  101. package/client/utils/api.ts +0 -30
  102. package/dist/index.js +0 -27
  103. package/lib/adapter.d.ts +0 -27
  104. package/lib/adapter.d.ts.map +0 -1
  105. package/lib/adapter.js +0 -93
  106. package/lib/adapter.js.map +0 -1
  107. package/lib/agent-prompt.d.ts +0 -3
  108. package/lib/agent-prompt.d.ts.map +0 -1
  109. package/lib/agent-prompt.js +0 -105
  110. package/lib/agent-prompt.js.map +0 -1
  111. package/lib/bot-base.d.ts +0 -143
  112. package/lib/bot-base.d.ts.map +0 -1
  113. package/lib/bot-base.js +0 -334
  114. package/lib/bot-base.js.map +0 -1
  115. package/lib/bot-http.d.ts +0 -18
  116. package/lib/bot-http.d.ts.map +0 -1
  117. package/lib/bot-http.js +0 -119
  118. package/lib/bot-http.js.map +0 -1
  119. package/lib/bot-ws-client.d.ts +0 -21
  120. package/lib/bot-ws-client.d.ts.map +0 -1
  121. package/lib/bot-ws-client.js +0 -165
  122. package/lib/bot-ws-client.js.map +0 -1
  123. package/lib/bot-ws-server.d.ts +0 -21
  124. package/lib/bot-ws-server.d.ts.map +0 -1
  125. package/lib/bot-ws-server.js +0 -150
  126. package/lib/bot-ws-server.js.map +0 -1
  127. package/lib/index.d.ts.map +0 -1
  128. package/lib/index.js.map +0 -1
  129. package/lib/napcat-inbound.d.ts.map +0 -1
  130. package/lib/napcat-inbound.js.map +0 -1
  131. package/lib/onebot-get-msg.d.ts.map +0 -1
  132. package/lib/onebot-get-msg.js.map +0 -1
  133. package/lib/routes.d.ts +0 -4
  134. package/lib/routes.d.ts.map +0 -1
  135. package/lib/routes.js +0 -61
  136. package/lib/routes.js.map +0 -1
  137. package/lib/tools.d.ts +0 -8
  138. package/lib/tools.d.ts.map +0 -1
  139. package/lib/tools.js +0 -605
  140. package/lib/tools.js.map +0 -1
  141. package/lib/types.d.ts +0 -293
  142. package/lib/types.d.ts.map +0 -1
  143. package/lib/types.js +0 -6
  144. package/lib/types.js.map +0 -1
  145. package/lib/typing-indicator.d.ts +0 -45
  146. package/lib/typing-indicator.d.ts.map +0 -1
  147. package/lib/typing-indicator.js +0 -132
  148. package/lib/typing-indicator.js.map +0 -1
  149. package/plugin.yml +0 -3
  150. package/src/adapter.ts +0 -99
  151. package/src/agent-prompt.ts +0 -114
  152. package/src/bot-base.ts +0 -376
  153. package/src/bot-http.ts +0 -109
  154. package/src/bot-ws-client.ts +0 -164
  155. package/src/bot-ws-server.ts +0 -150
  156. package/src/routes.ts +0 -61
  157. package/src/tools.ts +0 -632
  158. package/src/types.ts +0 -279
  159. package/src/typing-indicator.ts +0 -184
@@ -0,0 +1,301 @@
1
+ import { Endpoint } from 'zhin.js/adapter';
2
+ /**
3
+ * NapCat WS client endpoint — outbound connect to NapCat.
4
+ */
5
+ import WebSocket from 'ws';
6
+ import {
7
+ createRecallEndpointControl,
8
+ createEndpointLifecycle,
9
+ type EndpointConnectHandle,
10
+ type EndpointControl,
11
+ type EndpointLifecycle,
12
+ type EndpointManagement,
13
+ type EndpointSendRequest,
14
+ } from 'zhin.js/adapter';
15
+ import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
16
+ import type { CapabilityId } from 'zhin.js';
17
+ import { createNapCatEndpointManagement } from './endpoint-management.js';
18
+ import {
19
+ InboundMessageDeduper,
20
+ isNapCatBotMentioned,
21
+ isSelfMessage,
22
+ normalizeMessage,
23
+ } from './napcat-inbound.js';
24
+ import {
25
+ buildSendAction,
26
+ buildWsConnectOptions,
27
+ formatInboundContent,
28
+ formatOutboundSegments,
29
+ isMessageEvent,
30
+ napcatInboundConversation,
31
+ napcatOutboundTarget,
32
+ senderNickname,
33
+ senderUserId,
34
+ type NapCatEvent,
35
+ type NapCatWsConfig,
36
+ } from './protocol.js';
37
+ import { receiveNapCatSideEvent } from './side-event-dispatch.js';
38
+ import {
39
+ callNapCatWsAction,
40
+ handleNapCatWsMessage,
41
+ rejectAllPending,
42
+ } from './ws-transport.js';
43
+ import {
44
+ type NapCatPendingAction,
45
+ type NapCatWsCreateOptions,
46
+ type NapCatWsSocket,
47
+ } from './ws-types.js';
48
+ import { createNapCatContentPort } from './onebot-get-msg.js';
49
+ import { NapcatClient } from './client.js';
50
+
51
+ export interface NapCatWsEndpointOptions {
52
+ readonly id: CapabilityId;
53
+ readonly config: NapCatWsConfig;
54
+ readonly createWebSocket?: (
55
+ url: string,
56
+ options: NapCatWsCreateOptions,
57
+ ) => NapCatWsSocket;
58
+ }
59
+
60
+ export class NapCatWsEndpoint extends Endpoint<NapcatClient> {
61
+ readonly client = new NapcatClient((action, params) => this.#callApi(action, params));
62
+ readonly #logger!: ReturnType<typeof getAdapterLogger>;
63
+
64
+ readonly #options: NapCatWsEndpointOptions;
65
+ readonly #inboundDeduper = new InboundMessageDeduper();
66
+ readonly management: EndpointManagement = createNapCatEndpointManagement(this.client);
67
+ readonly control: EndpointControl = createRecallEndpointControl((id) => this.recallMessage(id));
68
+ readonly content = createNapCatContentPort((action, params) => this.client.callApi(action, params));
69
+ readonly #lifecycle: EndpointLifecycle;
70
+ #ws?: NapCatWsSocket;
71
+ #requestId = { value: 0 };
72
+ #pending = new Map<string, NapCatPendingAction>();
73
+ #open = false;
74
+
75
+ constructor(options: NapCatWsEndpointOptions) {
76
+ super();
77
+ this.#logger = getAdapterLogger('napcat', options.config.id);
78
+ this.#options = options;
79
+ this.#lifecycle = createEndpointLifecycle({
80
+ name: options.config.id,
81
+ // reconnect_interval 旧语义为固定间隔:multiplier 1 + 无 jitter + 不封顶
82
+ reconnect: {
83
+ initialIntervalMs: options.config.reconnect_interval,
84
+ multiplier: 1,
85
+ maxIntervalMs: Number.MAX_SAFE_INTEGER,
86
+ jitterMs: 0,
87
+ },
88
+ });
89
+ }
90
+
91
+ async start(): Promise<void> {
92
+ if (this.#lifecycle.started) return;
93
+ await this.#lifecycle.start((handle) => this.#connect(handle));
94
+ }
95
+
96
+ open(): void {
97
+ this.#open = true;
98
+ }
99
+
100
+ close(): void {
101
+ this.#open = false;
102
+ }
103
+
104
+ async stop(): Promise<void> {
105
+ this.#open = false;
106
+ await this.#lifecycle.stop();
107
+ rejectAllPending(this.#pending);
108
+ this.#inboundDeduper.clear();
109
+ if (this.#ws) {
110
+ try {
111
+ this.#ws.close();
112
+ } catch {
113
+ /* ignore */
114
+ }
115
+ this.#ws = undefined;
116
+ }
117
+ }
118
+
119
+ async send({ conversation, payload }: EndpointSendRequest): Promise<string> {
120
+ const message = formatOutboundSegments(payload);
121
+ const { action, params } = buildSendAction(napcatOutboundTarget(conversation), message);
122
+ const data = await this.client.callApi(action, params) as { message_id?: number | string } | undefined;
123
+ const messageId = data?.message_id != null ? String(data.message_id) : '';
124
+ this.#logger.debug(formatCompact({
125
+ op: 'napcat_send',
126
+ endpoint: this.#options.config.id,
127
+ target: `${conversation.kind}:${conversation.id}`,
128
+ messageId,
129
+ }));
130
+ return messageId;
131
+ }
132
+
133
+ async recallMessage(messageId: string): Promise<void> {
134
+ if (!messageId) return;
135
+ await this.client.callApi('delete_msg', { message_id: Number(messageId) });
136
+ }
137
+
138
+ #callApi(action: string, params: Record<string, unknown> = {}): Promise<unknown> {
139
+ return callNapCatWsAction(this.#ws, this.#pending, this.#requestId, action, params);
140
+ }
141
+
142
+ /** Test / internal: admit a parsed event when the endpoint is open. */
143
+ admit(ev: NapCatEvent): void {
144
+ if (!this.#open) return;
145
+ void this.emitPlatform(napCatPlatformEventName(ev), ev).catch((error) => {
146
+ this.#logger.warn(formatCompact({
147
+ op: 'napcat_platform_event_failed',
148
+ error: error instanceof Error ? error.message : String(error),
149
+ }));
150
+ });
151
+ if (!isMessageEvent(ev)) {
152
+ receiveNapCatSideEvent(
153
+ (name, payload) => this.emit(name, payload),
154
+ this.#options.config.id,
155
+ this.client,
156
+ ev,
157
+ this.#logger,
158
+ );
159
+ return;
160
+ }
161
+ if (isSelfMessage(ev)) return;
162
+ const msgId = String(ev.message_id);
163
+ if (!this.#inboundDeduper.shouldProcess(msgId)) return;
164
+ if (Array.isArray(ev.message) || typeof ev.message === 'string') {
165
+ ev = { ...ev, message: normalizeMessage(ev.message) };
166
+ }
167
+ const conversation = napcatInboundConversation(String(this.#options.id), ev);
168
+ const content = formatInboundContent(ev);
169
+ const nickname = senderNickname(ev);
170
+ const mentioned = isNapCatBotMentioned(ev);
171
+ void this.emit('message.receive', {
172
+ conversation,
173
+ message: { conversation, id: msgId },
174
+ content,
175
+ sender: {
176
+ id: senderUserId(ev),
177
+ name: nickname,
178
+ ...(ev.sender?.role ? { roles: [ev.sender.role] } : {}),
179
+ },
180
+ endpointId: this.#options.config.id,
181
+ ...(mentioned ? { mentioned: true } : {}),
182
+ metadata: Object.freeze({
183
+ message_type: ev.message_type,
184
+ user_id: ev.user_id != null ? String(ev.user_id) : undefined,
185
+ group_id: ev.group_id != null ? String(ev.group_id) : undefined,
186
+ time: ev.time,
187
+ self_id: ev.self_id != null ? String(ev.self_id) : undefined,
188
+ role: ev.sender?.role,
189
+ ...(nickname ? { nickname } : {}),
190
+ }),
191
+ }).catch((err) => {
192
+ this.#logger.warn(formatCompact({
193
+ op: 'napcat_gateway_receive_failed',
194
+ target: `${conversation.kind}:${conversation.id}`,
195
+ error: err instanceof Error ? err.message : String(err),
196
+ }));
197
+ });
198
+ }
199
+
200
+ async #connect(handle: EndpointConnectHandle): Promise<void> {
201
+ const { url, headers, safeUrl } = buildWsConnectOptions(this.#options.config);
202
+ const create = this.#options.createWebSocket
203
+ ?? ((connectUrl: string, options: NapCatWsCreateOptions) =>
204
+ new WebSocket(connectUrl, { headers: options.headers }) as unknown as NapCatWsSocket);
205
+
206
+ await new Promise<void>((resolve, reject) => {
207
+ let settled = false;
208
+ const ws = create(url, { headers });
209
+ this.#ws = ws;
210
+ handle.onForceClose(() => {
211
+ try {
212
+ ws.close();
213
+ } catch {
214
+ /* ignore */
215
+ }
216
+ });
217
+
218
+ ws.on('open', () => {
219
+ if (settled) return;
220
+ settled = true;
221
+ if (!this.#options.config.access_token) {
222
+ this.#logger.warn(formatCompact({
223
+ endpoint: this.#options.config.id,
224
+ ok: false,
225
+ error: 'missing access_token',
226
+ }));
227
+ }
228
+ this.#logger.debug(formatCompact({
229
+ endpoint: this.#options.config.id,
230
+ mode: 'ws',
231
+ url: safeUrl,
232
+ }));
233
+ // stop-during-connect 竞态:已停止则不再武装心跳(基座 stop 已清理定时器)
234
+ if (this.#lifecycle.started) {
235
+ this.#lifecycle.startHeartbeat(() => {
236
+ try {
237
+ ws.ping?.();
238
+ } catch {
239
+ /* ignore */
240
+ }
241
+ }, this.#options.config.heartbeat_interval);
242
+ }
243
+ resolve();
244
+ });
245
+
246
+ ws.on('message', (data) => {
247
+ handleNapCatWsMessage(data, {
248
+ endpointId: this.#options.config.id,
249
+ pending: this.#pending,
250
+ admit: (event) => this.admit(event),
251
+ });
252
+ });
253
+
254
+ ws.on('close', (code, reason) => {
255
+ const reasonStr = typeof reason === 'string'
256
+ ? reason
257
+ : Buffer.isBuffer(reason)
258
+ ? reason.toString()
259
+ : String(reason ?? '');
260
+ const codeNum = typeof code === 'number' ? code : Number(code ?? 0);
261
+ const codeHint = codeNum === 1005
262
+ ? ' [no status]'
263
+ : codeNum === 1006
264
+ ? ' [abnormal]'
265
+ : '';
266
+ this.#logger.warn(formatCompact({
267
+ op: 'disconnect',
268
+ code: codeNum,
269
+ error: `${reasonStr || 'closed'}${codeHint}`,
270
+ reconnect_ms: this.#options.config.reconnect_interval,
271
+ }));
272
+ // 基座语义:仅曾 open 的连接才武装重连;初始连接失败由 start() 的 catch 复位
273
+ handle.notifyClosed(new Error(`NapCat WS closed: ${codeNum} ${reasonStr}`));
274
+ if (!settled) {
275
+ settled = true;
276
+ reject(new Error(`NapCat WS closed: ${codeNum} ${reasonStr}`));
277
+ }
278
+ });
279
+
280
+ ws.on('error', (err) => {
281
+ const error = err instanceof Error ? err : new Error(String(err));
282
+ this.#logger.warn(formatCompact({
283
+ op: 'ws_error',
284
+ endpoint: this.#options.config.id,
285
+ ok: false,
286
+ error: error.message,
287
+ }));
288
+ if (!settled) {
289
+ settled = true;
290
+ reject(error);
291
+ }
292
+ });
293
+ });
294
+ }
295
+ }
296
+
297
+ function napCatPlatformEventName(ev: NapCatEvent): string {
298
+ return [ev.post_type, ev.message_type ?? ev.notice_type ?? ev.request_type, ev.sub_type]
299
+ .filter(Boolean)
300
+ .join('.');
301
+ }
@@ -0,0 +1,105 @@
1
+ import { clearInterval, clearTimeout, setInterval, setTimeout } from 'node:timers';
2
+ import { formatCompact, getLogger } from '@zhin.js/logger';
3
+ import {
4
+ type NapCatActionRequest,
5
+ type NapCatActionResponse,
6
+ type NapCatEvent,
7
+ } from './protocol.js';
8
+ import {
9
+ WS_OPEN,
10
+ type NapCatPendingAction,
11
+ type NapCatWsSocket,
12
+ } from './ws-types.js';
13
+
14
+ const logger = getLogger('napcat');
15
+
16
+ export function decodeWsPayload(data: unknown): string {
17
+ if (typeof data === 'string') return data;
18
+ if (Buffer.isBuffer(data)) return data.toString();
19
+ if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
20
+ return String(data ?? '');
21
+ }
22
+
23
+ export function handleNapCatWsMessage(
24
+ data: unknown,
25
+ options: {
26
+ readonly endpointId: string;
27
+ readonly pending: Map<string, NapCatPendingAction>;
28
+ readonly admit: (ev: NapCatEvent) => void;
29
+ },
30
+ ): void {
31
+ try {
32
+ const raw = decodeWsPayload(data);
33
+ const msg = JSON.parse(raw) as NapCatEvent | NapCatActionResponse;
34
+ if ('echo' in msg && typeof (msg as NapCatActionResponse).echo === 'string') {
35
+ const resp = msg as NapCatActionResponse;
36
+ const pending = options.pending.get(resp.echo!);
37
+ if (pending) {
38
+ options.pending.delete(resp.echo!);
39
+ clearTimeout(pending.timeout);
40
+ if (resp.status === 'ok') pending.resolve(resp.data);
41
+ else {
42
+ pending.reject(new Error(
43
+ `API error [${resp.retcode}]: ${resp.message || resp.wording || 'unknown'}`,
44
+ ));
45
+ }
46
+ }
47
+ return;
48
+ }
49
+ options.admit(msg as NapCatEvent);
50
+ } catch (error) {
51
+ logger.warn(formatCompact({
52
+ op: 'napcat_parse_failed',
53
+ endpoint: options.endpointId,
54
+ error: error instanceof Error ? error.message : String(error),
55
+ }));
56
+ }
57
+ }
58
+
59
+ export function callNapCatWsAction(
60
+ ws: NapCatWsSocket | undefined,
61
+ pending: Map<string, NapCatPendingAction>,
62
+ requestId: { value: number },
63
+ action: string,
64
+ params: Record<string, unknown>,
65
+ ): Promise<unknown> {
66
+ if (!ws || ws.readyState !== WS_OPEN) {
67
+ return Promise.reject(new Error('WebSocket is not connected'));
68
+ }
69
+ const echo = `req_${++requestId.value}`;
70
+ const req: NapCatActionRequest = { action, params, echo };
71
+ return new Promise((resolve, reject) => {
72
+ const timeout = setTimeout(() => {
73
+ pending.delete(echo);
74
+ reject(new Error(`API call timeout: ${action}`));
75
+ }, 30_000);
76
+ pending.set(echo, { resolve, reject, timeout });
77
+ ws.send(JSON.stringify(req));
78
+ });
79
+ }
80
+
81
+ export function startNapCatHeartbeat(
82
+ ws: NapCatWsSocket | undefined,
83
+ intervalMs: number,
84
+ existingTimer?: NodeJS.Timeout,
85
+ ): NodeJS.Timeout {
86
+ if (existingTimer) clearInterval(existingTimer);
87
+ return setInterval(() => {
88
+ try {
89
+ ws?.ping?.();
90
+ } catch {
91
+ /* ignore */
92
+ }
93
+ }, intervalMs);
94
+ }
95
+
96
+ export function rejectAllPending(
97
+ pending: Map<string, NapCatPendingAction>,
98
+ message = 'Connection closed',
99
+ ): void {
100
+ for (const [, entry] of pending) {
101
+ clearTimeout(entry.timeout);
102
+ entry.reject(new Error(message));
103
+ }
104
+ pending.clear();
105
+ }
@@ -0,0 +1,20 @@
1
+ /** Minimal WS surface used by the endpoint (real `ws` or test mock). */
2
+ export interface NapCatWsSocket {
3
+ readonly readyState: number;
4
+ send(data: string): void;
5
+ close(code?: number, reason?: string): void;
6
+ ping?(): void;
7
+ on(event: 'open' | 'message' | 'close' | 'error', listener: (...args: unknown[]) => void): void;
8
+ }
9
+
10
+ export interface NapCatWsCreateOptions {
11
+ readonly headers?: Record<string, string>;
12
+ }
13
+
14
+ export const WS_OPEN = 1;
15
+
16
+ export interface NapCatPendingAction {
17
+ resolve: (value: unknown) => void;
18
+ reject: (err: Error) => void;
19
+ timeout: NodeJS.Timeout;
20
+ }
@@ -0,0 +1,17 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+
3
+ export function verifyNapCatAccessToken(
4
+ accessToken: string | undefined,
5
+ request: IncomingMessage,
6
+ ): boolean {
7
+ if (!accessToken) return true;
8
+ const auth = request.headers.authorization ?? '';
9
+ if (auth === `Bearer ${accessToken}`) return true;
10
+ try {
11
+ const url = new URL(request.url ?? '/', 'http://localhost');
12
+ if (url.searchParams.get('access_token') === accessToken) return true;
13
+ } catch {
14
+ /* ignore */
15
+ }
16
+ return false;
17
+ }
@@ -0,0 +1,242 @@
1
+ import { Endpoint } from 'zhin.js/adapter';
2
+ /**
3
+ * NapCat reverse WSS endpoint — accepts inbound WebSocket from NapCat.
4
+ */
5
+ import { clearInterval } from 'node:timers';
6
+ import {
7
+ createRecallEndpointControl,
8
+ type EndpointControl,
9
+ type EndpointManagement,
10
+ type EndpointSendRequest,
11
+ } from 'zhin.js/adapter';
12
+ import type { HttpHost, WsConnection } from '@zhin.js/host-http';
13
+ import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
14
+ import type { CapabilityId } from 'zhin.js';
15
+ import { createNapCatEndpointManagement } from './endpoint-management.js';
16
+ import {
17
+ InboundMessageDeduper,
18
+ isNapCatBotMentioned,
19
+ isSelfMessage,
20
+ normalizeMessage,
21
+ } from './napcat-inbound.js';
22
+ import {
23
+ buildSendAction,
24
+ formatInboundContent,
25
+ formatOutboundSegments,
26
+ isMessageEvent,
27
+ napcatInboundConversation,
28
+ napcatOutboundTarget,
29
+ senderNickname,
30
+ senderUserId,
31
+ type NapCatEvent,
32
+ type NapCatWssConfig,
33
+ } from './protocol.js';
34
+ import { receiveNapCatSideEvent } from './side-event-dispatch.js';
35
+ import { createNapCatContentPort } from './onebot-get-msg.js';
36
+ import { NapcatClient } from './client.js';
37
+ import {
38
+ callNapCatWsAction,
39
+ handleNapCatWsMessage,
40
+ rejectAllPending,
41
+ startNapCatHeartbeat,
42
+ } from './ws-transport.js';
43
+ import { NapCatWsEndpoint } from './ws-endpoint.js';
44
+ import {
45
+ type NapCatPendingAction,
46
+ type NapCatWsSocket,
47
+ } from './ws-types.js';
48
+ import { verifyNapCatAccessToken } from './wss-auth.js';
49
+
50
+ export interface NapCatWssEndpointOptions {
51
+ readonly id: CapabilityId;
52
+ readonly http: HttpHost;
53
+ readonly config: NapCatWssConfig;
54
+ }
55
+
56
+ export class NapCatWssEndpoint extends Endpoint<NapcatClient> {
57
+ readonly client = new NapcatClient((action, params) => this.#callApi(action, params));
58
+ readonly #logger!: ReturnType<typeof getAdapterLogger>;
59
+
60
+ readonly #options: NapCatWssEndpointOptions;
61
+ readonly #inboundDeduper = new InboundMessageDeduper();
62
+ readonly management: EndpointManagement = createNapCatEndpointManagement(this.client);
63
+ readonly control: EndpointControl = createRecallEndpointControl((id) => this.recallMessage(id));
64
+ readonly content = createNapCatContentPort((action, params) => this.client.callApi(action, params));
65
+ #ws?: NapCatWsSocket;
66
+ #wsRelease?: () => void;
67
+ #heartbeatTimer?: NodeJS.Timeout;
68
+ #requestId = { value: 0 };
69
+ #pending = new Map<string, NapCatPendingAction>();
70
+ #open = false;
71
+ #started = false;
72
+
73
+ constructor(options: NapCatWssEndpointOptions) {
74
+ super();
75
+ this.#logger = getAdapterLogger('napcat', options.config.id);
76
+ this.#options = options;
77
+ }
78
+
79
+ async start(): Promise<void> {
80
+ if (this.#started) return;
81
+ this.#started = true;
82
+ const handle = this.#options.http.ws(this.#options.config.path);
83
+ this.#wsRelease = handle.onConnection((connection) => {
84
+ this.#acceptConnection(connection);
85
+ });
86
+ this.#logger.info(formatCompact({
87
+ op: 'listen',
88
+ endpoint: this.#options.config.id,
89
+ mode: 'wss',
90
+ path: this.#options.config.path,
91
+ }));
92
+ }
93
+
94
+ open(): void {
95
+ this.#open = true;
96
+ }
97
+
98
+ close(): void {
99
+ this.#open = false;
100
+ }
101
+
102
+ async stop(): Promise<void> {
103
+ this.#open = false;
104
+ this.#wsRelease?.();
105
+ this.#wsRelease = undefined;
106
+ if (this.#heartbeatTimer) {
107
+ clearInterval(this.#heartbeatTimer);
108
+ this.#heartbeatTimer = undefined;
109
+ }
110
+ rejectAllPending(this.#pending);
111
+ this.#inboundDeduper.clear();
112
+ if (this.#ws) {
113
+ try {
114
+ this.#ws.close();
115
+ } catch {
116
+ /* ignore */
117
+ }
118
+ this.#ws = undefined;
119
+ }
120
+ this.#started = false;
121
+ }
122
+
123
+ async send({ conversation, payload }: EndpointSendRequest): Promise<string> {
124
+ const message = formatOutboundSegments(payload);
125
+ const { action, params } = buildSendAction(napcatOutboundTarget(conversation), message);
126
+ const data = await this.client.callApi(action, params) as { message_id?: number | string } | undefined;
127
+ return data?.message_id != null ? String(data.message_id) : '';
128
+ }
129
+
130
+ async recallMessage(messageId: string): Promise<void> {
131
+ if (!messageId) return;
132
+ await this.client.callApi('delete_msg', { message_id: Number(messageId) });
133
+ }
134
+
135
+ #callApi(action: string, params: Record<string, unknown> = {}): Promise<unknown> {
136
+ return callNapCatWsAction(this.#ws, this.#pending, this.#requestId, action, params);
137
+ }
138
+
139
+ admit(ev: NapCatEvent): void {
140
+ if (!this.#open) return;
141
+ void this.emitPlatform(napCatPlatformEventName(ev), ev).catch((error) => {
142
+ this.#logger.warn(formatCompact({
143
+ op: 'napcat_platform_event_failed',
144
+ error: error instanceof Error ? error.message : String(error),
145
+ }));
146
+ });
147
+ if (!isMessageEvent(ev)) {
148
+ receiveNapCatSideEvent(
149
+ (name, payload) => this.emit(name, payload),
150
+ this.#options.config.id,
151
+ this.client,
152
+ ev,
153
+ this.#logger,
154
+ );
155
+ return;
156
+ }
157
+ if (isSelfMessage(ev)) return;
158
+ const msgId = String(ev.message_id);
159
+ if (!this.#inboundDeduper.shouldProcess(msgId)) return;
160
+ if (Array.isArray(ev.message) || typeof ev.message === 'string') {
161
+ ev = { ...ev, message: normalizeMessage(ev.message) };
162
+ }
163
+ const conversation = napcatInboundConversation(String(this.#options.id), ev);
164
+ const nickname = senderNickname(ev);
165
+ const mentioned = isNapCatBotMentioned(ev);
166
+ void this.emit('message.receive', {
167
+ conversation,
168
+ message: { conversation, id: msgId },
169
+ content: formatInboundContent(ev),
170
+ sender: {
171
+ id: senderUserId(ev),
172
+ name: nickname,
173
+ ...(ev.sender?.role ? { roles: [ev.sender.role] } : {}),
174
+ },
175
+ endpointId: this.#options.config.id,
176
+ ...(mentioned ? { mentioned: true } : {}),
177
+ metadata: Object.freeze({
178
+ message_type: ev.message_type,
179
+ user_id: ev.user_id != null ? String(ev.user_id) : undefined,
180
+ group_id: ev.group_id != null ? String(ev.group_id) : undefined,
181
+ time: ev.time,
182
+ self_id: ev.self_id != null ? String(ev.self_id) : undefined,
183
+ role: ev.sender?.role,
184
+ ...(nickname ? { nickname } : {}),
185
+ }),
186
+ }).catch((err) => {
187
+ this.#logger.warn(formatCompact({
188
+ op: 'napcat_gateway_receive_failed',
189
+ target: `${conversation.kind}:${conversation.id}`,
190
+ error: err instanceof Error ? err.message : String(err),
191
+ }));
192
+ });
193
+ }
194
+
195
+ #acceptConnection(connection: WsConnection): void {
196
+ if (!verifyNapCatAccessToken(this.#options.config.access_token, connection.request)) {
197
+ connection.socket.close(4003, 'Unauthorized');
198
+ return;
199
+ }
200
+ const socket = connection.socket as unknown as NapCatWsSocket;
201
+ if (this.#ws) {
202
+ try {
203
+ this.#ws.close();
204
+ } catch {
205
+ /* ignore */
206
+ }
207
+ }
208
+ this.#ws = socket;
209
+ this.#heartbeatTimer = startNapCatHeartbeat(
210
+ this.#ws,
211
+ this.#options.config.heartbeat_interval,
212
+ this.#heartbeatTimer,
213
+ );
214
+ socket.on('message', (data) => {
215
+ handleNapCatWsMessage(data, {
216
+ endpointId: this.#options.config.id,
217
+ pending: this.#pending,
218
+ admit: (event) => this.admit(event),
219
+ });
220
+ });
221
+ socket.on('close', () => {
222
+ if (this.#ws === socket) {
223
+ this.#ws = undefined;
224
+ if (this.#heartbeatTimer) {
225
+ clearInterval(this.#heartbeatTimer);
226
+ this.#heartbeatTimer = undefined;
227
+ }
228
+ }
229
+ });
230
+ this.#logger.debug(formatCompact({
231
+ endpoint: this.#options.config.id,
232
+ mode: 'wss',
233
+ peer: connection.request.socket.remoteAddress,
234
+ }));
235
+ }
236
+ }
237
+
238
+ function napCatPlatformEventName(ev: NapCatEvent): string {
239
+ return [ev.post_type, ev.message_type ?? ev.notice_type ?? ev.request_type, ev.sub_type]
240
+ .filter(Boolean)
241
+ .join('.');
242
+ }