feishu-user-plugin 1.3.7 → 1.3.8

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.
@@ -1,6 +1,7 @@
1
1
  const lark = require('@larksuiteoapi/node-sdk');
2
2
  const { fetchWithTimeout } = require('../../utils');
3
3
  const { stderrLogger } = require('../../logger');
4
+ const uatLifecycle = require('../../auth/uat');
4
5
 
5
6
  class LarkOfficialClient {
6
7
  constructor(appId, appSecret) {
@@ -74,254 +75,17 @@ class LarkOfficialClient {
74
75
  }
75
76
  }
76
77
 
77
- async _getValidUAT() {
78
- if (!this._uat) throw new Error('No user_access_token. Run: npx feishu-user-plugin oauth');
79
-
80
- const now = Math.floor(Date.now() / 1000);
81
- if (!this._uatExpires) this._uatExpires = this._decodeTokenExpiry(this._uat);
82
- // Proactively refresh if we know it's expiring within 5 min
83
- if (this._uatExpires > 0 && this._uatExpires <= now + 300) {
84
- return this._refreshUAT();
85
- }
86
- return this._uat;
87
- }
88
-
89
- _decodeTokenExpiry(token) {
90
- try {
91
- const payload = token?.split('.')?.[1];
92
- if (!payload) return 0;
93
- const data = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
94
- return typeof data.exp === 'number' ? data.exp : 0;
95
- } catch (_) {
96
- return 0;
97
- }
98
- }
99
-
100
- _adoptPersistedUATIfNewer() {
101
- try {
102
- // auth/credentials reads credentials.json first; falls back to legacy
103
- // mcpServers. The peer-rotated UAT will land wherever persistUAT wrote,
104
- // and we'll see it consistently.
105
- const { readCredentials } = require('../../auth/credentials');
106
- const creds = readCredentials();
107
- const token = creds.LARK_USER_ACCESS_TOKEN;
108
- const refresh = creds.LARK_USER_REFRESH_TOKEN;
109
- if (!token && !refresh) return false;
110
-
111
- const expires = parseInt(creds.LARK_UAT_EXPIRES || '0') || this._decodeTokenExpiry(token);
112
- const changed = (token && token !== this._uat)
113
- || (refresh && refresh !== this._uatRefresh)
114
- || (expires && expires !== this._uatExpires);
115
- if (!changed) return false;
116
-
117
- if (token) this._uat = token;
118
- if (refresh) this._uatRefresh = refresh;
119
- this._uatExpires = expires || 0;
120
- console.error('[feishu-user-plugin] UAT adopted latest persisted token before refresh');
121
- return true;
122
- } catch (e) {
123
- console.error(`[feishu-user-plugin] UAT persisted-token check failed: ${e.message}`);
124
- return false;
125
- }
126
- }
127
-
128
- // Cross-process advisory lock for UAT refresh. Feishu rotates the refresh_token
129
- // on every refresh (old one invalidated instantly). When multiple MCP server
130
- // processes share the same persisted refresh_token and all wake up near expiry,
131
- // they race: the first wins, the rest see `invalid_grant` and can't recover.
132
- // This lock serialises refreshes across processes; inside the critical section
133
- // we also re-read the persisted config so late arrivals adopt the winner's
134
- // token instead of attempting a doomed refresh with the already-rotated one.
135
- _uatLockPath() {
136
- const path = require('path');
137
- const os = require('os');
138
- return path.join(os.homedir(), '.claude', 'feishu-uat-refresh.lock');
139
- }
140
-
141
- async _acquireRefreshLock(lockPath, { staleMs = 30000, pollMs = 200, timeoutMs = 20000 } = {}) {
142
- const fs = require('fs');
143
- const path = require('path');
144
- try { fs.mkdirSync(path.dirname(lockPath), { recursive: true }); } catch (_) {}
145
- const start = Date.now();
146
- while (Date.now() - start < timeoutMs) {
147
- try {
148
- const fd = fs.openSync(lockPath, 'wx'); // O_CREAT | O_EXCL
149
- fs.writeSync(fd, `${process.pid}\n${Date.now()}\n`);
150
- fs.closeSync(fd);
151
- return true;
152
- } catch (e) {
153
- if (e.code !== 'EEXIST') throw e;
154
- try {
155
- const stat = fs.statSync(lockPath);
156
- if (Date.now() - stat.mtimeMs > staleMs) {
157
- try { fs.unlinkSync(lockPath); } catch (_) {}
158
- continue;
159
- }
160
- } catch (_) { /* lock vanished under us — retry */ }
161
- await new Promise(r => setTimeout(r, pollMs));
162
- }
163
- }
164
- return false;
165
- }
166
-
167
- _releaseRefreshLock(lockPath) {
168
- try { require('fs').unlinkSync(lockPath); } catch (_) {}
169
- }
170
-
171
- async _refreshUAT() {
172
- const lockPath = this._uatLockPath();
173
- const acquired = await this._acquireRefreshLock(lockPath);
174
- if (!acquired) {
175
- console.error('[feishu-user-plugin] UAT refresh lock timed out; proceeding without mutual exclusion');
176
- }
177
- try {
178
- // Re-check under lock: another process may have already refreshed and
179
- // persisted a new token while we waited. If so, adopt and skip the refresh.
180
- const now = Math.floor(Date.now() / 1000);
181
- if (this._adoptPersistedUATIfNewer() && this._uatExpires > now + 300) {
182
- return this._uat;
183
- }
184
-
185
- if (!this._uatRefresh) throw new Error('UAT expired and no refresh token. Run: npx feishu-user-plugin oauth');
186
-
187
- const res = await fetchWithTimeout('https://open.feishu.cn/open-apis/authen/v2/oauth/token', {
188
- method: 'POST',
189
- headers: { 'content-type': 'application/json' },
190
- body: JSON.stringify({
191
- grant_type: 'refresh_token',
192
- client_id: this.appId,
193
- client_secret: this.appSecret,
194
- refresh_token: this._uatRefresh,
195
- }),
196
- });
197
- const data = await res.json();
198
- const tokenData = data.access_token ? data : data.data;
199
- if (!tokenData?.access_token) throw new Error(`UAT refresh failed: ${JSON.stringify(data)}. Run: npx feishu-user-plugin oauth`);
200
-
201
- this._uat = tokenData.access_token;
202
- this._uatRefresh = tokenData.refresh_token || this._uatRefresh;
203
- const expiresIn = typeof tokenData.expires_in === 'number' && tokenData.expires_in > 0 ? tokenData.expires_in : 7200;
204
- this._uatExpires = Math.floor(Date.now() / 1000) + expiresIn;
205
- this._persistUAT();
206
- console.error('[feishu-user-plugin] UAT refreshed successfully');
207
- return this._uat;
208
- } finally {
209
- if (acquired) this._releaseRefreshLock(lockPath);
210
- }
211
- }
212
-
213
- _persistUAT() {
214
- // Lazy require to avoid circular dependency at module load time.
215
- // auth/credentials writes to credentials.json when it exists, otherwise
216
- // falls back to legacy mcpServers persistence — same call site, two
217
- // outcomes, same end result for callers.
218
- const { persistToConfig } = require('../../auth/credentials');
219
- persistToConfig({
220
- LARK_USER_ACCESS_TOKEN: this._uat,
221
- LARK_USER_REFRESH_TOKEN: this._uatRefresh,
222
- LARK_UAT_EXPIRES: String(this._uatExpires),
223
- });
224
- }
225
-
226
- // --- UAT-based IM operations (for P2P chats) ---
227
-
228
- // Wrapper: call fn with UAT, retry once after refresh if auth fails
229
- async _withUAT(fn) {
230
- let uat = await this._getValidUAT();
231
- const data = await fn(uat);
232
- // Known auth error codes: 99991668 (invalid), 99991663 (expired), 99991677 (auth_expired)
233
- if (data.code === 99991668 || data.code === 99991663 || data.code === 99991677) {
234
- // 99991668 is overloaded: "invalid token" (→ refresh helps) vs
235
- // "endpoint doesn't support UAT at all" (→ refresh is pointless, and
236
- // worse, it consumes a one-shot refresh_token rotation). The second
237
- // case is identifiable by the msg "user access token not support" or
238
- // "not support". If so, surface the code to the caller without refresh.
239
- if (data.code === 99991668 && typeof data.msg === 'string' && /not support/i.test(data.msg)) {
240
- return data;
241
- }
242
- // Token invalid/expired — try refresh once
243
- uat = await this._refreshUAT();
244
- return fn(uat);
245
- }
246
- return data;
247
- }
248
-
249
- // Generic UAT REST helper. Returns parsed JSON ({code, msg, data}).
250
- // Array query values are expanded to repeated keys (period_ids=a&period_ids=b)
251
- // because several Feishu endpoints (OKR, calendar) rely on that convention.
252
- async _uatREST(method, path, { body, query } = {}) {
253
- let qs = '';
254
- if (query) {
255
- const sp = new URLSearchParams();
256
- for (const [k, v] of Object.entries(query)) {
257
- if (v === undefined || v === null) continue;
258
- if (Array.isArray(v)) { for (const item of v) sp.append(k, String(item)); }
259
- else sp.append(k, String(v));
260
- }
261
- const str = sp.toString();
262
- if (str) qs = '?' + str;
263
- }
264
- const url = 'https://open.feishu.cn' + path + qs;
265
- return this._withUAT(async (uat) => {
266
- const headers = { 'Authorization': `Bearer ${uat}` };
267
- const init = { method, headers };
268
- if (body !== undefined) {
269
- headers['content-type'] = 'application/json';
270
- init.body = JSON.stringify(body);
271
- }
272
- const res = await fetchWithTimeout(url, init);
273
- return res.json();
274
- });
275
- }
276
-
277
- // Try UAT first (for resources likely owned by the user), fall back to app SDK on failure.
278
- // Returns SDK-shaped {code, msg, data, _viaUser}. _viaUser is true iff the UAT call succeeded;
279
- // callers can surface this to distinguish "created by user" vs "created by app" for resources
280
- // whose ownership matters (docs, bitables, folders).
281
- //
282
- // When BOTH paths fail (common for OKR/Calendar if neither UAT nor app has the scope),
283
- // the final error includes the UAT-side reason too, so the user can tell whether they
284
- // need a new OAuth (UAT missing scope) or a different app (app missing scope).
285
- async _asUserOrApp({ uatPath, method = 'GET', body, query, sdkFn, label }) {
286
- let uatSummary = null;
287
- if (this.hasUAT) {
288
- try {
289
- const data = await this._uatREST(method, uatPath, { body, query });
290
- if (data.code === 0) {
291
- data._viaUser = true;
292
- return data;
293
- }
294
- uatSummary = `as user: code=${data.code} msg=${data.msg}`;
295
- console.error(`[feishu-user-plugin] ${label} ${uatSummary}, retrying as app`);
296
- } catch (err) {
297
- uatSummary = `as user: ${err.message}`;
298
- console.error(`[feishu-user-plugin] ${label} as user threw (${err.message}), retrying as app`);
299
- }
300
- }
301
- try {
302
- const appData = await this._safeSDKCall(sdkFn, label);
303
- if (appData && typeof appData === 'object') {
304
- appData._viaUser = false;
305
- // Attach a warning when we silently fell back to bot identity. This lets
306
- // write handlers surface "⚠️ created as BOT, not you" so the user doesn't
307
- // discover it days later when a teammate can read the "private" resource.
308
- if (uatSummary) {
309
- appData._fallbackWarning = `⚠️ UAT 不可用 (${uatSummary}),本次操作以 bot 身份执行。资源归属于共享 bot「Claude聊天助手」,不是你。恢复方法:运行 \`npx feishu-user-plugin oauth\` 后重启 Claude Code / Codex。`;
310
- } else if (!this.hasUAT) {
311
- appData._fallbackWarning = `⚠️ 未配置 UAT,本次操作以 bot 身份执行。资源归属于共享 bot「Claude聊天助手」,不是你。想让资源归你所有,先跑 \`npx feishu-user-plugin oauth\` 然后重启 Claude Code / Codex。`;
312
- }
313
- }
314
- return appData;
315
- } catch (appErr) {
316
- if (uatSummary) {
317
- const err = new Error(`${label} failed on both identities. ${uatSummary}. as app: ${appErr.message}`);
318
- err.uatSummary = uatSummary;
319
- err.appError = appErr;
320
- throw err;
321
- }
322
- throw appErr;
323
- }
324
- }
78
+ // UAT lifecycle methods are extracted to src/auth/uat.js (v1.3.8 D.1).
79
+ // State (this._uat / this._uatRefresh / this._uatExpires) still lives here;
80
+ // function bodies live in auth/uat.js. These methods are 1-line delegates.
81
+ _decodeTokenExpiry(token) { return uatLifecycle.decodeTokenExpiry(token); }
82
+ async _getValidUAT() { return uatLifecycle.getValidUAT(this); }
83
+ _adoptPersistedUATIfNewer() { return uatLifecycle.adoptPersistedUATIfNewer(this); }
84
+ async _refreshUAT() { return uatLifecycle.refreshUAT(this); }
85
+ _persistUAT() { return uatLifecycle.persistUAT(this); }
86
+ async _withUAT(fn) { return uatLifecycle.withUAT(this, fn); }
87
+ async _uatREST(method, path, opts) { return uatLifecycle.uatREST(this, method, path, opts); }
88
+ async _asUserOrApp(opts) { return uatLifecycle.asUserOrApp(this, opts); }
325
89
 
326
90
  // --- Safe SDK Call (extracts real Feishu error from AxiosError) ---
327
91
 
@@ -1,6 +1,7 @@
1
1
  const path = require('path');
2
2
  const protobuf = require('protobufjs');
3
3
  const { generateRequestId, generateCid, parseCookie, formatCookie, fetchWithTimeout } = require('../utils');
4
+ const cookieHeartbeat = require('../auth/cookie');
4
5
 
5
6
  const GATEWAY_URL = 'https://internal-api-lark-api.feishu.cn/im/gateway/';
6
7
  const CSRF_URL = 'https://internal-api-lark-api.feishu.cn/accounts/csrf';
@@ -86,26 +87,9 @@ class LarkUserClient {
86
87
  }
87
88
 
88
89
  // --- Cookie Heartbeat ---
89
-
90
- _startHeartbeat() {
91
- // Refresh CSRF token every 4 hours to keep session alive
92
- // Feishu sl_session has 12h max-age; CSRF refresh also refreshes sl_session
93
- this._heartbeatTimer = setInterval(async () => {
94
- try {
95
- await this._getCsrfToken();
96
- // Lazy require to avoid circular dependency at module load time.
97
- // auth/credentials writes to credentials.json (single source of truth)
98
- // when it exists; falls back to legacy mcpServers persistence otherwise.
99
- const { persistToConfig } = require('../auth/credentials');
100
- persistToConfig({ LARK_COOKIE: this.cookieStr });
101
- console.error('[feishu-user-plugin] Cookie heartbeat: session refreshed and persisted');
102
- } catch (e) {
103
- console.error('[feishu-user-plugin] Cookie heartbeat failed:', e.message);
104
- }
105
- }, 4 * 60 * 60 * 1000); // 4 hours
106
- // Don't keep the process alive just for heartbeat
107
- if (this._heartbeatTimer.unref) this._heartbeatTimer.unref();
108
- }
90
+ // Body extracted to src/auth/cookie.js (v1.3.8 D.2). Timer state stays on
91
+ // this instance; auth/cookie.js mutates this._heartbeatTimer.
92
+ _startHeartbeat() { cookieHeartbeat.startHeartbeat(this); }
109
93
 
110
94
  async checkSession() {
111
95
  try {
@@ -205,11 +189,13 @@ class LarkUserClient {
205
189
  // missing required fields. Verified for IMAGE (v1.3.7 testing): the
206
190
  // simple {imageKey} content payload is rejected — Feishu Web encodes
207
191
  // images with extra metadata (image dimensions, mime type, etc.) that
208
- // we don't have in proto/lark.proto. Reverse-engineering requires Chrome
209
- // DevTools capture and is deferred to v1.3.8. Surface a clear error
210
- // routing the user to send_message_as_bot, which works.
192
+ // we don't have in proto/lark.proto. v1.3.8 shipped the capture/decode
193
+ // tooling (scripts/decode-feishu-protobuf.js + capture-feishu-protobuf.js
194
+ // + docs/COOKIE-PROTOBUF-CAPTURES.md). Actual reverse-engineering moved
195
+ // to v1.3.9. Surface a clear error routing the user to
196
+ // send_message_as_bot, which works.
211
197
  if (type === MsgType.IMAGE) {
212
- throw new Error('send_image_as_user: Feishu cookie protobuf gateway rejected the IMAGE wire format (HTTP 400). User-identity image sends are not yet supported — wire format reverse-engineering is deferred to v1.3.8. Workaround: use send_message_as_bot(chat_id, msg_type="image", payload={image_key:"..."}).');
198
+ throw new Error('send_image_as_user: Feishu cookie protobuf gateway rejected the IMAGE wire format (HTTP 400). User-identity image sends are not yet supported — wire format reverse-engineering is deferred to v1.3.9 (v1.3.8 shipped the capture/decode tooling at scripts/decode-feishu-protobuf.js). Workaround: use send_message_as_bot(chat_id, msg_type="image", payload={image_key:"..."}).');
213
199
  }
214
200
  throw new Error(`_sendMsg: cookie protobuf gateway returned non-2xx for type=${type}. The wire format likely doesn't match what Feishu expects.`);
215
201
  }
package/src/config.js CHANGED
@@ -274,23 +274,23 @@ function persistToConfig(updates) {
274
274
  * client: 'claude' (default) | 'codex' | 'both'
275
275
  * @returns {{ configPath: string, codexConfigPath?: string }}
276
276
  */
277
- function writeNewConfig(env, configPath, projectPath, client) {
277
+ function writeNewConfig(env, configPath, projectPath, client, options = {}) {
278
278
  const results = {};
279
279
 
280
280
  // --- Claude Code (JSON) ---
281
281
  if (client !== 'codex') {
282
- results.configPath = _writeClaudeConfig(env, configPath, projectPath);
282
+ results.configPath = _writeClaudeConfig(env, configPath, projectPath, options);
283
283
  }
284
284
 
285
285
  // --- Codex (TOML) ---
286
286
  if (client === 'codex' || client === 'both') {
287
- results.codexConfigPath = _writeCodexConfig(env);
287
+ results.codexConfigPath = _writeCodexConfig(env, options);
288
288
  }
289
289
 
290
290
  return results;
291
291
  }
292
292
 
293
- function _writeClaudeConfig(env, configPath, projectPath) {
293
+ function _writeClaudeConfig(env, configPath, projectPath, options = {}) {
294
294
  if (!configPath) {
295
295
  configPath = path.join(process.env.HOME || '', '.claude.json');
296
296
  }
@@ -312,7 +312,9 @@ function _writeClaudeConfig(env, configPath, projectPath) {
312
312
  const serverEntry = {
313
313
  command: 'npx',
314
314
  args: ['-y', 'feishu-user-plugin'],
315
- env,
315
+ env: options.pointerOnly
316
+ ? { FEISHU_PLUGIN_PROFILE: env.FEISHU_PLUGIN_PROFILE || 'default' }
317
+ : env,
316
318
  };
317
319
 
318
320
  if (projectPath && config.projects?.[projectPath]) {
@@ -334,7 +336,7 @@ function _writeClaudeConfig(env, configPath, projectPath) {
334
336
  return configPath;
335
337
  }
336
338
 
337
- function _writeCodexConfig(env) {
339
+ function _writeCodexConfig(env, options = {}) {
338
340
  const home = process.env.HOME || '';
339
341
  const codexDir = path.join(home, '.codex');
340
342
  const configPath = path.join(codexDir, 'config.toml');
@@ -352,8 +354,11 @@ function _writeCodexConfig(env) {
352
354
  content = _removeTomlServer(content, name);
353
355
  }
354
356
 
355
- // Append new entry
356
- content = content.trimEnd() + '\n\n' + _generateTomlServerEntry('feishu-user-plugin', env);
357
+ // Append new entry — pointer-only writes only FEISHU_PLUGIN_PROFILE
358
+ const envToWrite = options.pointerOnly
359
+ ? { FEISHU_PLUGIN_PROFILE: env.FEISHU_PLUGIN_PROFILE || 'default' }
360
+ : env;
361
+ content = content.trimEnd() + '\n\n' + _generateTomlServerEntry('feishu-user-plugin', envToWrite);
357
362
 
358
363
  _atomicWrite(configPath, content);
359
364
  console.error(`[feishu-user-plugin] Codex config written to ${configPath}`);
@@ -0,0 +1,100 @@
1
+ // src/events/event-buffer.js — in-memory FIFO buffer for WS events.
2
+ //
3
+ // Single-consumer model: tools/events.js pulls events with `drain()`, which
4
+ // removes them from the buffer. If multiple agents read concurrently they'll
5
+ // see partial sets — explicitly NOT designed to fan out the same event to N
6
+ // consumers, since the MCP server already serializes tool calls.
7
+ //
8
+ // What this owns:
9
+ // - _events: ordered list of events (oldest first)
10
+ // - cap: max retained; oldest dropped when full
11
+ // - push(event): append + trim
12
+ // - drain(filter?): remove and return matching events
13
+ // - peek(filter?): return matching events without removing
14
+ // - size, cap accessors
15
+
16
+ const DEFAULT_CAP = 1000;
17
+
18
+ class EventBuffer {
19
+ constructor({ cap = DEFAULT_CAP } = {}) {
20
+ this._events = [];
21
+ this._cap = Math.max(1, cap | 0);
22
+ this._totalSeen = 0;
23
+ this._totalDropped = 0;
24
+ }
25
+
26
+ push(event) {
27
+ if (!event || typeof event !== 'object') return;
28
+ if (!event._received_at) event._received_at = Math.floor(Date.now() / 1000);
29
+ this._events.push(event);
30
+ this._totalSeen++;
31
+ while (this._events.length > this._cap) {
32
+ this._events.shift();
33
+ this._totalDropped++;
34
+ }
35
+ }
36
+
37
+ drain(filter) {
38
+ if (!filter) {
39
+ const out = this._events;
40
+ this._events = [];
41
+ return out;
42
+ }
43
+ const fn = this._compileFilter(filter);
44
+ const kept = [];
45
+ const drained = [];
46
+ for (const e of this._events) {
47
+ if (fn(e)) drained.push(e);
48
+ else kept.push(e);
49
+ }
50
+ this._events = kept;
51
+ return drained;
52
+ }
53
+
54
+ peek(filter) {
55
+ if (!filter) return [...this._events];
56
+ const fn = this._compileFilter(filter);
57
+ return this._events.filter(fn);
58
+ }
59
+
60
+ size() { return this._events.length; }
61
+ cap() { return this._cap; }
62
+ stats() {
63
+ return {
64
+ size: this._events.length,
65
+ cap: this._cap,
66
+ totalSeen: this._totalSeen,
67
+ totalDropped: this._totalDropped,
68
+ };
69
+ }
70
+
71
+ // Filter language (intentionally narrow — extend on demand):
72
+ // { event_type: "im.message.receive_v1" } — exact match on type
73
+ // { chat_id: "oc_zzz" } — extract from event payload
74
+ // { since_seconds: 60 } — only events received in last N sec
75
+ // { event_types: ["a", "b"] } — any of these types
76
+ // Multiple keys = AND.
77
+ _compileFilter(filter) {
78
+ return (e) => {
79
+ if (filter.event_type && e.event_type !== filter.event_type) return false;
80
+ if (filter.event_types && !filter.event_types.includes(e.event_type)) return false;
81
+ if (filter.chat_id) {
82
+ const chatId = this._extractChatId(e);
83
+ if (chatId !== filter.chat_id) return false;
84
+ }
85
+ if (filter.since_seconds) {
86
+ const cutoff = Math.floor(Date.now() / 1000) - filter.since_seconds;
87
+ if ((e._received_at || 0) < cutoff) return false;
88
+ }
89
+ return true;
90
+ };
91
+ }
92
+
93
+ _extractChatId(e) {
94
+ return e?.event?.message?.chat_id
95
+ || e?.event?.chat_id
96
+ || null;
97
+ }
98
+ }
99
+
100
+ module.exports = { EventBuffer, DEFAULT_CAP };
@@ -0,0 +1,5 @@
1
+ // src/events/index.js — barrel import for the events subsystem.
2
+ const { EventBuffer, DEFAULT_CAP } = require('./event-buffer');
3
+ const { createWSServer } = require('./ws-server');
4
+
5
+ module.exports = { EventBuffer, DEFAULT_CAP, createWSServer };
@@ -0,0 +1,86 @@
1
+ // src/events/ws-server.js — Feishu WebSocket subscription wrapper.
2
+ //
3
+ // Owns the WSClient + EventDispatcher pair. The MCP main() in server.js calls
4
+ // startWS() at boot if APP_ID + APP_SECRET are configured; failures are
5
+ // logged-and-tolerated (MCP keeps serving tool calls without realtime).
6
+ //
7
+ // What this owns:
8
+ // - createWSServer(opts) → { buffer, start(), stop() } factory
9
+ // - Default event registrations (im.message.receive_v1)
10
+ // - Reconnect via SDK's built-in handling (WSClient does this internally)
11
+ //
12
+ // What it does NOT own:
13
+ // - The buffer's persistence — it's in-memory only.
14
+ // - Multi-profile fan-out — single WS per process, per active profile.
15
+
16
+ const lark = require('@larksuiteoapi/node-sdk');
17
+ const { EventBuffer, DEFAULT_CAP } = require('./event-buffer');
18
+ const { stderrLogger } = require('../logger');
19
+
20
+ // Wrap an SDK event handler so the payload always lands in the buffer with
21
+ // a stable shape. The SDK passes the raw event payload — we add metadata
22
+ // for downstream filtering / display.
23
+ function _bufferEventHandler(buffer, eventType) {
24
+ return async (data) => {
25
+ const event = {
26
+ event_type: eventType,
27
+ event_id: data?.event_id || data?.header?.event_id || null,
28
+ _received_at: Math.floor(Date.now() / 1000),
29
+ header: data?.header || null,
30
+ event: data?.event || data,
31
+ };
32
+ buffer.push(event);
33
+ };
34
+ }
35
+
36
+ function createWSServer({ appId, appSecret, bufferCap = DEFAULT_CAP, registrations = ['im.message.receive_v1'] } = {}) {
37
+ if (!appId || !appSecret) throw new Error('createWSServer: appId + appSecret required');
38
+
39
+ const buffer = new EventBuffer({ cap: bufferCap });
40
+ let wsClient = null;
41
+ let started = false;
42
+ let stopped = false;
43
+
44
+ const dispatcher = new lark.EventDispatcher({
45
+ logger: stderrLogger,
46
+ loggerLevel: lark.LoggerLevel.warn,
47
+ });
48
+
49
+ // Register handlers for each requested event type.
50
+ const handlers = {};
51
+ for (const t of registrations) {
52
+ handlers[t] = _bufferEventHandler(buffer, t);
53
+ }
54
+ dispatcher.register(handlers);
55
+
56
+ async function start() {
57
+ if (started) return;
58
+ started = true;
59
+ wsClient = new lark.WSClient({
60
+ appId, appSecret,
61
+ logger: stderrLogger,
62
+ loggerLevel: lark.LoggerLevel.warn,
63
+ });
64
+ try {
65
+ await wsClient.start({ eventDispatcher: dispatcher });
66
+ console.error(`[feishu-user-plugin] WS connected — listening for: ${registrations.join(', ')}`);
67
+ } catch (e) {
68
+ console.error(`[feishu-user-plugin] WS start failed: ${e.message}. Continuing without realtime events.`);
69
+ started = false;
70
+ wsClient = null;
71
+ }
72
+ }
73
+
74
+ function stop() {
75
+ if (stopped) return;
76
+ stopped = true;
77
+ if (wsClient) {
78
+ try { wsClient.close(); } catch (e) { console.error(`[feishu-user-plugin] WS close error: ${e.message}`); }
79
+ wsClient = null;
80
+ }
81
+ }
82
+
83
+ return { buffer, start, stop, get isRunning() { return started && !stopped; } };
84
+ }
85
+
86
+ module.exports = { createWSServer };