@zhin.js/adapter-napcat 3.0.1 → 4.0.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 (140) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +43 -96
  3. package/adapters/napcat.ts +39 -0
  4. package/agent/tools/ai_tts.ts +21 -0
  5. package/agent/tools/del_group_notice.ts +22 -0
  6. package/agent/tools/delete_essence_msg.ts +21 -0
  7. package/agent/tools/delete_friend.ts +20 -0
  8. package/agent/tools/download_file.ts +19 -0
  9. package/agent/tools/forward_single_msg.ts +32 -0
  10. package/agent/tools/get_ai_characters.ts +19 -0
  11. package/agent/tools/get_essence_list.ts +19 -0
  12. package/agent/tools/get_friend_msg_history.ts +20 -0
  13. package/agent/tools/get_group_file_url.ts +21 -0
  14. package/agent/tools/get_group_info_ex.ts +19 -0
  15. package/agent/tools/get_group_msg_history.ts +21 -0
  16. package/agent/tools/get_group_notice.ts +19 -0
  17. package/agent/tools/get_group_root_files.ts +19 -0
  18. package/agent/tools/get_group_shut_list.ts +19 -0
  19. package/agent/tools/get_mini_app_ark.ts +22 -0
  20. package/agent/tools/get_user_status.ts +18 -0
  21. package/agent/tools/group_sign.ts +20 -0
  22. package/agent/tools/mark_msg_as_read.ts +19 -0
  23. package/agent/tools/ocr_image.ts +18 -0
  24. package/agent/tools/send_forward_msg.ts +31 -0
  25. package/agent/tools/send_group_notice.ts +23 -0
  26. package/agent/tools/send_like.ts +20 -0
  27. package/agent/tools/send_poke.ts +20 -0
  28. package/agent/tools/set_avatar.ts +19 -0
  29. package/agent/tools/set_emoji_reaction.ts +20 -0
  30. package/agent/tools/set_essence_msg.ts +21 -0
  31. package/agent/tools/set_group_portrait.ts +22 -0
  32. package/agent/tools/set_online_status.ts +20 -0
  33. package/agent/tools/set_profile.ts +23 -0
  34. package/agent/tools/set_signature.ts +19 -0
  35. package/agent/tools/set_title.ts +23 -0
  36. package/agent/tools/translate.ts +18 -0
  37. package/agent/tools/upload_group_file.ts +23 -0
  38. package/lib/http-endpoint.d.ts +26 -0
  39. package/lib/http-endpoint.js +147 -0
  40. package/lib/index.d.ts +11 -21
  41. package/lib/index.js +10 -59
  42. package/lib/napcat-agent-deps.d.ts +51 -0
  43. package/lib/napcat-agent-deps.js +33 -0
  44. package/lib/napcat-inbound.d.ts +12 -5
  45. package/lib/napcat-inbound.js +28 -13
  46. package/lib/onebot-get-msg.d.ts +13 -2
  47. package/lib/onebot-get-msg.js +0 -1
  48. package/lib/protocol.d.ts +151 -0
  49. package/lib/protocol.js +217 -0
  50. package/lib/webhook.d.ts +2 -0
  51. package/lib/webhook.js +14 -0
  52. package/lib/ws-endpoint.d.ts +61 -0
  53. package/lib/ws-endpoint.js +357 -0
  54. package/lib/ws-transport.d.ts +13 -0
  55. package/lib/ws-transport.js +75 -0
  56. package/lib/ws-types.d.ts +17 -0
  57. package/lib/ws-types.js +1 -0
  58. package/lib/wss-auth.d.ts +2 -0
  59. package/lib/wss-auth.js +16 -0
  60. package/lib/wss-endpoint.d.ts +25 -0
  61. package/lib/wss-endpoint.js +157 -0
  62. package/package.json +48 -32
  63. package/plugin.ts +13 -0
  64. package/schema.json +48 -0
  65. package/src/http-endpoint.ts +197 -0
  66. package/src/index.ts +66 -82
  67. package/src/napcat-agent-deps.ts +95 -0
  68. package/src/napcat-inbound.ts +34 -10
  69. package/src/onebot-get-msg.ts +8 -2
  70. package/src/protocol.ts +373 -0
  71. package/src/webhook.ts +16 -0
  72. package/src/ws-endpoint.ts +452 -0
  73. package/src/ws-transport.ts +105 -0
  74. package/src/ws-types.ts +20 -0
  75. package/src/wss-auth.ts +17 -0
  76. package/src/wss-endpoint.ts +205 -0
  77. package/client/NapCatManagement.tsx +0 -113
  78. package/client/index.tsx +0 -11
  79. package/client/tsconfig.json +0 -7
  80. package/client/utils/api.ts +0 -30
  81. package/dist/index.js +0 -27
  82. package/lib/adapter.d.ts +0 -36
  83. package/lib/adapter.d.ts.map +0 -1
  84. package/lib/adapter.js +0 -102
  85. package/lib/adapter.js.map +0 -1
  86. package/lib/agent-prompt.d.ts +0 -3
  87. package/lib/agent-prompt.d.ts.map +0 -1
  88. package/lib/agent-prompt.js +0 -106
  89. package/lib/agent-prompt.js.map +0 -1
  90. package/lib/endpoint-base.d.ts +0 -144
  91. package/lib/endpoint-base.d.ts.map +0 -1
  92. package/lib/endpoint-base.js +0 -341
  93. package/lib/endpoint-base.js.map +0 -1
  94. package/lib/endpoint-http.d.ts +0 -17
  95. package/lib/endpoint-http.d.ts.map +0 -1
  96. package/lib/endpoint-http.js +0 -106
  97. package/lib/endpoint-http.js.map +0 -1
  98. package/lib/endpoint-ws-client.d.ts +0 -20
  99. package/lib/endpoint-ws-client.d.ts.map +0 -1
  100. package/lib/endpoint-ws-client.js +0 -139
  101. package/lib/endpoint-ws-client.js.map +0 -1
  102. package/lib/endpoint-ws-server.d.ts +0 -20
  103. package/lib/endpoint-ws-server.d.ts.map +0 -1
  104. package/lib/endpoint-ws-server.js +0 -137
  105. package/lib/endpoint-ws-server.js.map +0 -1
  106. package/lib/index.d.ts.map +0 -1
  107. package/lib/index.js.map +0 -1
  108. package/lib/napcat-inbound.d.ts.map +0 -1
  109. package/lib/napcat-inbound.js.map +0 -1
  110. package/lib/onebot-get-msg.d.ts.map +0 -1
  111. package/lib/onebot-get-msg.js.map +0 -1
  112. package/lib/routes.d.ts +0 -4
  113. package/lib/routes.d.ts.map +0 -1
  114. package/lib/routes.js +0 -61
  115. package/lib/routes.js.map +0 -1
  116. package/lib/segment-mapper.d.ts +0 -2
  117. package/lib/segment-mapper.d.ts.map +0 -1
  118. package/lib/segment-mapper.js +0 -2
  119. package/lib/segment-mapper.js.map +0 -1
  120. package/lib/tools.d.ts +0 -8
  121. package/lib/tools.d.ts.map +0 -1
  122. package/lib/tools.js +0 -605
  123. package/lib/tools.js.map +0 -1
  124. package/lib/types.d.ts +0 -275
  125. package/lib/types.d.ts.map +0 -1
  126. package/lib/types.js +0 -6
  127. package/lib/types.js.map +0 -1
  128. package/plugin.yml +0 -3
  129. package/src/adapter.ts +0 -109
  130. package/src/agent-prompt.ts +0 -116
  131. package/src/endpoint-base.ts +0 -386
  132. package/src/endpoint-http.ts +0 -95
  133. package/src/endpoint-ws-client.ts +0 -137
  134. package/src/endpoint-ws-server.ts +0 -136
  135. package/src/routes.ts +0 -61
  136. package/src/segment-mapper.ts +0 -1
  137. package/src/tools.ts +0 -632
  138. package/src/types.ts +0 -266
  139. /package/{skills/napcat → agent}/PERMITS.md +0 -0
  140. /package/{skills/napcat/SKILL.md → agent/skills/napcat.md} +0 -0
