@amaster.ai/pi-channels 0.1.2-beta.2

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 (63) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +153 -0
  3. package/dist/adapters/feishu.d.ts +5 -0
  4. package/dist/adapters/feishu.d.ts.map +1 -0
  5. package/dist/adapters/feishu.js +312 -0
  6. package/dist/adapters/feishu.js.map +1 -0
  7. package/dist/adapters/webhook.d.ts +3 -0
  8. package/dist/adapters/webhook.d.ts.map +1 -0
  9. package/dist/adapters/webhook.js +63 -0
  10. package/dist/adapters/webhook.js.map +1 -0
  11. package/dist/adapters/wecom/adapter.d.ts +3 -0
  12. package/dist/adapters/wecom/adapter.d.ts.map +1 -0
  13. package/dist/adapters/wecom/adapter.js +202 -0
  14. package/dist/adapters/wecom/adapter.js.map +1 -0
  15. package/dist/adapters/wecom/client.d.ts +13 -0
  16. package/dist/adapters/wecom/client.d.ts.map +1 -0
  17. package/dist/adapters/wecom/client.js +116 -0
  18. package/dist/adapters/wecom/client.js.map +1 -0
  19. package/dist/adapters/wecom/crypto.d.ts +14 -0
  20. package/dist/adapters/wecom/crypto.d.ts.map +1 -0
  21. package/dist/adapters/wecom/crypto.js +37 -0
  22. package/dist/adapters/wecom/crypto.js.map +1 -0
  23. package/dist/adapters/wecom/errors.d.ts +25 -0
  24. package/dist/adapters/wecom/errors.d.ts.map +1 -0
  25. package/dist/adapters/wecom/errors.js +56 -0
  26. package/dist/adapters/wecom/errors.js.map +1 -0
  27. package/dist/adapters/wecom/types.d.ts +52 -0
  28. package/dist/adapters/wecom/types.d.ts.map +1 -0
  29. package/dist/adapters/wecom/types.js +2 -0
  30. package/dist/adapters/wecom/types.js.map +1 -0
  31. package/dist/adapters/wecom/xml.d.ts +4 -0
  32. package/dist/adapters/wecom/xml.d.ts.map +1 -0
  33. package/dist/adapters/wecom/xml.js +16 -0
  34. package/dist/adapters/wecom/xml.js.map +1 -0
  35. package/dist/adapters/wecom.d.ts +4 -0
  36. package/dist/adapters/wecom.d.ts.map +1 -0
  37. package/dist/adapters/wecom.js +3 -0
  38. package/dist/adapters/wecom.js.map +1 -0
  39. package/dist/bridge.d.ts +26 -0
  40. package/dist/bridge.d.ts.map +1 -0
  41. package/dist/bridge.js +219 -0
  42. package/dist/bridge.js.map +1 -0
  43. package/dist/config.d.ts +3 -0
  44. package/dist/config.d.ts.map +1 -0
  45. package/dist/config.js +76 -0
  46. package/dist/config.js.map +1 -0
  47. package/dist/http.d.ts +11 -0
  48. package/dist/http.d.ts.map +1 -0
  49. package/dist/http.js +39 -0
  50. package/dist/http.js.map +1 -0
  51. package/dist/index.d.ts +3 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +178 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/registry.d.ts +34 -0
  56. package/dist/registry.d.ts.map +1 -0
  57. package/dist/registry.js +146 -0
  58. package/dist/registry.js.map +1 -0
  59. package/dist/types.d.ts +116 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/types.js +2 -0
  62. package/dist/types.js.map +1 -0
  63. package/package.json +53 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # @amaster.ai/pi-channels
