@zhin.js/adapter-napcat 1.0.1 → 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 +661 -0
  2. package/README.md +60 -95
  3. package/adapters/napcat.js +47 -0
  4. package/adapters/napcat.ts +64 -0
  5. package/{skills/napcat → agent}/PERMITS.md +3 -3
  6. package/{skills/napcat/SKILL.md → agent/skills/napcat.md} +2 -2
  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 -59
  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 -32
  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 -87
  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 -28
  104. package/lib/adapter.d.ts.map +0 -1
  105. package/lib/adapter.js +0 -94
  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/endpoint-base.d.ts +0 -143
  112. package/lib/endpoint-base.d.ts.map +0 -1
  113. package/lib/endpoint-base.js +0 -334
  114. package/lib/endpoint-base.js.map +0 -1
  115. package/lib/endpoint-http.d.ts +0 -18
  116. package/lib/endpoint-http.d.ts.map +0 -1
  117. package/lib/endpoint-http.js +0 -119
  118. package/lib/endpoint-http.js.map +0 -1
  119. package/lib/endpoint-ws-client.d.ts +0 -21
  120. package/lib/endpoint-ws-client.d.ts.map +0 -1
  121. package/lib/endpoint-ws-client.js +0 -165
  122. package/lib/endpoint-ws-client.js.map +0 -1
  123. package/lib/endpoint-ws-server.d.ts +0 -21
  124. package/lib/endpoint-ws-server.d.ts.map +0 -1
  125. package/lib/endpoint-ws-server.js +0 -150
  126. package/lib/endpoint-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 -101
  151. package/src/agent-prompt.ts +0 -114
  152. package/src/endpoint-base.ts +0 -376
  153. package/src/endpoint-http.ts +0 -109
  154. package/src/endpoint-ws-client.ts +0 -164
  155. package/src/endpoint-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
