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,7 +1,14 @@
1
1
  import { BaseChannel } from './index';
2
2
  /**
3
- * WeChat Channel (Stub) v0.8.0
4
- * WeChat Official Account message handling, template messages, QR code login.
3
+ * WeChat Official Account Channel — v1.0.0
4
+ *
5
+ * Handles:
6
+ * - GET verification (signature/timestamp/nonce/echostr)
7
+ * - POST XML message parsing and reply
8
+ * - Customer Service Message API for async replies
9
+ * - Access token management with caching
10
+ * - Template messages
11
+ * - Subscribe/unsubscribe events
5
12
  */
6
13
  export interface WeChatChannelConfig {
7
14
  /** WeChat Official Account AppID */
@@ -10,9 +17,9 @@ export interface WeChatChannelConfig {
10
17
  appSecret: string;
11
18
  /** Verification token for message validation */
12
19
  token: string;
13
- /** AES encoding key for encrypted messages */
20
+ /** AES encoding key for encrypted messages (optional) */
14
21
  encodingAESKey?: string;
15
- /** HTTP server port (default: 3002) */
22
+ /** HTTP server port (default: 8080) */
16
23
  port?: number;
17
24
  }
18
25
  export interface WeChatMessage {
@@ -39,24 +46,37 @@ export declare class WeChatChannel extends BaseChannel {
39
46
  private config;
40
47
  private accessToken;
41
48
  private tokenExpiry;
49
+ private server;
42
50
  constructor(config: WeChatChannelConfig);
43
51
  start(): Promise<void>;
44
52
  stop(): Promise<void>;
45
- /** Get or refresh access token */
46
- getAccessToken(): Promise<string>;
53
+ /** Verify WeChat signature for GET requests */
54
+ private handleVerification;
55
+ /** Handle incoming POST messages (XML) */
56
+ private handleIncoming;
57
+ /** Verify WeChat signature */
58
+ verifySignature(signature: string, timestamp: string, nonce: string): boolean;
59
+ /** Parse WeChat XML message using regex */
60
+ static parseXML(xml: string): WeChatMessage | null;
61
+ /** Format response as WeChat XML */
62
+ static formatXMLResponse(toUser: string, fromUser: string, content: string): string;
47
63
  /** Handle incoming WeChat message */
48
64
  handleMessage(wxMsg: WeChatMessage): Promise<string>;
49
- /** Handle WeChat events (subscribe, scan, etc.) */
65
+ /** Handle WeChat events */
50
66
  private handleEvent;
51
67
  /** Convert WeChat message to internal Message */
52
68
  private wechatToMessage;
69
+ /** Get or refresh access token */
70
+ getAccessToken(): Promise<string>;
71
+ /** Send customer service message */
72
+ sendMessage(openId: string, text: string): Promise<void>;
53
73
  /** Send template message */
54
74
  sendTemplateMessage(data: TemplateMessageData): Promise<boolean>;
55
- /** Generate QR code for login (stub) */
56
- generateLoginQR(): Promise<{
57
- ticket: string;
58
- url: string;
59
- expireSeconds: number;
60
- }>;
75
+ /** Read request body */
76
+ private readBody;
77
+ /** Simple HTTPS GET */
78
+ private httpsGet;
79
+ /** Simple HTTPS POST */
80
+ private httpsPost;
61
81
  }
62
82
  //# sourceMappingURL=wechat.d.ts.map
@@ -1,37 +1,167 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.WeChatChannel = void 0;
4
37
  const index_1 = require("./index");
38
+ const http = __importStar(require("http"));
39
+ const https = __importStar(require("https"));
40
+ const crypto = __importStar(require("crypto"));
5
41
  class WeChatChannel extends index_1.BaseChannel {
6
42
  type = 'wechat';
7
43
  config;
8
44
  accessToken = null;
9
45
  tokenExpiry = 0;
46
+ server = null;
10
47
  constructor(config) {
11
48
  super();
12
49
  this.config = config;
13
50
  }
14
51
  async start() {
15
- // TODO: Start HTTP server to receive WeChat push messages
16
- // 1. Verify signature on GET requests
17
- // 2. Parse XML messages on POST requests
18
- // 3. Route to handler and reply with XML
52
+ const port = this.config.port ?? 8080;
53
+ this.server = http.createServer(async (req, res) => {
54
+ try {
55
+ if (req.method === 'GET') {
56
+ await this.handleVerification(req, res);
57
+ }
58
+ else if (req.method === 'POST') {
59
+ await this.handleIncoming(req, res);
60
+ }
61
+ else {
62
+ res.writeHead(405);
63
+ res.end('Method Not Allowed');
64
+ }
65
+ }
66
+ catch (err) {
67
+ console.error('[WeChatChannel] Error:', err);
68
+ res.writeHead(500);
69
+ res.end('Internal Server Error');
70
+ }
71
+ });
72
+ return new Promise((resolve) => {
73
+ this.server.listen(port, () => {
74
+ console.log(`[WeChatChannel] Listening on port ${port}`);
75
+ resolve();
76
+ });
77
+ });
19
78
  }
20
79
  async stop() {
21
- // TODO: Stop HTTP server
80
+ return new Promise((resolve, reject) => {
81
+ if (!this.server)
82
+ return resolve();
83
+ this.server.close((err) => (err ? reject(err) : resolve()));
84
+ });
22
85
  }
23
- /** Get or refresh access token */
24
- async getAccessToken() {
25
- if (this.accessToken && Date.now() < this.tokenExpiry) {
26
- return this.accessToken;
86
+ /** Verify WeChat signature for GET requests */
87
+ async handleVerification(req, res) {
88
+ const url = new URL(req.url ?? '/', `http://localhost`);
89
+ const signature = url.searchParams.get('signature') ?? '';
90
+ const timestamp = url.searchParams.get('timestamp') ?? '';
91
+ const nonce = url.searchParams.get('nonce') ?? '';
92
+ const echostr = url.searchParams.get('echostr') ?? '';
93
+ if (this.verifySignature(signature, timestamp, nonce)) {
94
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
95
+ res.end(echostr);
96
+ }
97
+ else {
98
+ res.writeHead(403);
99
+ res.end('Invalid signature');
100
+ }
101
+ }
102
+ /** Handle incoming POST messages (XML) */
103
+ async handleIncoming(req, res) {
104
+ const body = await this.readBody(req);
105
+ const wxMsg = WeChatChannel.parseXML(body);
106
+ if (!wxMsg) {
107
+ res.writeHead(400);
108
+ res.end('Bad Request');
109
+ return;
110
+ }
111
+ const replyText = await this.handleMessage(wxMsg);
112
+ if (replyText) {
113
+ const xml = WeChatChannel.formatXMLResponse(wxMsg.fromUserName, wxMsg.toUserName, replyText);
114
+ res.writeHead(200, { 'Content-Type': 'application/xml' });
115
+ res.end(xml);
27
116
  }
28
- // TODO: Implement token refresh
29
- // const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.config.appId}&secret=${this.config.appSecret}`;
30
- // const res = await fetch(url);
31
- // const data = await res.json();
32
- // this.accessToken = data.access_token;
33
- // this.tokenExpiry = Date.now() + (data.expires_in - 300) * 1000;
34
- return this.accessToken ?? '';
117
+ else {
118
+ // Return "success" to prevent WeChat retries
119
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
120
+ res.end('success');
121
+ }
122
+ }
123
+ /** Verify WeChat signature */
124
+ verifySignature(signature, timestamp, nonce) {
125
+ const arr = [this.config.token, timestamp, nonce].sort();
126
+ const hash = crypto.createHash('sha1').update(arr.join('')).digest('hex');
127
+ return hash === signature;
128
+ }
129
+ /** Parse WeChat XML message using regex */
130
+ static parseXML(xml) {
131
+ const extract = (tag) => {
132
+ const cdataMatch = xml.match(new RegExp(`<${tag}><!\\[CDATA\\[([\\s\\S]*?)\\]\\]></${tag}>`));
133
+ if (cdataMatch)
134
+ return cdataMatch[1];
135
+ const plainMatch = xml.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
136
+ return plainMatch ? plainMatch[1] : '';
137
+ };
138
+ const toUserName = extract('ToUserName');
139
+ const fromUserName = extract('FromUserName');
140
+ const createTime = extract('CreateTime');
141
+ const msgType = extract('MsgType');
142
+ if (!toUserName || !fromUserName || !msgType)
143
+ return null;
144
+ return {
145
+ toUserName,
146
+ fromUserName,
147
+ createTime: parseInt(createTime, 10) || 0,
148
+ msgType: msgType,
149
+ content: extract('Content') || undefined,
150
+ msgId: extract('MsgId') || undefined,
151
+ event: extract('Event') || undefined,
152
+ eventKey: extract('EventKey') || undefined,
153
+ };
154
+ }
155
+ /** Format response as WeChat XML */
156
+ static formatXMLResponse(toUser, fromUser, content) {
157
+ const timestamp = Math.floor(Date.now() / 1000);
158
+ return `<xml>
159
+ <ToUserName><![CDATA[${toUser}]]></ToUserName>
160
+ <FromUserName><![CDATA[${fromUser}]]></FromUserName>
161
+ <CreateTime>${timestamp}</CreateTime>
162
+ <MsgType><![CDATA[text]]></MsgType>
163
+ <Content><![CDATA[${content}]]></Content>
164
+ </xml>`;
35
165
  }
36
166
  /** Handle incoming WeChat message */
37
167
  async handleMessage(wxMsg) {
@@ -45,11 +175,13 @@ class WeChatChannel extends index_1.BaseChannel {
45
175
  }
46
176
  return '';
47
177
  }
48
- /** Handle WeChat events (subscribe, scan, etc.) */
178
+ /** Handle WeChat events */
49
179
  handleEvent(wxMsg) {
50
180
  switch (wxMsg.event) {
51
181
  case 'subscribe':
52
182
  return 'Welcome! How can I help you?';
183
+ case 'unsubscribe':
184
+ return '';
53
185
  case 'SCAN':
54
186
  return `QR code scanned: ${wxMsg.eventKey}`;
55
187
  default:
@@ -71,33 +203,88 @@ class WeChatChannel extends index_1.BaseChannel {
71
203
  },
72
204
  };
73
205
  }
206
+ /** Get or refresh access token */
207
+ async getAccessToken() {
208
+ if (this.accessToken && Date.now() < this.tokenExpiry) {
209
+ return this.accessToken;
210
+ }
211
+ const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.config.appId}&secret=${this.config.appSecret}`;
212
+ const data = await this.httpsGet(url);
213
+ const parsed = JSON.parse(data);
214
+ if (parsed.access_token) {
215
+ this.accessToken = parsed.access_token;
216
+ this.tokenExpiry = Date.now() + (parsed.expires_in - 300) * 1000;
217
+ return this.accessToken;
218
+ }
219
+ throw new Error(`[WeChatChannel] Failed to get access token: ${data}`);
220
+ }
221
+ /** Send customer service message */
222
+ async sendMessage(openId, text) {
223
+ const token = await this.getAccessToken();
224
+ const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${token}`;
225
+ const body = JSON.stringify({
226
+ touser: openId,
227
+ msgtype: 'text',
228
+ text: { content: text },
229
+ });
230
+ await this.httpsPost(url, body);
231
+ }
74
232
  /** Send template message */
75
233
  async sendTemplateMessage(data) {
76
- // TODO: Implement
77
- // const token = await this.getAccessToken();
78
- // const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`;
79
- // const res = await fetch(url, {
80
- // method: 'POST',
81
- // body: JSON.stringify({
82
- // touser: data.toUser,
83
- // template_id: data.templateId,
84
- // url: data.url,
85
- // data: data.data,
86
- // }),
87
- // });
88
- void data;
89
- return true;
90
- }
91
- /** Generate QR code for login (stub) */
92
- async generateLoginQR() {
93
- // TODO: Implement with WeChat QR code API
94
- // const token = await this.getAccessToken();
95
- // POST to https://api.weixin.qq.com/cgi-bin/qrcode/create
96
- return {
97
- ticket: 'stub-ticket',
98
- url: 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=stub-ticket',
99
- expireSeconds: 300,
100
- };
234
+ const token = await this.getAccessToken();
235
+ const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`;
236
+ const body = JSON.stringify({
237
+ touser: data.toUser,
238
+ template_id: data.templateId,
239
+ url: data.url,
240
+ data: data.data,
241
+ });
242
+ const result = await this.httpsPost(url, body);
243
+ const parsed = JSON.parse(result);
244
+ return parsed.errcode === 0;
245
+ }
246
+ /** Read request body */
247
+ readBody(req) {
248
+ return new Promise((resolve, reject) => {
249
+ const chunks = [];
250
+ req.on('data', (chunk) => chunks.push(chunk));
251
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
252
+ req.on('error', reject);
253
+ });
254
+ }
255
+ /** Simple HTTPS GET */
256
+ httpsGet(url) {
257
+ return new Promise((resolve, reject) => {
258
+ https.get(url, (res) => {
259
+ const chunks = [];
260
+ res.on('data', (chunk) => chunks.push(chunk));
261
+ res.on('end', () => resolve(Buffer.concat(chunks).toString()));
262
+ res.on('error', reject);
263
+ }).on('error', reject);
264
+ });
265
+ }
266
+ /** Simple HTTPS POST */
267
+ httpsPost(url, body) {
268
+ return new Promise((resolve, reject) => {
269
+ const parsed = new URL(url);
270
+ const req = https.request({
271
+ hostname: parsed.hostname,
272
+ path: parsed.pathname + parsed.search,
273
+ method: 'POST',
274
+ headers: {
275
+ 'Content-Type': 'application/json',
276
+ 'Content-Length': Buffer.byteLength(body),
277
+ },
278
+ }, (res) => {
279
+ const chunks = [];
280
+ res.on('data', (chunk) => chunks.push(chunk));
281
+ res.on('end', () => resolve(Buffer.concat(chunks).toString()));
282
+ res.on('error', reject);
283
+ });
284
+ req.on('error', reject);
285
+ req.write(body);
286
+ req.end();
287
+ });
101
288
  }
102
289
  }
103
290
  exports.WeChatChannel = WeChatChannel;