2
+
3
+ Pi extension for native messaging channels.
4
+
5
+ This package follows the same extension shape as the open-source `@e9n/pi-channels`
6
+ package: it registers a `notify` tool, channel events, route aliases, and an optional
7
+ chat bridge that turns incoming channel messages into pi prompts.
8
+
9
+ It does not depend on `@e9n/pi-channels` at runtime. That package is published as
10
+ a standalone extension source package with the older `@mariozechner/*` peer
11
+ namespace and Slack/Telegram dependencies. This package keeps the same channel
12
+ contract while targeting this repo's `@earendil-works/*` API surface and native
13
+ Feishu/WeCom adapters.
14
+
15
+ ## Channels
16
+
17
+ - `feishu` - Native Feishu/Lark app messaging backed by the official
18
+ `@larksuiteoapi/node-sdk`. Supports outgoing text messages, WebSocket events
19
+ by default, and HTTP event callbacks as a fallback.
20
+ - `wecom` - Native WeCom self-built app messaging. Supports outgoing text
21
+ messages, appchat messages, encrypted HTTP callbacks for text messages, token
22
+ caching, request timeouts, and actionable API errors such as trusted-IP
23
+ failures.
24
+ - `webhook` - Generic outgoing HTTP requests.
25
+
26
+ ## Example
27
+
28
+ ```json
29
+ {
30
+ "pi-channels": {
31
+ "adapters": {
32
+ "feishu": {
33
+ "type": "feishu",
34
+ "appId": "${FEISHU_APP_ID}",
35
+ "appSecret": "${FEISHU_APP_SECRET}",
36
+ "eventMode": "websocket",
37
+ "respondToMentionsOnly": true
38
+ },
39
+ "wecom": {
40
+ "type": "wecom",
41
+ "corpId": "${WECOM_CORP_ID}",
42
+ "agentId": "${WECOM_AGENT_ID}",
43
+ "secret": "${WECOM_SECRET}",
44
+ "timeoutMs": 15000,
45
+ "token": "${WECOM_CALLBACK_TOKEN}",
46
+ "encodingAesKey": "${WECOM_ENCODING_AES_KEY}",
47
+ "incoming": {
48
+ "enabled": true,
49
+ "port": 8788,
50
+ "path": "/wecom/events"
51
+ }
52
+ }
53
+ },
54
+ "routes": {
55
+ "ops": {
56
+ "adapter": "feishu",
57
+ "recipient": "oc_xxx"
58
+ }
59
+ },
60
+ "bridge": {
61
+ "enabled": true
62
+ }
63
+ }
64
+ }
65
+ ```
66
+
67
+ ### Feishu modes
68
+
69
+ WebSocket is the default and recommended mode because it does not require a
70
+ public callback URL:
71
+
72
+ ```json
73
+ {
74
+ "type": "feishu",
75
+ "appId": "${FEISHU_APP_ID}",
76
+ "appSecret": "${FEISHU_APP_SECRET}",
77
+ "eventMode": "websocket",
78
+ "respondToMentionsOnly": true,
79
+ "allowedChatIds": ["oc_xxx"]
80
+ }
81
+ ```
82
+
83
+ Use HTTP callback mode when the deployment already exposes a Feishu event URL.
84
+ The SDK handles challenge responses, token verification, and encrypted event
85
+ payloads:
86
+
87
+ ```json
88
+ {
89
+ "type": "feishu",
90
+ "appId": "${FEISHU_APP_ID}",
91
+ "appSecret": "${FEISHU_APP_SECRET}",
92
+ "eventMode": "http",
93
+ "verificationToken": "${FEISHU_VERIFICATION_TOKEN}",
94
+ "encryptKey": "${FEISHU_ENCRYPT_KEY}",
95
+ "botOpenId": "ou_xxx",
96
+ "incoming": {
97
+ "port": 8787,
98
+ "path": "/feishu/events"
99
+ }
100
+ }
101
+ ```
102
+
103
+ Set `"eventMode": "off"` for outgoing-only usage.
104
+
105
+ ## Tool
106
+
107
+ ```text
108
+ notify(action: "send", adapter: "ops", text: "hello")
109
+ notify(action: "list")
110
+ notify(action: "test", adapter: "ops")
111
+ ```
112
+
113
+ For Feishu, recipients default to `chat_id`. Prefix the recipient to override the
114
+ receive id type:
115
+
116
+ ```text
117
+ chat_id:oc_xxx
118
+ open_id:ou_xxx
119
+ user_id:abc123
120
+ email:name@example.com
121
+ ```
122
+
123
+ For WeCom, recipients default to `touser`. Prefix the recipient to send to parties
124
+ or tags. Prefix with `chat:` or `appchat:` to use the WeCom appchat API:
125
+
126
+ ```text
127
+ user:zhangsan
128
+ party:2
129
+ tag:7
130
+ appchat:chat-id
131
+ ```
132
+
133
+ If WeCom returns `60020 not allow to access from your ip`, the adapter raises a
134
+ typed `WeComApiError` with category `ip_whitelist`. Configure the trusted IP in
135
+ the WeCom console, or run pi behind a fixed egress proxy that is allowed by the
136
+ enterprise.
137
+
138
+ ## Events
139
+
140
+ - `channel:send`
141
+ - `channel:receive`
142
+ - `channel:register`
143
+ - `channel:remove`
144
+ - `channel:list`
145
+
146
+ ## Commands
147
+
148
+ ```text
149
+ /channel list
150
+ /channel bridge on
151
+ /channel bridge off
152
+ /channel bridge status
153
+ ```
@@ -0,0 +1,5 @@
1
+ import type { AdapterConfig, ChannelAdapter } from '../types.js';
2
+ export declare function createFeishuAdapter(config: AdapterConfig, context?: {
3
+ log?: (event: string, data?: Record<string, unknown>, level?: string) => void;
4
+ }): ChannelAdapter;
5
+ //# sourceMappingURL=feishu.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feishu.d.ts","sourceRoot":"","sources":["../../src/adapters/feishu.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EAIf,MAAM,aAAa,CAAC;AA2JrB,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,aAAa,EACrB,OAAO,GAAE;IACP,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;CAC1E,GACL,cAAc,CA8OhB"}
@@ -0,0 +1,312 @@
1
+ import { createServer } from 'node:http';
2
+ import * as lark from '@larksuiteoapi/node-sdk';
3
+ function asConfig(config) {
4
+ return config;
5
+ }
6
+ function requireString(value, name) {
7
+ if (typeof value === 'string' && value.trim())
8
+ return value;
9
+ throw new Error(`Feishu adapter requires ${name}`);
10
+ }
11
+ function optionalNonEmptyString(value) {
12
+ return typeof value === 'string' && value.trim() ? value : undefined;
13
+ }
14
+ function parseTextContent(content) {
15
+ try {
16
+ const parsed = JSON.parse(content);
17
+ return { text: typeof parsed.text === 'string' ? parsed.text : '' };
18
+ }
19
+ catch {
20
+ return { text: content };
21
+ }
22
+ }
23
+ function resolveReceiveId(message, defaultType) {
24
+ const match = message.recipient.match(/^(chat_id|open_id|user_id|union_id|email):(.+)$/);
25
+ if (!match)
26
+ return { receiveIdType: defaultType, receiveId: message.recipient };
27
+ return { receiveIdType: match[1], receiveId: match[2] };
28
+ }
29
+ function resolveDomain(value) {
30
+ if (!value)
31
+ return undefined;
32
+ if (value === 'feishu')
33
+ return lark.Domain.Feishu;
34
+ if (value === 'lark')
35
+ return lark.Domain.Lark;
36
+ if (typeof value === 'string')
37
+ return value;
38
+ return undefined;
39
+ }
40
+ function resolveAppType(value) {
41
+ if (value === 'isv' || value === 'ISV')
42
+ return lark.AppType.ISV;
43
+ if (value === 'self_build' || value === 'selfBuild' || value === 'SelfBuild') {
44
+ return lark.AppType.SelfBuild;
45
+ }
46
+ return undefined;
47
+ }
48
+ function resolveLoggerLevel(value) {
49
+ if (value === 'debug')
50
+ return lark.LoggerLevel.debug;
51
+ if (value === 'info')
52
+ return lark.LoggerLevel.info;
53
+ if (value === 'warn')
54
+ return lark.LoggerLevel.warn;
55
+ if (value === 'trace')
56
+ return lark.LoggerLevel.trace;
57
+ return lark.LoggerLevel.error;
58
+ }
59
+ function createSdkLogger(log) {
60
+ const emit = (level, msg) => {
61
+ log?.('feishu-sdk', { message: msg.map(String).join(' ') }, level);
62
+ };
63
+ return {
64
+ error: (...msg) => emit('ERROR', msg),
65
+ warn: (...msg) => emit('WARN', msg),
66
+ info: (...msg) => emit('INFO', msg),
67
+ debug: (...msg) => emit('DEBUG', msg),
68
+ trace: (...msg) => emit('TRACE', msg),
69
+ };
70
+ }
71
+ function shouldAcceptMessage(msg, cfg) {
72
+ const allowedChatIds = cfg.allowedChatIds;
73
+ if (Array.isArray(allowedChatIds) &&
74
+ allowedChatIds.length > 0 &&
75
+ !allowedChatIds.includes(msg.chatId)) {
76
+ return false;
77
+ }
78
+ const allowedSenderIds = cfg.allowedSenderIds;
79
+ if (Array.isArray(allowedSenderIds) &&
80
+ allowedSenderIds.length > 0 &&
81
+ !allowedSenderIds.includes(msg.senderId)) {
82
+ return false;
83
+ }
84
+ if ((cfg.respondToMentionsOnly ?? true) && msg.chatType === 'group' && !msg.mentionedBot) {
85
+ return false;
86
+ }
87
+ return true;
88
+ }
89
+ function senderForMessage(chatId, threadId) {
90
+ return threadId ? `${chatId}:${threadId}` : chatId;
91
+ }
92
+ export function createFeishuAdapter(config, context = {}) {
93
+ const cfg = asConfig(config);
94
+ const appId = requireString(cfg.appId, 'appId');
95
+ const appSecret = requireString(cfg.appSecret, 'appSecret');
96
+ const defaultReceiveIdType = cfg.receiveIdType ?? 'chat_id';
97
+ const eventMode = resolveEventMode(cfg);
98
+ const logger = createSdkLogger(context.log);
99
+ const loggerLevel = resolveLoggerLevel(cfg.loggerLevel);
100
+ const domain = resolveDomain(cfg.domain);
101
+ const appType = resolveAppType(cfg.appType);
102
+ const client = new lark.Client({
103
+ appId,
104
+ appSecret,
105
+ logger,
106
+ loggerLevel,
107
+ source: 'amaster-pi-channels',
108
+ ...(domain !== undefined ? { domain } : {}),
109
+ ...(appType !== undefined ? { appType } : {}),
110
+ });
111
+ let channel = null;
112
+ let server = null;
113
+ async function sendText(message) {
114
+ if (!message.text)
115
+ throw new Error('Feishu adapter requires text');
116
+ const text = message.source ? `[${message.source}]\n${message.text}` : message.text;
117
+ const replyToMessageId = typeof message.metadata?.messageId === 'string'
118
+ ? message.metadata.messageId
119
+ : typeof message.metadata?.replyToMessageId === 'string'
120
+ ? message.metadata.replyToMessageId
121
+ : undefined;
122
+ if (replyToMessageId) {
123
+ const response = await client.im.message.reply({
124
+ path: { message_id: replyToMessageId },
125
+ data: {
126
+ msg_type: 'text',
127
+ content: JSON.stringify({ text }),
128
+ reply_in_thread: cfg.replyInThread ?? Boolean(message.metadata?.threadId),
129
+ },
130
+ });
131
+ if (response.code !== 0) {
132
+ throw new Error(`Feishu reply error: ${response.msg ?? response.code ?? 'unknown'}`);
133
+ }
134
+ return;
135
+ }
136
+ const { receiveIdType, receiveId } = resolveReceiveId(message, defaultReceiveIdType);
137
+ const response = await client.im.message.create({
138
+ params: { receive_id_type: receiveIdType },
139
+ data: {
140
+ receive_id: receiveId,
141
+ msg_type: 'text',
142
+ content: JSON.stringify({ text }),
143
+ },
144
+ });
145
+ if (response.code !== 0) {
146
+ throw new Error(`Feishu send error: ${response.msg ?? response.code ?? 'unknown'}`);
147
+ }
148
+ }
149
+ function handleNormalizedMessage(msg, onMessage) {
150
+ if (!shouldAcceptMessage({
151
+ chatId: msg.chatId,
152
+ senderId: msg.senderId,
153
+ chatType: msg.chatType,
154
+ mentionedBot: msg.mentionedBot,
155
+ }, cfg)) {
156
+ return;
157
+ }
158
+ if (msg.rawContentType !== 'text' && msg.rawContentType !== 'post')
159
+ return;
160
+ if (!msg.content.trim())
161
+ return;
162
+ void onMessage({
163
+ adapter: 'feishu',
164
+ sender: senderForMessage(msg.chatId, msg.threadId),
165
+ text: msg.content,
166
+ metadata: {
167
+ messageId: msg.messageId,
168
+ chatId: msg.chatId,
169
+ chatType: msg.chatType,
170
+ senderId: msg.senderId,
171
+ senderName: msg.senderName,
172
+ threadId: msg.threadId,
173
+ rootId: msg.rootId,
174
+ replyToMessageId: msg.replyToMessageId,
175
+ messageIdForReply: msg.messageId,
176
+ rawContentType: msg.rawContentType,
177
+ },
178
+ });
179
+ }
180
+ function handleRawMessage(data, onMessage) {
181
+ if (data.message.message_type !== 'text')
182
+ return;
183
+ const parsed = parseTextContent(data.message.content);
184
+ const senderId = data.sender.sender_id?.open_id ??
185
+ data.sender.sender_id?.user_id ??
186
+ data.sender.sender_id?.union_id ??
187
+ '';
188
+ const mentionedBot = !cfg.botOpenId ||
189
+ (data.message.mentions ?? []).some((mention) => mention.id.open_id === cfg.botOpenId ||
190
+ mention.id.user_id === cfg.botOpenId ||
191
+ mention.id.union_id === cfg.botOpenId);
192
+ if (!shouldAcceptMessage({
193
+ chatId: data.message.chat_id,
194
+ senderId,
195
+ chatType: data.message.chat_type,
196
+ mentionedBot,
197
+ }, cfg)) {
198
+ return;
199
+ }
200
+ const text = parsed.text.trim();
201
+ if (!text)
202
+ return;
203
+ void onMessage({
204
+ adapter: 'feishu',
205
+ sender: senderForMessage(data.message.chat_id, data.message.thread_id),
206
+ text,
207
+ metadata: {
208
+ eventId: data.event_id,
209
+ tenantKey: data.tenant_key,
210
+ messageId: data.message.message_id,
211
+ replyToMessageId: data.message.message_id,
212
+ chatId: data.message.chat_id,
213
+ chatType: data.message.chat_type,
214
+ threadId: data.message.thread_id,
215
+ rootId: data.message.root_id,
216
+ senderId: data.sender.sender_id,
217
+ },
218
+ });
219
+ }
220
+ async function start(onMessage) {
221
+ if (eventMode === 'off')
222
+ return;
223
+ if (eventMode === 'websocket') {
224
+ if (channel)
225
+ return;
226
+ channel = lark.createLarkChannel({
227
+ appId,
228
+ appSecret,
229
+ transport: 'websocket',
230
+ logger,
231
+ loggerLevel,
232
+ source: 'amaster-pi-channels',
233
+ includeRawEvent: true,
234
+ ...(domain !== undefined ? { domain } : {}),
235
+ policy: {
236
+ requireMention: cfg.respondToMentionsOnly ?? true,
237
+ respondToMentionAll: cfg.respondToMentionAll ?? false,
238
+ ...(Array.isArray(cfg.allowedChatIds) && cfg.allowedChatIds.length > 0
239
+ ? { groupAllowlist: cfg.allowedChatIds }
240
+ : {}),
241
+ ...(cfg.dmMode ? { dmMode: cfg.dmMode } : {}),
242
+ ...(Array.isArray(cfg.dmAllowlist) && cfg.dmAllowlist.length > 0
243
+ ? { dmAllowlist: cfg.dmAllowlist }
244
+ : {}),
245
+ },
246
+ ...(cfg.handshakeTimeoutMs ? { handshakeTimeoutMs: cfg.handshakeTimeoutMs } : {}),
247
+ ...(cfg.wsPingTimeoutSeconds
248
+ ? { wsConfig: { pingTimeout: cfg.wsPingTimeoutSeconds } }
249
+ : {}),
250
+ });
251
+ channel.on('message', (msg) => handleNormalizedMessage(msg, onMessage));
252
+ channel.on('error', (error) => {
253
+ context.log?.('feishu-channel-error', { error: error.message, code: error.code }, 'ERROR');
254
+ });
255
+ await channel.connect();
256
+ return;
257
+ }
258
+ if (server)
259
+ return;
260
+ const incoming = cfg.incoming ?? {};
261
+ const host = incoming.host ?? '0.0.0.0';
262
+ const port = incoming.port ?? 8787;
263
+ const path = incoming.path ?? '/feishu/events';
264
+ const dispatcher = new lark.EventDispatcher({
265
+ logger,
266
+ loggerLevel,
267
+ ...(optionalNonEmptyString(cfg.verificationToken)
268
+ ? { verificationToken: cfg.verificationToken }
269
+ : {}),
270
+ ...(optionalNonEmptyString(cfg.encryptKey) ? { encryptKey: cfg.encryptKey } : {}),
271
+ }).register({
272
+ 'im.message.receive_v1': async (data) => {
273
+ handleRawMessage(data, onMessage);
274
+ },
275
+ });
276
+ const handler = lark.adaptDefault(path, dispatcher, { autoChallenge: true });
277
+ server = createServer((request, response) => {
278
+ void handler(request, response);
279
+ });
280
+ await new Promise((resolve, reject) => {
281
+ server.once('error', reject);
282
+ server.listen(port, host, () => {
283
+ server.off('error', reject);
284
+ resolve();
285
+ });
286
+ });
287
+ }
288
+ return {
289
+ direction: eventMode === 'off' ? 'outgoing' : 'bidirectional',
290
+ send: sendText,
291
+ start,
292
+ async stop() {
293
+ if (channel) {
294
+ await channel.disconnect();
295
+ channel = null;
296
+ }
297
+ if (server) {
298
+ await new Promise((resolve) => server.close(() => resolve()));
299
+ server = null;
300
+ }
301
+ },
302
+ };
303
+ }
304
+ function resolveEventMode(cfg) {
305
+ if (cfg.eventMode === 'http' || cfg.eventMode === 'websocket' || cfg.eventMode === 'off') {
306
+ return cfg.eventMode;
307
+ }
308
+ if (cfg.incoming?.enabled)
309
+ return 'http';
310
+ return 'websocket';
311
+ }
312
+ //# sourceMappingURL=feishu.js.map