package/src/client.ts ADDED
@@ -0,0 +1,79 @@
1
+ import { defineEndpointClient } from 'zhin.js/adapter';
2
+ import type { NapCatEvent } from './protocol.js';
3
+
4
+ export type NapcatApiCall = (
5
+ action: string,
6
+ params?: Record<string, unknown>,
7
+ ) => Promise<unknown>;
8
+
9
+ /** Transport-independent NapCat protocol Client produced by every Endpoint mode. */
10
+ export class NapcatClient {
11
+ constructor(readonly callApi: NapcatApiCall) {}
12
+
13
+ async setTitle(groupId: number, userId: number, title: string, duration = -1): Promise<boolean> {
14
+ await this.callApi('set_group_special_title', {
15
+ group_id: groupId,
16
+ user_id: userId,
17
+ special_title: title,
18
+ duration,
19
+ });
20
+ return true;
21
+ }
22
+
23
+ sendLike(userId: number, times = 1) { return this.callApi('send_like', { user_id: userId, times }); }
24
+ deleteFriend(userId: number) { return this.callApi('delete_friend', { user_id: userId }); }
25
+ markMsgAsRead(messageId: number) { return this.callApi('mark_msg_as_read', { message_id: messageId }); }
26
+ ocrImage(image: string) { return this.callApi('ocr_image', { image }); }
27
+ setQQProfile(nickname: string, company?: string, email?: string, college?: string, personalNote?: string) {
28
+ return this.callApi('set_qq_profile', { nickname, company, email, college, personal_note: personalNote });
29
+ }
30
+ setGroupPortrait(groupId: number, file: string) { return this.callApi('set_group_portrait', { group_id: groupId, file }); }
31
+ setEssenceMsg(messageId: number) { return this.callApi('set_essence_msg', { message_id: messageId }); }
32
+ deleteEssenceMsg(messageId: number) { return this.callApi('delete_essence_msg', { message_id: messageId }); }
33
+ getEssenceMsgList(groupId: number) { return this.callApi('get_essence_msg_list', { group_id: groupId }); }
34
+ sendGroupSign(groupId: number) { return this.callApi('send_group_sign', { group_id: groupId }); }
35
+ sendGroupNotice(groupId: number, content: string, image?: string) { return this.callApi('_send_group_notice', { group_id: groupId, content, image }); }
36
+ getGroupNotice(groupId: number) { return this.callApi('_get_group_notice', { group_id: groupId }); }
37
+ deleteGroupNotice(groupId: number, noticeId: string) { return this.callApi('_del_group_notice', { group_id: groupId, notice_id: noticeId }); }
38
+ uploadGroupFile(groupId: number, file: string, name: string, folder?: string) { return this.callApi('upload_group_file', { group_id: groupId, file, name, folder }); }
39
+ getGroupRootFiles(groupId: number) { return this.callApi('get_group_root_files', { group_id: groupId }); }
40
+ getGroupFileUrl(groupId: number, fileId: string, busid: number) { return this.callApi('get_group_file_url', { group_id: groupId, file_id: fileId, busid }); }
41
+ downloadFile(url: string, threadCount = 1, headers?: string[]) { return this.callApi('download_file', { url, thread_count: threadCount, headers }); }
42
+ setOnlineStatus(status: number, extStatus: number) { return this.callApi('set_online_status', { status, ext_status: extStatus }); }
43
+ setQQAvatar(file: string) { return this.callApi('set_qq_avatar', { file }); }
44
+ forwardFriendSingleMsg(userId: number, messageId: number) { return this.callApi('forward_friend_single_msg', { user_id: userId, message_id: messageId }); }
45
+ forwardGroupSingleMsg(groupId: number, messageId: number) { return this.callApi('forward_group_single_msg', { group_id: groupId, message_id: messageId }); }
46
+ translateEn2Zh(sourceText: string) { return this.callApi('translate_en2zh', { source_text: sourceText }); }
47
+ setMsgEmojiLike(messageId: number, emojiId: string) { return this.callApi('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId }); }
48
+ sendForwardMsg(messageType: 'private' | 'group', id: number, messages: unknown[]) {
49
+ return this.callApi('send_forward_msg', {
50
+ message_type: messageType,
51
+ [messageType === 'group' ? 'group_id' : 'user_id']: id,
52
+ messages,
53
+ });
54
+ }
55
+ getFriendMsgHistory(userId: number, messageSeq?: number, count?: number) { return this.callApi('get_friend_msg_history', { user_id: userId, message_seq: messageSeq, count }); }
56
+ getGroupMsgHistory(groupId: number, messageSeq?: number, count?: number) { return this.callApi('get_group_msg_history', { group_id: groupId, message_seq: messageSeq, count }); }
57
+ setSelfLongnick(longnick: string) { return this.callApi('set_self_longnick', { longNick: longnick }); }
58
+ getGroupInfoEx(groupId: number) { return this.callApi('get_group_info_ex', { group_id: groupId }); }
59
+ sendPoke(userId: number, groupId?: number) { return this.callApi('send_poke', { user_id: userId, group_id: groupId }); }
60
+ ncGetUserStatus(userId: number) { return this.callApi('nc_get_user_status', { user_id: userId }); }
61
+ getGroupShutList(groupId: number) { return this.callApi('get_group_shut_list', { group_id: groupId }); }
62
+ getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) { return this.callApi('get_mini_app_ark', { type, title, desc, picUrl, jumpUrl }); }
63
+ getAiCharacters(groupId: number) { return this.callApi('get_ai_characters', { group_id: groupId }); }
64
+ sendGroupAiRecord(groupId: number, characterId: string, text: string) {
65
+ return this.callApi('send_group_ai_record', { group_id: groupId, character: characterId, text });
66
+ }
67
+ }
68
+ export type NapcatClientEventMap = Record<string, NapCatEvent>;
69
+
70
+ declare module '@zhin.js/feature-kit' {
71
+ interface AdapterClientRegistry {
72
+ readonly napcat: {
73
+ readonly client: NapcatClient;
74
+ readonly events: NapcatClientEventMap;
75
+ };
76
+ }
77
+ }
78
+
79
+ export const napcatClient = defineEndpointClient<NapcatClient, NapcatClientEventMap>('napcat');
@@ -0,0 +1,72 @@
1
+ /**
2
+ * NapCat endpoint management 语义端口(Console 社交面 RPC 消费,见
3
+ * packages/im/adapter/src/endpoint-management.ts)。
4
+ *
5
+ * 归一化取舍:
6
+ * - friend → {user_id:number, nickname, remark: remark ?? ''}
7
+ * - group → {group_id:number, name: group_name ?? name}
8
+ * - 群成员列表保持 OneBot11 原生形状,仅保证数组
9
+ */
10
+ import type {
11
+ EndpointFriend,
12
+ EndpointGroup,
13
+ EndpointManagement,
14
+ } from 'zhin.js/adapter';
15
+
16
+ /** 管理面只依赖 endpoint 的 callApi(ws/wss/http 三种传输各自实现)。 */
17
+ export interface NapCatManagementCaller {
18
+ callApi(action: string, params?: Record<string, unknown>): Promise<unknown>;
19
+ }
20
+
21
+ export function createNapCatEndpointManagement(
22
+ endpoint: NapCatManagementCaller,
23
+ ): EndpointManagement {
24
+ return Object.freeze<EndpointManagement>({
25
+ async listFriends(): Promise<readonly EndpointFriend[]> {
26
+ const data = await endpoint.callApi('get_friend_list');
27
+ return toArray(data).map((value) => {
28
+ const friend = asRecord(value);
29
+ return {
30
+ user_id: toNumberId(friend.user_id, 'user_id'),
31
+ nickname: String(friend.nickname ?? ''),
32
+ remark: String(friend.remark ?? ''),
33
+ };
34
+ });
35
+ },
36
+ async listGroups(): Promise<readonly EndpointGroup[]> {
37
+ const data = await endpoint.callApi('get_group_list');
38
+ return toArray(data).map((value) => {
39
+ const group = asRecord(value);
40
+ return {
41
+ group_id: toNumberId(group.group_id, 'group_id'),
42
+ name: String(group.group_name ?? group.name ?? ''),
43
+ };
44
+ });
45
+ },
46
+ async listGroupMembers(groupId: string): Promise<readonly unknown[]> {
47
+ const data = await endpoint.callApi('get_group_member_list', {
48
+ group_id: toNumberId(groupId, 'group_id'),
49
+ });
50
+ return toArray(data);
51
+ },
52
+ });
53
+ }
54
+
55
+ function asRecord(value: unknown): Record<string, unknown> {
56
+ return value !== null && typeof value === 'object'
57
+ ? value as Record<string, unknown>
58
+ : {};
59
+ }
60
+
61
+ function toArray(value: unknown): readonly unknown[] {
62
+ return Array.isArray(value) ? value : [];
63
+ }
64
+
65
+ /** console RPC 传入的 gid/uid 可能是字符串,统一收敛为数字。 */
66
+ function toNumberId(value: unknown, label: string): number {
67
+ const n = Number(value);
68
+ if (!Number.isFinite(n) || String(value ?? '').trim() === '') {
69
+ throw new TypeError(`napcat ${label} 必须是数字: ${String(value)}`);
70
+ }
71
+ return n;
72
+ }
@@ -0,0 +1,234 @@
1
+ import { Endpoint } from 'zhin.js/adapter';
2
+ /**
3
+ * NapCat HTTP endpoint — POST inbound events + HTTP API outbound.
4
+ */
5
+ import type { IncomingMessage, ServerResponse } from 'node:http';
6
+ import {
7
+ createRecallEndpointControl,
8
+ type EndpointControl,
9
+ type EndpointManagement,
10
+ type EndpointSendRequest,
11
+ } from 'zhin.js/adapter';
12
+ import type { HttpHost, HttpRouteRegistration } 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
+ callNapCatHttpAction,
25
+ formatInboundContent,
26
+ formatOutboundSegments,
27
+ isMessageEvent,
28
+ napcatInboundConversation,
29
+ napcatOutboundTarget,
30
+ senderNickname,
31
+ senderUserId,
32
+ type NapCatEvent,
33
+ type NapCatHttpConfig,
34
+ } from './protocol.js';
35
+ import { receiveNapCatSideEvent } from './side-event-dispatch.js';
36
+ import { createNapCatContentPort } from './onebot-get-msg.js';
37
+ import { NapcatClient } from './client.js';
38
+ import { readRequestBody } from './webhook.js';
39
+ import { NapCatWsEndpoint } from './ws-endpoint.js';
40
+ import { verifyNapCatAccessToken } from './wss-auth.js';
41
+
42
+ export interface NapCatHttpEndpointOptions {
43
+ readonly id: CapabilityId;
44
+ readonly http: HttpHost;
45
+ readonly config: NapCatHttpConfig;
46
+ readonly callHttpAction?: typeof callNapCatHttpAction;
47
+ }
48
+
49
+ export class NapCatHttpEndpoint extends Endpoint<NapcatClient> {
50
+ readonly client = new NapcatClient((action, params) => this.#callApi(action, params));
51
+ readonly #logger!: ReturnType<typeof getAdapterLogger>;
52
+
53
+ readonly #options: NapCatHttpEndpointOptions;
54
+ readonly #inboundDeduper = new InboundMessageDeduper();
55
+ readonly management: EndpointManagement = createNapCatEndpointManagement(this.client);
56
+ readonly control: EndpointControl = createRecallEndpointControl((id) => this.recallMessage(id));
57
+ readonly content = createNapCatContentPort((action, params) => this.client.callApi(action, params));
58
+ readonly #callHttpAction: typeof callNapCatHttpAction;
59
+ #routeReleases: HttpRouteRegistration[] = [];
60
+ #open = false;
61
+ #started = false;
62
+
63
+ constructor(options: NapCatHttpEndpointOptions) {
64
+ super();
65
+ this.#logger = getAdapterLogger('napcat', options.config.id);
66
+ this.#options = options;
67
+ this.#callHttpAction = options.callHttpAction ?? callNapCatHttpAction;
68
+ }
69
+
70
+ async start(): Promise<void> {
71
+ if (this.#started) return;
72
+ this.#started = true;
73
+ this.#setupRoutes();
74
+ this.#logger.info(formatCompact({
75
+ op: 'listen',
76
+ endpoint: this.#options.config.id,
77
+ mode: 'http',
78
+ path: this.#options.config.post_path,
79
+ }));
80
+ }
81
+
82
+ open(): void {
83
+ this.#open = true;
84
+ }
85
+
86
+ close(): void {
87
+ this.#open = false;
88
+ }
89
+
90
+ async stop(): Promise<void> {
91
+ this.#open = false;
92
+ for (const release of this.#routeReleases.splice(0)) release();
93
+ this.#inboundDeduper.clear();
94
+ this.#started = false;
95
+ this.#logger.debug(formatCompact({ op: 'disconnect' }));
96
+ }
97
+
98
+ async send({ conversation, payload }: EndpointSendRequest): Promise<string> {
99
+ const message = formatOutboundSegments(payload);
100
+ const { action, params } = buildSendAction(napcatOutboundTarget(conversation), message);
101
+ const resp = await this.#callHttpAction(
102
+ {
103
+ http_url: this.#options.config.http_url,
104
+ access_token: this.#options.config.access_token,
105
+ },
106
+ action,
107
+ params,
108
+ );
109
+ const data = resp.data as { message_id?: number | string } | undefined;
110
+ const messageId = data?.message_id != null ? String(data.message_id) : '';
111
+ this.#logger.debug(formatCompact({
112
+ op: 'napcat_send',
113
+ endpoint: this.#options.config.id,
114
+ target: `${conversation.kind}:${conversation.id}`,
115
+ messageId,
116
+ }));
117
+ return messageId;
118
+ }
119
+
120
+ async recallMessage(messageId: string): Promise<void> {
121
+ if (!messageId) return;
122
+ await this.client.callApi('delete_msg', { message_id: Number(messageId) });
123
+ }
124
+
125
+ #callApi(action: string, params: Record<string, unknown> = {}): Promise<unknown> {
126
+ return this.#callHttpAction(
127
+ {
128
+ http_url: this.#options.config.http_url,
129
+ access_token: this.#options.config.access_token,
130
+ },
131
+ action,
132
+ params,
133
+ ).then((resp) => resp.data);
134
+ }
135
+
136
+ admit(ev: NapCatEvent): void {
137
+ if (!this.#open) return;
138
+ void this.emitPlatform(napCatPlatformEventName(ev), ev).catch((error) => {
139
+ this.#logger.warn(formatCompact({
140
+ op: 'napcat_platform_event_failed',
141
+ error: error instanceof Error ? error.message : String(error),
142
+ }));
143
+ });
144
+ if (!isMessageEvent(ev)) {
145
+ receiveNapCatSideEvent(
146
+ (name, payload) => this.emit(name, payload),
147
+ this.#options.config.id,
148
+ this.client,
149
+ ev,
150
+ this.#logger,
151
+ );
152
+ return;
153
+ }
154
+ if (isSelfMessage(ev)) return;
155
+ const msgId = String(ev.message_id);
156
+ if (!this.#inboundDeduper.shouldProcess(msgId)) return;
157
+ if (Array.isArray(ev.message) || typeof ev.message === 'string') {
158
+ ev = { ...ev, message: normalizeMessage(ev.message) };
159
+ }
160
+ const conversation = napcatInboundConversation(String(this.#options.id), ev);
161
+ const nickname = senderNickname(ev);
162
+ const mentioned = isNapCatBotMentioned(ev);
163
+ void this.emit('message.receive', {
164
+ conversation,
165
+ message: { conversation, id: msgId },
166
+ content: formatInboundContent(ev),
167
+ sender: {
168
+ id: senderUserId(ev),
169
+ name: nickname,
170
+ ...(ev.sender?.role ? { roles: [ev.sender.role] } : {}),
171
+ },
172
+ endpointId: this.#options.config.id,
173
+ ...(mentioned ? { mentioned: true } : {}),
174
+ metadata: Object.freeze({
175
+ message_type: ev.message_type,
176
+ user_id: ev.user_id != null ? String(ev.user_id) : undefined,
177
+ group_id: ev.group_id != null ? String(ev.group_id) : undefined,
178
+ time: ev.time,
179
+ self_id: ev.self_id != null ? String(ev.self_id) : undefined,
180
+ role: ev.sender?.role,
181
+ ...(nickname ? { nickname } : {}),
182
+ }),
183
+ }).catch((err) => {
184
+ this.#logger.warn(formatCompact({
185
+ op: 'napcat_gateway_receive_failed',
186
+ target: `${conversation.kind}:${conversation.id}`,
187
+ error: err instanceof Error ? err.message : String(err),
188
+ }));
189
+ });
190
+ }
191
+
192
+ #setupRoutes(): void {
193
+ const path = this.#options.config.post_path;
194
+ this.#routeReleases.push(
195
+ this.#options.http.route('POST', path, async (request, response) => {
196
+ await this.#handlePost(request, response);
197
+ }, { summary: 'NapCat HTTP event callback', tags: ['napcat'] }),
198
+ );
199
+ }
200
+
201
+ async #handlePost(request: IncomingMessage, response: ServerResponse): Promise<void> {
202
+ try {
203
+ if (!verifyNapCatAccessToken(this.#options.config.access_token, request)) {
204
+ response.writeHead(403, { 'Content-Type': 'application/json' });
205
+ response.end(JSON.stringify({ message: 'Unauthorized' }));
206
+ return;
207
+ }
208
+ const raw = await readRequestBody(request);
209
+ let ev: NapCatEvent;
210
+ try {
211
+ ev = JSON.parse(raw) as NapCatEvent;
212
+ } catch {
213
+ response.writeHead(400, { 'Content-Type': 'application/json' });
214
+ response.end(JSON.stringify({ message: 'Invalid JSON' }));
215
+ return;
216
+ }
217
+ if (this.#open) this.admit(ev);
218
+ response.writeHead(200, { 'Content-Type': 'application/json' });
219
+ response.end(JSON.stringify({ status: 'ok' }));
220
+ } catch (error) {
221
+ this.#logger.error('NapCat HTTP webhook error:', error);
222
+ if (!response.headersSent) {
223
+ response.writeHead(500, { 'Content-Type': 'application/json' });
224
+ response.end(JSON.stringify({ message: 'Internal Server Error' }));
225
+ }
226
+ }
227
+ }
228
+ }
229
+
230
+ function napCatPlatformEventName(ev: NapCatEvent): string {
231
+ return [ev.post_type, ev.message_type ?? ev.notice_type ?? ev.request_type, ev.sub_type]
232
+ .filter(Boolean)
233
+ .join('.');
234
+ }
package/src/index.ts CHANGED
@@ -1,98 +1,74 @@
1
- /**
2
- * NapCat 适配器入口
3
- * 支持 OneBot11 标准 + go-cqhttp 扩展 + NapCat 独有 API
4
- * 连接方式:正向 WS / 反向 WS / HTTP
5
- */
6
- import path from 'path';
7
- import {
8
- usePlugin,
9
- type Plugin,
10
- type Context,
11
- type IGroupManagement,
12
- createGroupManagementTools,
13
- registerDefaultGroupPlatformPermitChecker,
14
- type ToolFeature,
15
- registerAgentPromptContributor,
16
- unregisterAgentPromptContributor,
17
- } from 'zhin.js';
18
- import type { Router } from '@zhin.js/host-router';
19
- import { PageManager } from '@zhin.js/host-api';
20
- import { NapCatAdapter } from './adapter.js';
21
- import { createNapCatTools } from './tools.js';
22
- import { createNapCatAgentPromptContributor } from './agent-prompt.js';
23
- import { registerRoutes } from './routes.js';
1
+ export {
2
+ buildSendAction,
3
+ buildWsConnectOptions,
4
+ callNapCatHttpAction,
5
+ formatInboundContent,
6
+ formatOutboundSegments,
7
+ getChannelId,
8
+ isMessageEvent,
9
+ mediaRefToOneBotFile,
10
+ napcatInboundConversation,
11
+ napcatOutboundTarget,
12
+ resolveNapCatConfig,
13
+ senderNickname,
14
+ senderUserId,
15
+ type MessageSegment,
16
+ type NapCatActionRequest,
17
+ type NapCatActionResponse,
18
+ type NapCatAdapterConfig,
19
+ type NapCatConfigBase,
20
+ type NapCatEndpointConfig,
21
+ type NapCatEvent,
22
+ type NapCatHttpConfig,
23
+ type NapCatMessageEvent,
24
+ type NapCatSender,
25
+ type NapCatWireSegment,
26
+ type NapCatWsConfig,
27
+ type NapCatWssConfig,
28
+ type ParsedSendTarget,
29
+ type ResolvedNapCatConfig,
30
+ } from './protocol.js';
24
31
 
