opc-agent 1.4.0 → 2.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 (198) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +91 -32
  3. package/dist/channels/email.d.ts +32 -26
  4. package/dist/channels/email.js +239 -62
  5. package/dist/channels/feishu.d.ts +21 -6
  6. package/dist/channels/feishu.js +225 -126
  7. package/dist/channels/telegram.d.ts +30 -9
  8. package/dist/channels/telegram.js +125 -33
  9. package/dist/channels/websocket.d.ts +46 -3
  10. package/dist/channels/websocket.js +306 -37
  11. package/dist/channels/wechat.d.ts +33 -13
  12. package/dist/channels/wechat.js +229 -42
  13. package/dist/cli.js +1127 -19
  14. package/dist/core/a2a.d.ts +17 -0
  15. package/dist/core/a2a.js +43 -1
  16. package/dist/core/agent.d.ts +39 -0
  17. package/dist/core/agent.js +228 -3
  18. package/dist/core/runtime.d.ts +7 -0
  19. package/dist/core/runtime.js +205 -2
  20. package/dist/core/sandbox.d.ts +26 -0
  21. package/dist/core/sandbox.js +117 -0
  22. package/dist/core/scheduler.d.ts +52 -0
  23. package/dist/core/scheduler.js +168 -0
  24. package/dist/core/subagent.d.ts +28 -0
  25. package/dist/core/subagent.js +65 -0
  26. package/dist/core/workflow-graph.d.ts +93 -0
  27. package/dist/core/workflow-graph.js +247 -0
  28. package/dist/daemon.d.ts +3 -0
  29. package/dist/daemon.js +134 -0
  30. package/dist/doctor.d.ts +15 -0
  31. package/dist/doctor.js +183 -0
  32. package/dist/eval/index.d.ts +65 -0
  33. package/dist/eval/index.js +191 -0
  34. package/dist/index.d.ts +37 -6
  35. package/dist/index.js +75 -3
  36. package/dist/plugins/content-filter.d.ts +7 -0
  37. package/dist/plugins/content-filter.js +25 -0
  38. package/dist/plugins/index.d.ts +42 -0
  39. package/dist/plugins/index.js +108 -2
  40. package/dist/plugins/logger.d.ts +6 -0
  41. package/dist/plugins/logger.js +20 -0
  42. package/dist/plugins/rate-limiter.d.ts +7 -0
  43. package/dist/plugins/rate-limiter.js +35 -0
  44. package/dist/protocols/a2a/client.d.ts +25 -0
  45. package/dist/protocols/a2a/client.js +115 -0
  46. package/dist/protocols/a2a/index.d.ts +6 -0
  47. package/dist/protocols/a2a/index.js +12 -0
  48. package/dist/protocols/a2a/server.d.ts +41 -0
  49. package/dist/protocols/a2a/server.js +295 -0
  50. package/dist/protocols/a2a/types.d.ts +91 -0
  51. package/dist/protocols/a2a/types.js +15 -0
  52. package/dist/protocols/a2a/utils.d.ts +6 -0
  53. package/dist/protocols/a2a/utils.js +47 -0
  54. package/dist/protocols/agui/client.d.ts +10 -0
  55. package/dist/protocols/agui/client.js +75 -0
  56. package/dist/protocols/agui/index.d.ts +4 -0
  57. package/dist/protocols/agui/index.js +25 -0
  58. package/dist/protocols/agui/server.d.ts +37 -0
  59. package/dist/protocols/agui/server.js +191 -0
  60. package/dist/protocols/agui/types.d.ts +107 -0
  61. package/dist/protocols/agui/types.js +17 -0
  62. package/dist/protocols/index.d.ts +2 -0
  63. package/dist/protocols/index.js +19 -0
  64. package/dist/protocols/mcp/agent-tools.d.ts +11 -0
  65. package/dist/protocols/mcp/agent-tools.js +129 -0
  66. package/dist/protocols/mcp/index.d.ts +5 -0
  67. package/dist/protocols/mcp/index.js +11 -0
  68. package/dist/protocols/mcp/server.d.ts +31 -0
  69. package/dist/protocols/mcp/server.js +248 -0
  70. package/dist/protocols/mcp/types.d.ts +92 -0
  71. package/dist/protocols/mcp/types.js +17 -0
  72. package/dist/providers/index.d.ts +5 -1
  73. package/dist/providers/index.js +16 -9
  74. package/dist/publish/index.d.ts +45 -0
  75. package/dist/publish/index.js +350 -0
  76. package/dist/schema/oad.d.ts +859 -67
  77. package/dist/schema/oad.js +47 -3
  78. package/dist/security/approval.d.ts +36 -0
  79. package/dist/security/approval.js +113 -0
  80. package/dist/security/index.d.ts +4 -0
  81. package/dist/security/index.js +8 -0
  82. package/dist/security/keys.d.ts +16 -0
  83. package/dist/security/keys.js +117 -0
  84. package/dist/skills/auto-learn.d.ts +28 -0
  85. package/dist/skills/auto-learn.js +257 -0
  86. package/dist/studio/server.d.ts +63 -0
  87. package/dist/studio/server.js +625 -0
  88. package/dist/studio-ui/index.html +662 -0
  89. package/dist/telemetry/index.d.ts +93 -0
  90. package/dist/telemetry/index.js +285 -0
  91. package/dist/tools/builtin/datetime.d.ts +3 -0
  92. package/dist/tools/builtin/datetime.js +44 -0
  93. package/dist/tools/builtin/file.d.ts +3 -0
  94. package/dist/tools/builtin/file.js +151 -0
  95. package/dist/tools/builtin/index.d.ts +15 -0
  96. package/dist/tools/builtin/index.js +30 -0
  97. package/dist/tools/builtin/shell.d.ts +3 -0
  98. package/dist/tools/builtin/shell.js +43 -0
  99. package/dist/tools/builtin/web.d.ts +3 -0
  100. package/dist/tools/builtin/web.js +37 -0
  101. package/dist/tools/mcp-client.d.ts +24 -0
  102. package/dist/tools/mcp-client.js +119 -0
  103. package/package.json +5 -3
  104. package/scripts/install.ps1 +31 -0
  105. package/scripts/install.sh +40 -0
  106. package/src/channels/email.ts +351 -177
  107. package/src/channels/feishu.ts +349 -236
  108. package/src/channels/telegram.ts +212 -90
  109. package/src/channels/websocket.ts +399 -87
  110. package/src/channels/wechat.ts +329 -149
  111. package/src/cli.ts +1201 -20
  112. package/src/core/a2a.ts +60 -0
  113. package/src/core/agent.ts +420 -152
  114. package/src/core/runtime.ts +174 -0
  115. package/src/core/sandbox.ts +143 -0
  116. package/src/core/scheduler.ts +187 -0
  117. package/src/core/subagent.ts +98 -0
  118. package/src/core/workflow-graph.ts +365 -0
  119. package/src/daemon.ts +96 -0
  120. package/src/doctor.ts +156 -0
  121. package/src/eval/index.ts +211 -0
  122. package/src/eval/suites/basic.json +16 -0
  123. package/src/eval/suites/memory.json +12 -0
  124. package/src/eval/suites/safety.json +14 -0
  125. package/src/index.ts +65 -6
  126. package/src/plugins/content-filter.ts +23 -0
  127. package/src/plugins/index.ts +133 -2
  128. package/src/plugins/logger.ts +18 -0
  129. package/src/plugins/rate-limiter.ts +38 -0
  130. package/src/protocols/a2a/client.ts +132 -0
  131. package/src/protocols/a2a/index.ts +8 -0
  132. package/src/protocols/a2a/server.ts +333 -0
  133. package/src/protocols/a2a/types.ts +88 -0
  134. package/src/protocols/a2a/utils.ts +50 -0
  135. package/src/protocols/agui/client.ts +83 -0
  136. package/src/protocols/agui/index.ts +4 -0
  137. package/src/protocols/agui/server.ts +218 -0
  138. package/src/protocols/agui/types.ts +153 -0
  139. package/src/protocols/index.ts +2 -0
  140. package/src/protocols/mcp/agent-tools.ts +134 -0
  141. package/src/protocols/mcp/index.ts +8 -0
  142. package/src/protocols/mcp/server.ts +262 -0
  143. package/src/protocols/mcp/types.ts +69 -0
  144. package/src/providers/index.ts +354 -339
  145. package/src/publish/index.ts +376 -0
  146. package/src/schema/oad.ts +204 -154
  147. package/src/security/approval.ts +131 -0
  148. package/src/security/index.ts +3 -0
  149. package/src/security/keys.ts +87 -0
  150. package/src/skills/auto-learn.ts +262 -0
  151. package/src/studio/server.ts +629 -0
  152. package/src/studio-ui/index.html +662 -0
  153. package/src/telemetry/index.ts +324 -0
  154. package/src/tools/builtin/datetime.ts +41 -0
  155. package/src/tools/builtin/file.ts +107 -0
  156. package/src/tools/builtin/index.ts +28 -0
  157. package/src/tools/builtin/shell.ts +43 -0
  158. package/src/tools/builtin/web.ts +35 -0
  159. package/src/tools/mcp-client.ts +131 -0
  160. package/src/types/agent-workstation.d.ts +2 -0
  161. package/tests/a2a-protocol.test.ts +285 -0
  162. package/tests/agui-protocol.test.ts +246 -0
  163. package/tests/auto-learn.test.ts +105 -0
  164. package/tests/builtin-tools.test.ts +83 -0
  165. package/tests/channels/discord.test.ts +79 -0
  166. package/tests/channels/email.test.ts +148 -0
  167. package/tests/channels/feishu.test.ts +123 -0
  168. package/tests/channels/telegram.test.ts +129 -0
  169. package/tests/channels/websocket.test.ts +53 -0
  170. package/tests/channels/wechat.test.ts +170 -0
  171. package/tests/chat-cli.test.ts +160 -0
  172. package/tests/cli.test.ts +46 -0
  173. package/tests/daemon.test.ts +135 -0
  174. package/tests/deepbrain-wire.test.ts +234 -0
  175. package/tests/doctor.test.ts +38 -0
  176. package/tests/eval.test.ts +173 -0
  177. package/tests/init-role.test.ts +124 -0
  178. package/tests/mcp-client.test.ts +92 -0
  179. package/tests/mcp-server.test.ts +178 -0
  180. package/tests/plugin-a2a-enhanced.test.ts +230 -0
  181. package/tests/publish.test.ts +231 -0
  182. package/tests/scheduler.test.ts +200 -0
  183. package/tests/security-enhanced.test.ts +233 -0
  184. package/tests/skill-learner.test.ts +161 -0
  185. package/tests/studio.test.ts +229 -0
  186. package/tests/subagent.test.ts +193 -0
  187. package/tests/telegram-discord.test.ts +60 -0
  188. package/tests/telemetry.test.ts +186 -0
  189. package/tests/tools/builtin-extended.test.ts +138 -0
  190. package/tests/workflow-graph.test.ts +279 -0
  191. package/tutorial/customer-service-agent/README.md +612 -0
  192. package/tutorial/customer-service-agent/SOUL.md +26 -0
  193. package/tutorial/customer-service-agent/agent.yaml +63 -0
  194. package/tutorial/customer-service-agent/package.json +19 -0
  195. package/tutorial/customer-service-agent/src/index.ts +69 -0
  196. package/tutorial/customer-service-agent/src/skills/faq.ts +27 -0
  197. package/tutorial/customer-service-agent/src/skills/ticket.ts +22 -0
  198. package/tutorial/customer-service-agent/tsconfig.json +14 -0