@@ -1,136 +0,0 @@
1
- /**
2
- * NapCat 反向 WebSocket 连接
3
- */
4
- import WebSocket, { WebSocketServer } from 'ws';
5
- import { formatCompact } from 'zhin.js';
6
- import type { IncomingMessage } from 'http';
7
- import { NapCatEndpointBase } from './endpoint-base.js';
8
- import type { NapCatWsServerConfig, ApiResponse } from './types.js';
9
- import type { NapCatAdapter } from './adapter.js';
10
- import type { Router } from '@zhin.js/host-router';
11
-
12
- export class NapCatWsServer extends NapCatEndpointBase {
13
- #wss?: WebSocketServer;
14
- #clientMap = new Map<string, WebSocket>();
15
- private heartbeatTimer?: NodeJS.Timeout;
16
- private requestId = 0;
17
- private pendingRequests = new Map<string, {
18
- resolve: (value: any) => void;
19
- reject: (error: Error) => void;
20
- timeout: NodeJS.Timeout;
21
- }>();
22
-
23
- declare $config: NapCatWsServerConfig;
24
-
25
- constructor(adapter: NapCatAdapter, public router: Router, config: NapCatWsServerConfig) {
26
- super(adapter, config);
27
- }
28
-
29
- async $connect(): Promise<void> {
30
- if (!this.$config.access_token) {
31
- this.logger.warn(formatCompact({ endpoint: this.$id, ok: false, error: 'missing access_token' }));
32
- }
33
- this.#wss = this.router.ws(this.$config.path, {
34
- verifyClient: (info: { origin: string; secure: boolean; req: IncomingMessage }) => {
35
- const authorization = info.req.headers['authorization'] || '';
36
- if (this.$config.access_token && authorization !== `Bearer ${this.$config.access_token}`) {
37
- this.logger.error(`[${this.$id}] auth failed`);
38
- return false;
39
- }
40
- return true;
41
- },
42
- });
43
- this.logger.info(formatCompact( { op: 'listen', endpoint: this.$id, mode: 'wss', path: this.$config.path }));
44
-
45
- this.#wss.on('connection', (client, req) => {
46
- this.startHeartbeat();
47
- this.logger.info(formatCompact({ endpoint: this.$id, peer: req.socket.remoteAddress }));
48
-
49
- client.on('error', (err) => this.logger.warn(formatCompact( {
50
- op: 'ws_error',
51
- endpoint: this.$id,
52
- ok: false,
53
- error: err instanceof Error ? err.message : String(err),
54
- })));
55
- client.on('close', (code, reason) => {
56
- const reasonStr = reason?.toString?.() || '';
57
- this.logger.warn(formatCompact( {
58
- op: 'disconnect',
59
- endpoint: this.$id,
60
- code,
61
- error: reasonStr || undefined,
62
- }));
63
- for (const [key, val] of this.#clientMap) {
64
- if (val === client) this.#clientMap.delete(key);
65
- }
66
- if (this.#clientMap.size === 0) this.$connected = false;
67
- });
68
- client.on('message', (data) => {
69
- try { this.handleWsMessage(client, JSON.parse(data.toString())); } catch (e) { this.emit('error', e); }
70
- });
71
- });
72
- }
73
-
74
- async $disconnect(): Promise<void> {
75
- this.#wss?.close();
76
- if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = undefined; }
77
- for (const [, req] of this.pendingRequests) { clearTimeout(req.timeout); req.reject(new Error('Connection closed')); }
78
- this.pendingRequests.clear();
79
- this.inboundDeduper.clear();
80
- this.$connected = false;
81
- }
82
-
83
- async callApi<T = any>(action: string, params: Record<string, any> = {}): Promise<T> {
84
- const selfId = this.getFirstSelfId();
85
- const client = this.#clientMap.get(selfId);
86
- if (!client || client.readyState !== WebSocket.OPEN) throw new Error('WebSocket is not connected');
87
- const echo = `req_${++this.requestId}`;
88
- return new Promise((resolve, reject) => {
89
- const timeout = setTimeout(() => { this.pendingRequests.delete(echo); reject(new Error(`API call timeout: ${action}`)); }, 30000);
90
- this.pendingRequests.set(echo, { resolve, reject, timeout });
91
- client.send(JSON.stringify({ action, params, echo }));
92
- });
93
- }
94
-
95
- private getFirstSelfId(): string {
96
- const first = this.#clientMap.keys().next().value;
97
- if (!first) throw new Error('No NapCat client connected to reverse WS');
98
- return first;
99
- }
100
-
101
- private handleWsMessage(client: WebSocket, message: any): void {
102
- if (message.self_id != null) {
103
- const selfIdStr = String(message.self_id);
104
- if (!this.#clientMap.has(selfIdStr) || this.#clientMap.get(selfIdStr) !== client) {
105
- this.#clientMap.set(selfIdStr, client);
106
- if (!this.$connected) this.$connected = true;
107
- }
108
- }
109
- if (message.echo && this.pendingRequests.has(message.echo)) {
110
- const req = this.pendingRequests.get(message.echo)!;
111
- this.pendingRequests.delete(message.echo);
112
- clearTimeout(req.timeout);
113
- const resp = message as ApiResponse;
114
- if (resp.status === 'ok') return req.resolve(resp.data);
115
- return req.reject(new Error(`API error [${resp.retcode}]: ${resp.message || resp.wording || 'unknown'}`));
116
- }
117
-
118
- if (message.post_type === 'meta_event' && message.sub_type === 'connect') {
119
- this.#clientMap.set(String(message.self_id), client);
120
- this.$connected = true;
121
- this.logger.info(formatCompact({ endpoint: this.$id, self_id: message.self_id }));
122
- return;
123
- }
124
- this.dispatchEvent(message);
125
- }
126
-
127
- private startHeartbeat(): void {
128
- if (this.heartbeatTimer) return;
129
- const interval = this.$config.heartbeat_interval || 30000;
130
- this.heartbeatTimer = setInterval(() => {
131
- for (const client of this.#wss?.clients || []) {
132
- if (client.readyState === WebSocket.OPEN) client.ping();
133
- }
134
- }, interval);
135
- }
136
- }
package/src/routes.ts DELETED
@@ -1,61 +0,0 @@
1
- import type { Router } from '@zhin.js/host-router';
2
- import type { NapCatAdapter } from './adapter.js';
3
-
4
- export function registerRoutes(router: Router, napcat: NapCatAdapter): void {
5
- router.get('/api/napcat/endpoints', async (ctx) => {
6
- try {
7
- const endpoints = Array.from(napcat.endpoints.values());
8
- if (endpoints.length === 0) {
9
- ctx.body = { success: true, data: [], message: '暂无 NapCat Endpoint 实例' };
10
- return;
11
- }
12
- const result = await Promise.all(
13
- endpoints.map(async (endpoint) => {
14
- try {
15
- const connection = (endpoint.$config as any).connection ?? 'ws';
16
- const base: Record<string, unknown> = {
17
- name: endpoint.$config.name,
18
- connected: endpoint.$connected || false,
19
- connection,
20
- status: endpoint.$connected ? 'online' : 'offline',
21
- lastActivity: new Date().toISOString(),
22
- };
23
- if (endpoint.$connected) {
24
- try {
25
- const friends = await endpoint.getFriendList();
26
- const groups = await endpoint.getGroupList();
27
- base.friendCount = Array.isArray(friends) ? friends.length : 0;
28
- base.groupCount = Array.isArray(groups) ? groups.length : 0;
29
- } catch {
30
- base.friendCount = 0;
31
- base.groupCount = 0;
32
- }
33
- } else {
34
- base.friendCount = 0;
35
- base.groupCount = 0;
36
- }
37
- return base;
38
- } catch {
39
- return {
40
- name: endpoint.$config.name,
41
- connected: false,
42
- connection: 'unknown',
43
- status: 'error',
44
- friendCount: 0,
45
- groupCount: 0,
46
- };
47
- }
48
- }),
49
- );
50
- ctx.body = { success: true, data: result, timestamp: new Date().toISOString() };
51
- } catch (error) {
52
- ctx.status = 500;
53
- ctx.body = {
54
- success: false,
55
- error: 'NAPCAT_API_ERROR',
56
- message: '获取 Endpoint 数据失败',
57
- details: process.env.NODE_ENV === 'development' ? (error as Error).message : undefined,
58
- };
59
- }
60
- });
61
- }
@@ -1 +0,0 @@
1
- export { toCanonicalSegments, fromCanonicalSegments } from 'zhin.js';