25
- export * from './types.js';
26
- export { NapCatWsClient } from './endpoint-ws-client.js';
27
- export { NapCatWsServer } from './endpoint-ws-server.js';
28
- export { NapCatHttpEndpoint } from './endpoint-http.js';
29
- export { NapCatAdapter, type NapCatEndpoint } from './adapter.js';
30
- export { NapCatEndpointBase } from './endpoint-base.js';
31
32
  export {
32
- NapCatTypingIndicatorManager,
33
- enableTypingIndicator,
34
- type NapCatTypingIndicatorConfig,
35
- } from './typing-indicator.js';
33
+ InboundMessageDeduper,
34
+ isNapCatBotMentioned,
35
+ isSelfMessage,
36
+ normalizeMessage,
37
+ } from './napcat-inbound.js';
36
38
 
37
- declare module 'zhin.js' {
38
- namespace Plugin {
39
- interface Contexts {
40
- web: PageManager;
41
- router: Router;
42
- }
43
- }
44
- interface Adapters {
45
- napcat: NapCatAdapter;
46
- }
47
- }
39
+ export {
40
+ napcatClient,
41
+ type NapcatClient,
42
+ type NapcatClientEventMap,
43
+ } from './client.js';
48
44
 
49
- const plugin = usePlugin();
50
- const { provide, useContext } = plugin;
45
+ export { parseOneBotGetMsgResponse } from './onebot-get-msg.js';
51
46
 