@@ -1,149 +1,329 @@
1
- import { BaseChannel } from './index';
2
- import type { Message } from '../core/types';
3
-
4
- /**
5
- * WeChat Channel (Stub) — v0.8.0
6
- * WeChat Official Account message handling, template messages, QR code login.
7
- */
8
-
9
- export interface WeChatChannelConfig {
10
- /** WeChat Official Account AppID */
11
- appId: string;
12
- /** WeChat Official Account AppSecret */
13
- appSecret: string;
14
- /** Verification token for message validation */
15
- token: string;
16
- /** AES encoding key for encrypted messages */
17
- encodingAESKey?: string;
18
- /** HTTP server port (default: 3002) */
19
- port?: number;
20
- }
21
-
22
- export interface WeChatMessage {
23
- toUserName: string;
24
- fromUserName: string;
25
- createTime: number;
26
- msgType: 'text' | 'image' | 'voice' | 'video' | 'event';
27
- content?: string;
28
- msgId?: string;
29
- event?: string;
30
- eventKey?: string;
31
- }
32
-
33
- export interface TemplateMessageData {
34
- toUser: string;
35
- templateId: string;
36
- url?: string;
37
- data: Record<string, { value: string; color?: string }>;
38
- }
39
-
40
- export class WeChatChannel extends BaseChannel {
41
- type = 'wechat';
42
- private config: WeChatChannelConfig;
43
- private accessToken: string | null = null;
44
- private tokenExpiry = 0;
45
-
46
- constructor(config: WeChatChannelConfig) {
47
- super();
48
- this.config = config;
49
- }
50
-
51
- async start(): Promise<void> {
52
- // TODO: Start HTTP server to receive WeChat push messages
53
- // 1. Verify signature on GET requests
54
- // 2. Parse XML messages on POST requests
55
- // 3. Route to handler and reply with XML
56
- }
57
-
58
- async stop(): Promise<void> {
59
- // TODO: Stop HTTP server
60
- }
61
-
62
- /** Get or refresh access token */
63
- async getAccessToken(): Promise<string> {
64
- if (this.accessToken && Date.now() < this.tokenExpiry) {
65
- return this.accessToken;
66
- }
67
-
68
- // TODO: Implement token refresh
69
- // const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.config.appId}&secret=${this.config.appSecret}`;
70
- // const res = await fetch(url);
71
- // const data = await res.json();
72
- // this.accessToken = data.access_token;
73
- // this.tokenExpiry = Date.now() + (data.expires_in - 300) * 1000;
74
-
75
- return this.accessToken ?? '';
76
- }
77
-
78
- /** Handle incoming WeChat message */
79
- async handleMessage(wxMsg: WeChatMessage): Promise<string> {
80
- if (wxMsg.msgType === 'event') {
81
- return this.handleEvent(wxMsg);
82
- }
83
-
84
- const message = this.wechatToMessage(wxMsg);
85
- if (this.handler) {
86
- const reply = await this.handler(message);
87
- return reply.content;
88
- }
89
- return '';
90
- }
91
-
92
- /** Handle WeChat events (subscribe, scan, etc.) */
93
- private handleEvent(wxMsg: WeChatMessage): string {
94
- switch (wxMsg.event) {
95
- case 'subscribe':
96
- return 'Welcome! How can I help you?';
97
- case 'SCAN':
98
- return `QR code scanned: ${wxMsg.eventKey}`;
99
- default:
100
- return '';
101
- }
102
- }
103
-
104
- /** Convert WeChat message to internal Message */
105
- private wechatToMessage(wxMsg: WeChatMessage): Message {
106
- return {
107
- id: wxMsg.msgId ?? `wx-${wxMsg.createTime}`,
108
- role: 'user',
109
- content: wxMsg.content ?? '',
110
- timestamp: wxMsg.createTime * 1000,
111
- metadata: {
112
- channel: 'wechat',
113
- fromUser: wxMsg.fromUserName,
114
- toUser: wxMsg.toUserName,
115
- msgType: wxMsg.msgType,
116
- },
117
- };
118
- }
119
-
120
- /** Send template message */
121
- async sendTemplateMessage(data: TemplateMessageData): Promise<boolean> {
122
- // TODO: Implement
123
- // const token = await this.getAccessToken();
124
- // const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`;
125
- // const res = await fetch(url, {
126
- // method: 'POST',
127
- // body: JSON.stringify({
128
- // touser: data.toUser,
129
- // template_id: data.templateId,
130
- // url: data.url,
131
- // data: data.data,
132
- // }),
133
- // });
134
- void data;
135
- return true;
136
- }
137
-
138
- /** Generate QR code for login (stub) */
139
- async generateLoginQR(): Promise<{ ticket: string; url: string; expireSeconds: number }> {
140
- // TODO: Implement with WeChat QR code API
141
- // const token = await this.getAccessToken();
142
- // POST to https://api.weixin.qq.com/cgi-bin/qrcode/create
143
- return {
144
- ticket: 'stub-ticket',
145
- url: 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=stub-ticket',
146
- expireSeconds: 300,
147
- };
148
- }
149
- }
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+ import * as http from 'http';
4
+ import * as https from 'https';
5
+ import * as crypto from 'crypto';
6
+
7
+ /**
8
+ * WeChat Official Account Channel — v1.0.0
9
+ *
10
+ * Handles:
11
+ * - GET verification (signature/timestamp/nonce/echostr)
12
+ * - POST XML message parsing and reply
13
+ * - Customer Service Message API for async replies
14
+ * - Access token management with caching
15
+ * - Template messages
16
+ * - Subscribe/unsubscribe events
17
+ */
18
+
19
+ export interface WeChatChannelConfig {
20
+ /** WeChat Official Account AppID */
21
+ appId: string;
22
+ /** WeChat Official Account AppSecret */
23
+ appSecret: string;
24
+ /** Verification token for message validation */
25
+ token: string;
26
+ /** AES encoding key for encrypted messages (optional) */
27
+ encodingAESKey?: string;
28
+ /** HTTP server port (default: 8080) */
29
+ port?: number;
30
+ }
31
+
32
+ export interface WeChatMessage {
33
+ toUserName: string;
34
+ fromUserName: string;
35
+ createTime: number;
36
+ msgType: 'text' | 'image' | 'voice' | 'video' | 'event';
37
+ content?: string;
38
+ msgId?: string;
39
+ event?: string;
40
+ eventKey?: string;
41
+ }
42
+
43
+ export interface TemplateMessageData {
44
+ toUser: string;
45
+ templateId: string;
46
+ url?: string;
47
+ data: Record<string, { value: string; color?: string }>;
48
+ }
49
+
50
+ export class WeChatChannel extends BaseChannel {
51
+ type = 'wechat';
52
+ private config: WeChatChannelConfig;
53
+ private accessToken: string | null = null;
54
+ private tokenExpiry = 0;
55
+ private server: http.Server | null = null;
56
+
57
+ constructor(config: WeChatChannelConfig) {
58
+ super();
59
+ this.config = config;
60
+ }
61
+
62
+ async start(): Promise<void> {
63
+ const port = this.config.port ?? 8080;
64
+
65
+ this.server = http.createServer(async (req, res) => {
66
+ try {
67
+ if (req.method === 'GET') {
68
+ await this.handleVerification(req, res);
69
+ } else if (req.method === 'POST') {
70
+ await this.handleIncoming(req, res);
71
+ } else {
72
+ res.writeHead(405);
73
+ res.end('Method Not Allowed');
74
+ }
75
+ } catch (err) {
76
+ console.error('[WeChatChannel] Error:', err);
77
+ res.writeHead(500);
78
+ res.end('Internal Server Error');
79
+ }
80
+ });
81
+
82
+ return new Promise((resolve) => {
83
+ this.server!.listen(port, () => {
84
+ console.log(`[WeChatChannel] Listening on port ${port}`);
85
+ resolve();
86
+ });
87
+ });
88
+ }
89
+
90
+ async stop(): Promise<void> {
91
+ return new Promise((resolve, reject) => {
92
+ if (!this.server) return resolve();
93
+ this.server.close((err) => (err ? reject(err) : resolve()));
94
+ });
95
+ }
96
+
97
+ /** Verify WeChat signature for GET requests */
98
+ private async handleVerification(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
99
+ const url = new URL(req.url ?? '/', `http://localhost`);
100
+ const signature = url.searchParams.get('signature') ?? '';
101
+ const timestamp = url.searchParams.get('timestamp') ?? '';
102
+ const nonce = url.searchParams.get('nonce') ?? '';
103
+ const echostr = url.searchParams.get('echostr') ?? '';
104
+
105
+ if (this.verifySignature(signature, timestamp, nonce)) {
106
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
107
+ res.end(echostr);
108
+ } else {
109
+ res.writeHead(403);
110
+ res.end('Invalid signature');
111
+ }
112
+ }
113
+
114
+ /** Handle incoming POST messages (XML) */
115
+ private async handleIncoming(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
116
+ const body = await this.readBody(req);
117
+ const wxMsg = WeChatChannel.parseXML(body);
118
+
119
+ if (!wxMsg) {
120
+ res.writeHead(400);
121
+ res.end('Bad Request');
122
+ return;
123
+ }
124
+
125
+ const replyText = await this.handleMessage(wxMsg);
126
+
127
+ if (replyText) {
128
+ const xml = WeChatChannel.formatXMLResponse(
129
+ wxMsg.fromUserName,
130
+ wxMsg.toUserName,
131
+ replyText
132
+ );
133
+ res.writeHead(200, { 'Content-Type': 'application/xml' });
134
+ res.end(xml);
135
+ } else {
136
+ // Return "success" to prevent WeChat retries
137
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
138
+ res.end('success');
139
+ }
140
+ }
141
+
142
+ /** Verify WeChat signature */
143
+ verifySignature(signature: string, timestamp: string, nonce: string): boolean {
144
+ const arr = [this.config.token, timestamp, nonce].sort();
145
+ const hash = crypto.createHash('sha1').update(arr.join('')).digest('hex');
146
+ return hash === signature;
147
+ }
148
+
149
+ /** Parse WeChat XML message using regex */
150
+ static parseXML(xml: string): WeChatMessage | null {
151
+ const extract = (tag: string): string => {
152
+ const cdataMatch = xml.match(new RegExp(`<${tag}><!\\[CDATA\\[([\\s\\S]*?)\\]\\]></${tag}>`));
153
+ if (cdataMatch) return cdataMatch[1];
154
+ const plainMatch = xml.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
155
+ return plainMatch ? plainMatch[1] : '';
156
+ };
157
+
158
+ const toUserName = extract('ToUserName');
159
+ const fromUserName = extract('FromUserName');
160
+ const createTime = extract('CreateTime');
161
+ const msgType = extract('MsgType');
162
+
163
+ if (!toUserName || !fromUserName || !msgType) return null;
164
+
165
+ return {
166
+ toUserName,
167
+ fromUserName,
168
+ createTime: parseInt(createTime, 10) || 0,
169
+ msgType: msgType as WeChatMessage['msgType'],
170
+ content: extract('Content') || undefined,
171
+ msgId: extract('MsgId') || undefined,
172
+ event: extract('Event') || undefined,
173
+ eventKey: extract('EventKey') || undefined,
174
+ };
175
+ }
176
+
177
+ /** Format response as WeChat XML */
178
+ static formatXMLResponse(toUser: string, fromUser: string, content: string): string {
179
+ const timestamp = Math.floor(Date.now() / 1000);
180
+ return `<xml>
181
+ <ToUserName><![CDATA[${toUser}]]></ToUserName>
182
+ <FromUserName><![CDATA[${fromUser}]]></FromUserName>
183
+ <CreateTime>${timestamp}</CreateTime>
184
+ <MsgType><![CDATA[text]]></MsgType>
185
+ <Content><![CDATA[${content}]]></Content>
186
+ </xml>`;
187
+ }
188
+
189
+ /** Handle incoming WeChat message */
190
+ async handleMessage(wxMsg: WeChatMessage): Promise<string> {
191
+ if (wxMsg.msgType === 'event') {
192
+ return this.handleEvent(wxMsg);
193
+ }
194
+
195
+ const message = this.wechatToMessage(wxMsg);
196
+ if (this.handler) {
197
+ const reply = await this.handler(message);
198
+ return reply.content;
199
+ }
200
+ return '';
201
+ }
202
+
203
+ /** Handle WeChat events */
204
+ private handleEvent(wxMsg: WeChatMessage): string {
205
+ switch (wxMsg.event) {
206
+ case 'subscribe':
207
+ return 'Welcome! How can I help you?';
208
+ case 'unsubscribe':
209
+ return '';
210
+ case 'SCAN':
211
+ return `QR code scanned: ${wxMsg.eventKey}`;
212
+ default:
213
+ return '';
214
+ }
215
+ }
216
+
217
+ /** Convert WeChat message to internal Message */
218
+ private wechatToMessage(wxMsg: WeChatMessage): Message {
219
+ return {
220
+ id: wxMsg.msgId ?? `wx-${wxMsg.createTime}`,
221
+ role: 'user',
222
+ content: wxMsg.content ?? '',
223
+ timestamp: wxMsg.createTime * 1000,
224
+ metadata: {
225
+ channel: 'wechat',
226
+ fromUser: wxMsg.fromUserName,
227
+ toUser: wxMsg.toUserName,
228
+ msgType: wxMsg.msgType,
229
+ },
230
+ };
231
+ }
232
+
233
+ /** Get or refresh access token */
234
+ async getAccessToken(): Promise<string> {
235
+ if (this.accessToken && Date.now() < this.tokenExpiry) {
236
+ return this.accessToken;
237
+ }
238
+
239
+ const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.config.appId}&secret=${this.config.appSecret}`;
240
+
241
+ const data = await this.httpsGet(url);
242
+ const parsed = JSON.parse(data);
243
+
244
+ if (parsed.access_token) {
245
+ this.accessToken = parsed.access_token;
246
+ this.tokenExpiry = Date.now() + (parsed.expires_in - 300) * 1000;
247
+ return this.accessToken!;
248
+ }
249
+
250
+ throw new Error(`[WeChatChannel] Failed to get access token: ${data}`);
251
+ }
252
+
253
+ /** Send customer service message */
254
+ async sendMessage(openId: string, text: string): Promise<void> {
255
+ const token = await this.getAccessToken();
256
+ const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${token}`;
257
+
258
+ const body = JSON.stringify({
259
+ touser: openId,
260
+ msgtype: 'text',
261
+ text: { content: text },
262
+ });
263
+
264
+ await this.httpsPost(url, body);
265
+ }
266
+
267
+ /** Send template message */
268
+ async sendTemplateMessage(data: TemplateMessageData): Promise<boolean> {
269
+ const token = await this.getAccessToken();
270
+ const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`;
271
+
272
+ const body = JSON.stringify({
273
+ touser: data.toUser,
274
+ template_id: data.templateId,
275
+ url: data.url,
276
+ data: data.data,
277
+ });
278
+
279
+ const result = await this.httpsPost(url, body);
280
+ const parsed = JSON.parse(result);
281
+ return parsed.errcode === 0;
282
+ }
283
+
284
+ /** Read request body */
285
+ private readBody(req: http.IncomingMessage): Promise<string> {
286
+ return new Promise((resolve, reject) => {
287
+ const chunks: Buffer[] = [];
288
+ req.on('data', (chunk) => chunks.push(chunk));
289
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
290
+ req.on('error', reject);
291
+ });
292
+ }
293
+
294
+ /** Simple HTTPS GET */
295
+ private httpsGet(url: string): Promise<string> {
296
+ return new Promise((resolve, reject) => {
297
+ https.get(url, (res) => {
298
+ const chunks: Buffer[] = [];
299
+ res.on('data', (chunk) => chunks.push(chunk));
300
+ res.on('end', () => resolve(Buffer.concat(chunks).toString()));
301
+ res.on('error', reject);
302
+ }).on('error', reject);
303
+ });
304
+ }
305
+
306
+ /** Simple HTTPS POST */
307
+ private httpsPost(url: string, body: string): Promise<string> {
308
+ return new Promise((resolve, reject) => {
309
+ const parsed = new URL(url);
310
+ const req = https.request({
311
+ hostname: parsed.hostname,
312
+ path: parsed.pathname + parsed.search,
313
+ method: 'POST',
314
+ headers: {
315
+ 'Content-Type': 'application/json',
316
+ 'Content-Length': Buffer.byteLength(body),
317
+ },
318
+ }, (res) => {
319
+ const chunks: Buffer[] = [];
320
+ res.on('data', (chunk) => chunks.push(chunk));
321
+ res.on('end', () => resolve(Buffer.concat(chunks).toString()));
322
+ res.on('error', reject);
323
+ });
324
+ req.on('error', reject);
325
+ req.write(body);
326
+ req.end();
327
+ });
328
+ }
329
+ }