52
- // ── 适配器注册 ─────────────────────────────────────────────────────
53
- provide({
54
- name: 'napcat',
55
- description: 'NapCatQQ 适配器(OneBot11 + go-cqhttp + NapCat 扩展,正向/反向 WS + HTTP)',
56
- mounted: async (p: Plugin) => {
57
- registerAgentPromptContributor(createNapCatAgentPromptContributor());
58
- const adapter = new NapCatAdapter(p);
59
- await adapter.start();
60
- return adapter;
61
- },
62
- dispose: async (adapter: NapCatAdapter) => {
63
- unregisterAgentPromptContributor('napcat');
64
- await adapter.stop();
65
- },
66
- } as unknown as Context<'napcat'>);
47
+ export {
48
+ NapCatWsEndpoint,
49
+ type NapCatWsEndpointOptions,
50
+ } from './ws-endpoint.js';
67
51
 
68
- // ── AI 工具注册 ────────────────────────────────────────────────────
69
- useContext('tool', 'napcat', (toolService: ToolFeature, napcat: NapCatAdapter) => {
70
- const disposers: (() => void)[] = [];
71
- disposers.push(registerDefaultGroupPlatformPermitChecker('napcat'));
52
+ export {
53
+ NapCatWssEndpoint,
54
+ type NapCatWssEndpointOptions,
55
+ } from './wss-endpoint.js';
72
56
 
73
- const groupTools = createGroupManagementTools(
74
- napcat as unknown as IGroupManagement,
75
- 'napcat',
76
- );
77
- disposers.push(...groupTools.map(t => toolService.addTool(t, plugin.name)));
57
+ export {
58
+ NapCatHttpEndpoint,
59
+ type NapCatHttpEndpointOptions,
60
+ } from './http-endpoint.js';
78
61
 
79
- const napcatTools = createNapCatTools(napcat);
80
- disposers.push(...napcatTools.map(t => toolService.addTool(t, plugin.name)));
62
+ export type { NapCatWsSocket, NapCatWsCreateOptions } from './ws-types.js';
81
63
 
82
- return () => disposers.forEach(d => d());
83
- });
64
+ export {
65
+ callNapCatWsAction,
66
+ decodeWsPayload,
67
+ handleNapCatWsMessage,
68
+ rejectAllPending,
69
+ startNapCatHeartbeat,
70
+ } from './ws-transport.js';
84
71
 
85
- // ── Web 控制台入口 ─────────────────────────────────────────────────
86
- useContext('web', (pageManager) => {
87
- pageManager.addEntry({
88
- id: 'napcat',
89
- development: path.resolve(import.meta.dirname, '../client/index.tsx'),
90
- production: path.resolve(import.meta.dirname, '../dist/index.js'),
91
- meta: { name: 'NapCat' },
92
- });
93
- });
72
+ export { verifyNapCatAccessToken } from './wss-auth.js';
94
73
 
95
- // ── HTTP 路由 ──────────────────────────────────────────────────────
96
- useContext('router', 'napcat', async (router: Router, napcat: NapCatAdapter) => {
97
- registerRoutes(router, napcat);
98
- });
74
+ export { readRequestBody } from './webhook.js';
@@ -0,0 +1,26 @@
1
+ /**
2
+ * `napcat.endpoint` 命令族:由 @zhin.js/adapter 的 createEndpointCommands 套件生成。
3
+ * commands/endpoint/ 下的 list / add / remove 直接默认导出这三项。
4
+ */
5
+ import { createEndpointCommands } from 'zhin.js/adapter';
6
+ import { defineCommand } from 'zhin.js/command';
7
+ import { napcatRuntimeStateToken } from './napcat-runtime-state.js';
8
+
9
+ export const napcatEndpointCommands = createEndpointCommands({
10
+ adapterKey: 'napcat',
11
+ adapterDisplayName: 'NapCat',
12
+ fields: [
13
+ { key: 'url', description: 'NapCat WebSocket URL(connection: ws 必填)' },
14
+ { key: 'path', description: 'reverse-wss 路径(connection: wss)' },
15
+ { key: 'http_url', description: 'HTTP API base URL(connection: http 出站)' },
16
+ { key: 'post_path', description: 'HTTP POST 事件路径(connection: http 入站)' },
17
+ { key: 'access_token', env: true, description: 'NapCat access token' },
18
+ ],
19
+ running: (use) => use(napcatRuntimeStateToken).endpoints.values(),
20
+ describeEntry: (entry) => {
21
+ if (entry.url) return `url: ${String(entry.url)}`;
22
+ if (entry.path) return `path: ${String(entry.path)}`;
23
+ if (entry.http_url) return `http_url: ${String(entry.http_url)}`;
24
+ return '';
25
+ },
26
+ }, defineCommand);
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * NapCat 入站消息治理:去重、自发过滤、消息归一化
3
3
  */
4
- import type { NapCatMessageEvent, MessageSegment } from './types.js';
4
+ import type { NapCatMessageEvent, MessageSegment } from './protocol.js';
5
5
 
6
6
  const DEDUPE_TTL_MS = 120_000;
7
7
 
@@ -24,7 +24,11 @@ export class InboundMessageDeduper {
24
24
  }
25
25
 
26
26
  /** 判断是否为 bot 自身发出的消息 */
27
- export function isSelfMessage(event: NapCatMessageEvent): boolean {
27
+ export function isSelfMessage(event: NapCatMessageEvent | {
28
+ post_type?: string;
29
+ self_id?: number | string;
30
+ user_id?: number | string;
31
+ }): boolean {
28
32
  if (event.post_type === 'message_sent') return true;
29
33
  if (event.self_id != null && event.user_id != null) {
30
34
  return Number(event.self_id) === Number(event.user_id);
@@ -44,14 +48,34 @@ export function normalizeMessage(message: MessageSegment[] | string): MessageSeg
44
48
  return [];
45
49
  }
46
50
 
51
+ const CQ_AT_RE = /\[CQ:at,qq=([^\],\s]+)\]/g;
52
+
53
+ function atTargetMatchesUin(target: unknown, uin: string): boolean {
54
+ const qq = String(target ?? '').trim();
55
+ return Boolean(qq) && qq !== 'all' && Number(qq) === Number(uin);
56
+ }
57
+
47
58
  /**
48
- * 生成用于 notice / request 事件的去重 key
59
+ * OneBot11 mentioned 判定:消息段 {type:'at', data:{qq}} 的 qq 等于本机 uin
60
+ * (事件 self_id)时为 true;`qq === 'all'` 不算。兼容 CQ 字符串形式。
49
61
  */
50
- export function resolveSideEventDedupeKey(event: any, prefix: string): string {
51
- const parts = [prefix, event.time, event.notice_type || event.request_type];
52
- if (event.group_id) parts.push(event.group_id);
53
- if (event.user_id) parts.push(event.user_id);
54
- if (event.message_id) parts.push(event.message_id);
55
- if (event.flag) parts.push(event.flag);
56
- return parts.join(':');
62
+ export function isNapCatBotMentioned(ev: {
63
+ self_id?: number | string;
64
+ message?: MessageSegment[] | string;
65
+ }): boolean {
66
+ if (ev.self_id == null) return false;
67
+ const uin = String(ev.self_id).trim();
68
+ if (!uin) return false;
69
+ const segments = normalizeMessage(ev.message ?? []);
70
+ for (const seg of segments) {
71
+ if (seg.type === 'at' && atTargetMatchesUin(seg.data?.qq, uin)) return true;
72
+ }
73
+ const text = segments
74
+ .map((seg) => (seg.type === 'text' ? String(seg.data?.text ?? '') : ''))
75
+ .join('');
76
+ if (!text) return false;
77
+ for (const match of text.matchAll(CQ_AT_RE)) {
78
+ if (atTargetMatchesUin(match[1], uin)) return true;
79
+ }
80
+ return false;
57
81
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * NapCat 插件实例的运行时状态:adapter create() 注册的 endpoint 列表。
3
+ * 由 plugin.ts setup() provide,adapter create 与 `napcat.endpoint` 命令共享(同一 owner generation)。
4
+ */
5
+ import { defineEndpointRuntimeStateToken } from 'zhin.js/adapter';
6
+
7
+ export const napcatRuntimeStateToken = defineEndpointRuntimeStateToken('napcat');