@alexsun-top/opencode-chat-room 0.7.8 → 0.8.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 (183) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/LICENSE +21 -0
  3. package/README.md +77 -36
  4. package/README.zh-CN.md +82 -41
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +6905 -2764
  7. package/package.json +33 -3
  8. package/packages/chat-room-channeld/README.md +315 -0
  9. package/packages/chat-room-channeld/dist/feishu-adapter.js +1262 -0
  10. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  11. package/packages/chat-room-channeld/src/adapter.ts +509 -0
  12. package/packages/chat-room-channeld/src/cli.ts +124 -0
  13. package/packages/chat-room-channeld/src/config.ts +269 -0
  14. package/packages/chat-room-channeld/src/delivery.ts +163 -0
  15. package/packages/chat-room-channeld/src/feishu-adapter.ts +303 -0
  16. package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
  17. package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
  18. package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
  19. package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
  20. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
  21. package/packages/chat-room-channeld/src/framing.ts +128 -0
  22. package/packages/chat-room-channeld/src/host-helpers.ts +52 -0
  23. package/packages/chat-room-channeld/src/host.ts +627 -0
  24. package/packages/chat-room-channeld/src/inbound.ts +26 -0
  25. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  26. package/packages/chat-room-channeld/src/log.ts +26 -0
  27. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  28. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  29. package/packages/chat-room-channeld/src/published.ts +37 -0
  30. package/packages/chat-room-channeld/src/rules.ts +127 -0
  31. package/packages/chat-room-channeld/src/state.ts +502 -0
  32. package/packages/chat-room-channeld/src/stats.ts +209 -0
  33. package/plugin.ts +22 -5
  34. package/server/addressing-routes.ts +130 -0
  35. package/server/admin-state.ts +13 -13
  36. package/server/app.ts +95 -0
  37. package/server/assets/NOTICE.txt +3 -2
  38. package/server/assets/SHIKI-LICENSE +22 -0
  39. package/server/assets/base.css +24 -10
  40. package/server/assets/chat/announcements.js +70 -7
  41. package/server/assets/chat/doc-preview.js +187 -39
  42. package/server/assets/chat/events.js +3 -0
  43. package/server/assets/chat/files.js +46 -4
  44. package/server/assets/chat/forward.js +69 -0
  45. package/server/assets/chat/index.js +4 -0
  46. package/server/assets/chat/integration-editor.js +163 -0
  47. package/server/assets/chat/integration-values.js +124 -0
  48. package/server/assets/chat/integrations.js +498 -0
  49. package/server/assets/chat/locales/de.js +45 -4
  50. package/server/assets/chat/locales/es.js +45 -4
  51. package/server/assets/chat/locales/fr.js +45 -4
  52. package/server/assets/chat/locales/it.js +45 -4
  53. package/server/assets/chat/locales/ja.js +45 -4
  54. package/server/assets/chat/locales/ko.js +45 -4
  55. package/server/assets/chat/markdown-footnotes.js +115 -0
  56. package/server/assets/chat/markdown.js +46 -43
  57. package/server/assets/chat/messages.js +5 -5
  58. package/server/assets/chat/office-preview.js +69 -0
  59. package/server/assets/chat/palette.js +1 -1
  60. package/server/assets/chat/panels.js +36 -0
  61. package/server/assets/chat/recall.js +58 -7
  62. package/server/assets/chat/receipts.js +15 -3
  63. package/server/assets/chat/reminders.js +69 -8
  64. package/server/assets/chat/replies.js +7 -1
  65. package/server/assets/chat/resource-format.js +11 -0
  66. package/server/assets/chat/settings.js +30 -2
  67. package/server/assets/chat/shiki.js +87 -0
  68. package/server/assets/chat/side-pane.js +9 -3
  69. package/server/assets/chat/state.js +107 -11
  70. package/server/assets/chat/system-events.js +32 -0
  71. package/server/assets/chat/system-messages.js +23 -12
  72. package/server/assets/chat/task-row.js +0 -6
  73. package/server/assets/chat/tasks.js +121 -33
  74. package/server/assets/code-highlight.css +74 -62
  75. package/server/assets/conversation.css +126 -25
  76. package/server/assets/doc-preview.css +36 -3
  77. package/server/assets/files.css +5 -0
  78. package/server/assets/fluent-icons.svg +2 -0
  79. package/server/assets/monaco/LICENSE +21 -0
  80. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  81. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  82. package/server/assets/monaco/editor.worker.js +45 -0
  83. package/server/assets/monaco/integration-rules.css +1 -0
  84. package/server/assets/monaco/integration-rules.js +1297 -0
  85. package/server/assets/monaco/json.worker.js +77 -0
  86. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  87. package/server/assets/office/docx.bundle.js +33 -0
  88. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  89. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  90. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  91. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  92. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  93. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  94. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  95. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  96. package/server/assets/{HIGHLIGHT-LICENSE → office/licenses/zrender-LICENSE.txt} +2 -2
  97. package/server/assets/office/pptx.bundle.js +104 -0
  98. package/server/assets/office/xlsx.bundle.js +141 -0
  99. package/server/assets/recall.css +5 -4
  100. package/server/assets/responsive.css +52 -8
  101. package/server/assets/settings.css +73 -1
  102. package/server/assets/shiki.bundle.js +152 -0
  103. package/server/assets/tasks.css +57 -7
  104. package/server/channel-integration.ts +519 -0
  105. package/server/channel-settings.ts +77 -0
  106. package/server/channels.ts +557 -0
  107. package/server/chat-server.ts +33 -558
  108. package/server/chat.html +195 -22
  109. package/server/http-server.ts +3 -182
  110. package/server/resource-routes.ts +16 -16
  111. package/server/routes/inbox.ts +100 -0
  112. package/server/routes/pages.ts +83 -0
  113. package/server/routes/questions.ts +39 -0
  114. package/server/routes/room-actions.ts +162 -0
  115. package/server/routes/rooms.ts +160 -0
  116. package/server/startup.ts +84 -0
  117. package/server/sw.js +5 -2
  118. package/server/task-routes.ts +1 -1
  119. package/skills/chatroom/SKILL.md +1 -1
  120. package/src/center/center-client.ts +71 -1
  121. package/src/config/file-config.ts +29 -42
  122. package/src/platform/http-server.ts +182 -0
  123. package/src/protocol/addressing.ts +21 -0
  124. package/src/protocol/config.ts +58 -0
  125. package/src/protocol/room.ts +51 -0
  126. package/src/rooms/resources.ts +26 -16
  127. package/src/rooms/room-service.ts +2 -48
  128. package/src/rooms/storage.ts +329 -0
  129. package/src/rooms/tasks.ts +21 -5
  130. package/src/runtime/v2-plugin.ts +8 -2
  131. package/src/runtime/watch.ts +4 -3
  132. package/src/state/pg-database.ts +183 -0
  133. package/src/state/pg-migrate.ts +175 -0
  134. package/src/state/pg-sql.mjs +175 -0
  135. package/src/state/pg-worker.mjs +148 -0
  136. package/src/state/sqlite-announcements.ts +25 -0
  137. package/src/state/sqlite-database.ts +121 -0
  138. package/src/state/sqlite-legacy.ts +90 -0
  139. package/src/state/sqlite-members.ts +155 -0
  140. package/src/state/sqlite-messages.ts +288 -0
  141. package/src/state/sqlite-resources.ts +39 -0
  142. package/src/state/sqlite-rooms.ts +87 -0
  143. package/src/state/sqlite-schema.ts +80 -0
  144. package/src/state/sqlite-state-store.ts +33 -0
  145. package/src/state/sqlite-state.ts +15 -866
  146. package/src/state/sqlite-tasks.ts +65 -0
  147. package/src/state/sqlite-transaction.ts +13 -0
  148. package/src/state/sqlite.ts +21 -1
  149. package/src/state/store.ts +13 -3
  150. package/src/tui/app.mjs +32 -19
  151. package/src/tui/config.mjs +12 -4
  152. package/src/tui/http.mjs +16 -2
  153. package/src/tui/i18n.mjs +38 -0
  154. package/src/tui/info-app.mjs +50 -51
  155. package/src/tui/info-content.mjs +79 -44
  156. package/src/tui/join-app.mjs +9 -9
  157. package/src/tui/locales/en.mjs +349 -0
  158. package/src/tui/locales/zh-CN.mjs +349 -0
  159. package/src/tui/main.mjs +85 -37
  160. package/src/tui/markdown.mjs +3 -2
  161. package/src/tui/mentions.mjs +3 -1
  162. package/src/tui/message-app.mjs +22 -21
  163. package/src/tui/message-view.mjs +2 -1
  164. package/src/tui/palette-app.mjs +9 -8
  165. package/src/tui/palette.mjs +30 -24
  166. package/src/tui/prefs.mjs +92 -0
  167. package/src/tui/reminder-app.mjs +18 -17
  168. package/src/tui/room-settings-app.mjs +30 -28
  169. package/src/tui/settings-app.mjs +153 -0
  170. package/src/tui/ui-content.mjs +65 -86
  171. package/src/tui/ui-help.mjs +73 -0
  172. package/src/tui/ui-overlay-view.mjs +23 -7
  173. package/src/tui/ui-suggest.mjs +6 -5
  174. package/src/tui/ui-theme.mjs +37 -33
  175. package/src/tui/ui-view.mjs +22 -7
  176. package/src/tui/ui.mjs +15 -3
  177. package/src/web/editor.worker.ts +1 -0
  178. package/src/web/integration-rules-editor.ts +439 -0
  179. package/src/web/integration-rules.ts +22 -0
  180. package/src/web/integration-schema.ts +228 -0
  181. package/src/web/json.worker.ts +1 -0
  182. package/src/web/office-viewer.ts +221 -0
  183. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -0,0 +1,355 @@
1
+ import { decodeFrame, encodeFrame, headerValue, jsonPayload, type WsFrame } from "./feishu-ws-frames.ts";
2
+
3
+ const DEFAULT_PING_MS = 120_000;
4
+ const DEFAULT_RECONNECT_MS = 120_000;
5
+ const DEFAULT_NONCE_MS = 30_000;
6
+ const FRAGMENT_TTL_MS = 10_000;
7
+ const CONNECT_TIMEOUT_MS = 10_000;
8
+
9
+ export interface LiveSocket {
10
+ binaryType: string;
11
+ readyState: number;
12
+ send(data: Uint8Array): void;
13
+ close(): void;
14
+ addEventListener(type: string, listener: (event: any) => void): void;
15
+ }
16
+
17
+ type SocketCtor = new (url: string) => LiveSocket;
18
+
19
+ interface Discovered {
20
+ url: string;
21
+ serviceId: number;
22
+ pingMs: number;
23
+ reconnectMs: number;
24
+ reconnectNonceMs: number;
25
+ }
26
+
27
+ interface Fragment {
28
+ parts: Array<Uint8Array | undefined>;
29
+ received: number;
30
+ timer: ReturnType<typeof setTimeout>;
31
+ }
32
+
33
+ export interface LiveConnectionOptions {
34
+ appId: string;
35
+ appSecret: string;
36
+ baseUrl: string;
37
+ timeoutMs: number;
38
+ /** Test seam: defaults to the platform WebSocket constructor. */
39
+ socketFactory?: (url: string) => LiveSocket;
40
+ /** Complete JSON event payloads; return false to make Feishu retry. */
41
+ onEvent(payload: string): Promise<boolean>;
42
+ log(message: string): void;
43
+ }
44
+
45
+ function isRecord(value: unknown): value is Record<string, unknown> {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+
49
+ async function discovery(options: LiveConnectionOptions): Promise<Discovered> {
50
+ const controller = new AbortController();
51
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
52
+ let raw: { status: number; body: unknown };
53
+ try {
54
+ const response = await fetch(`${options.baseUrl}/callback/ws/endpoint`, {
55
+ method: "POST",
56
+ headers: { "Content-Type": "application/json; charset=utf-8", locale: "zh" },
57
+ body: JSON.stringify({ AppID: options.appId, AppSecret: options.appSecret }),
58
+ signal: controller.signal,
59
+ });
60
+ const text = await response.text();
61
+ let body: unknown;
62
+ try {
63
+ body = JSON.parse(text);
64
+ } catch {
65
+ body = undefined;
66
+ }
67
+ raw = { status: response.status, body };
68
+ } catch (error) {
69
+ const code = (error as { cause?: { code?: unknown } } | null)?.cause?.code;
70
+ const detail = typeof code === "string" ? ` (${code})` : "";
71
+ throw new Error(`feishu long connection discovery failed${detail}`);
72
+ } finally {
73
+ clearTimeout(timer);
74
+ }
75
+ if (!isRecord(raw.body) || typeof raw.body.code !== "number") {
76
+ throw new Error(`feishu long connection discovery failed: http ${raw.status}`);
77
+ }
78
+ if (raw.body.code !== 0) {
79
+ const msg = typeof raw.body.msg === "string" && raw.body.msg ? `: ${raw.body.msg}` : "";
80
+ throw new Error(`feishu long connection unavailable: code ${raw.body.code}${msg}`);
81
+ }
82
+ const data = isRecord(raw.body.data) ? raw.body.data : undefined;
83
+ const url = data && typeof data.URL === "string" ? data.URL : "";
84
+ if (!url.startsWith("ws://") && !url.startsWith("wss://")) {
85
+ throw new Error("feishu long connection discovery returned no WebSocket URL");
86
+ }
87
+ const parsed = new URL(url);
88
+ const serviceId = Number(parsed.searchParams.get("service_id"));
89
+ if (!Number.isInteger(serviceId)) {
90
+ throw new Error("feishu long connection URL is missing service_id");
91
+ }
92
+ const config = data && isRecord(data.ClientConfig) ? data.ClientConfig : {};
93
+ const seconds = (value: unknown, fallback: number): number =>
94
+ typeof value === "number" && Number.isFinite(value) && value > 0 ? value * 1000 : fallback;
95
+ return {
96
+ url,
97
+ serviceId,
98
+ pingMs: seconds(config.PingInterval, DEFAULT_PING_MS),
99
+ reconnectMs: seconds(config.ReconnectInterval, DEFAULT_RECONNECT_MS),
100
+ reconnectNonceMs: seconds(config.ReconnectNonce, DEFAULT_NONCE_MS),
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Feishu event long connection: endpoint discovery, pbbp2 frames, ping/pong,
106
+ * fragment reassembly, acknowledgement after the host commits, and reconnect.
107
+ */
108
+ export class FeishuLiveConnection {
109
+ readonly #options: LiveConnectionOptions;
110
+ readonly #fragments = new Map<string, Fragment>();
111
+ #socket?: LiveSocket;
112
+ #discovered?: Discovered;
113
+ #pingTimer?: ReturnType<typeof setTimeout>;
114
+ #reconnectTimer?: ReturnType<typeof setTimeout>;
115
+ #stopped = false;
116
+ #connecting = false;
117
+ #attempts = 0;
118
+
119
+ constructor(options: LiveConnectionOptions) {
120
+ this.#options = options;
121
+ }
122
+
123
+ async start(): Promise<void> {
124
+ this.#stopped = false;
125
+ this.#discovered = await discovery(this.#options);
126
+ await this.#connect();
127
+ this.#options.log(`inbound long connection ready service=${this.#discovered.serviceId}`);
128
+ }
129
+
130
+ async stop(): Promise<void> {
131
+ this.#stopped = true;
132
+ if (this.#pingTimer) clearTimeout(this.#pingTimer);
133
+ if (this.#reconnectTimer) clearTimeout(this.#reconnectTimer);
134
+ this.#pingTimer = undefined;
135
+ this.#reconnectTimer = undefined;
136
+ for (const fragment of this.#fragments.values()) clearTimeout(fragment.timer);
137
+ this.#fragments.clear();
138
+ const socket = this.#socket;
139
+ this.#socket = undefined;
140
+ if (socket) {
141
+ try {
142
+ socket.close();
143
+ } catch {
144
+ // Socket may already be closed.
145
+ }
146
+ }
147
+ }
148
+
149
+ #connect(): Promise<void> {
150
+ const factory = this.#options.socketFactory;
151
+ const Ctor = factory
152
+ ? undefined
153
+ : (globalThis as { WebSocket?: SocketCtor }).WebSocket;
154
+ if (!factory && !Ctor) {
155
+ return Promise.reject(new Error("feishu long connection requires a WebSocket client"));
156
+ }
157
+ const discovered = this.#discovered;
158
+ if (!discovered) return Promise.reject(new Error("feishu long connection is not discovered"));
159
+ const create = factory ?? ((url: string) => new Ctor!(url));
160
+ return new Promise((resolve, reject) => {
161
+ const socket = create(discovered.url);
162
+ socket.binaryType = "arraybuffer";
163
+ let settled = false;
164
+ const timer = setTimeout(() => {
165
+ if (settled) return;
166
+ settled = true;
167
+ try {
168
+ socket.close();
169
+ } catch {
170
+ // Ignore close failures on a dead handshake.
171
+ }
172
+ reject(new Error("feishu long connection timed out"));
173
+ }, CONNECT_TIMEOUT_MS);
174
+ socket.addEventListener("open", () => {
175
+ if (settled) return;
176
+ settled = true;
177
+ clearTimeout(timer);
178
+ if (this.#stopped) {
179
+ try {
180
+ socket.close();
181
+ } catch {
182
+ // Ignore close failures after stop.
183
+ }
184
+ reject(new Error("feishu long connection stopped"));
185
+ return;
186
+ }
187
+ this.#attempts = 0;
188
+ this.#socket = socket;
189
+ this.#attach(socket);
190
+ this.#ping();
191
+ resolve();
192
+ });
193
+ socket.addEventListener("error", () => {
194
+ if (settled) return;
195
+ settled = true;
196
+ clearTimeout(timer);
197
+ reject(new Error("feishu long connection failed"));
198
+ });
199
+ socket.addEventListener("close", () => {
200
+ if (settled) return;
201
+ settled = true;
202
+ clearTimeout(timer);
203
+ reject(new Error("feishu long connection closed during handshake"));
204
+ });
205
+ });
206
+ }
207
+
208
+ #attach(socket: LiveSocket): void {
209
+ socket.addEventListener("message", (event: { data?: unknown }) => {
210
+ void this.#onSocketMessage(event.data).catch((error: unknown) => {
211
+ this.#options.log(`inbound frame failed: ${error instanceof Error ? error.message : String(error)}`);
212
+ });
213
+ });
214
+ socket.addEventListener("error", () => {
215
+ this.#options.log("inbound socket error");
216
+ });
217
+ socket.addEventListener("close", () => {
218
+ // A late close from a socket replaced by a reconnect must not clear the
219
+ // current connection's ping timer or schedule a duplicate reconnect.
220
+ if (this.#socket !== socket) return;
221
+ this.#socket = undefined;
222
+ if (this.#pingTimer) clearTimeout(this.#pingTimer);
223
+ this.#pingTimer = undefined;
224
+ this.#scheduleReconnect();
225
+ });
226
+ }
227
+
228
+ async #onSocketMessage(data: unknown): Promise<void> {
229
+ let bytes: Uint8Array;
230
+ if (data instanceof ArrayBuffer) bytes = new Uint8Array(data);
231
+ else if (ArrayBuffer.isView(data)) bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
232
+ else if (typeof Blob !== "undefined" && data instanceof Blob) bytes = new Uint8Array(await data.arrayBuffer());
233
+ else return;
234
+
235
+ const frame = decodeFrame(bytes);
236
+ if (frame.method === 0) {
237
+ this.#onControl(frame);
238
+ return;
239
+ }
240
+ if (frame.method !== 1) return;
241
+ const type = headerValue(frame, "type");
242
+ if (type !== "event") return;
243
+ const payload = this.#assemble(frame);
244
+ if (!payload) return;
245
+ const text = new TextDecoder().decode(payload);
246
+ let ok = false;
247
+ try {
248
+ ok = await this.#options.onEvent(text);
249
+ } catch {
250
+ ok = false;
251
+ }
252
+ this.#ack(frame, ok ? 200 : 500);
253
+ }
254
+
255
+ #onControl(frame: WsFrame): void {
256
+ if (headerValue(frame, "type") !== "pong" || !frame.payload) return;
257
+ try {
258
+ const pong = JSON.parse(new TextDecoder().decode(frame.payload)) as Record<string, unknown>;
259
+ const next = this.#discovered;
260
+ if (!next) return;
261
+ if (typeof pong.PingInterval === "number" && pong.PingInterval > 0) next.pingMs = pong.PingInterval * 1000;
262
+ if (typeof pong.ReconnectInterval === "number" && pong.ReconnectInterval > 0) {
263
+ next.reconnectMs = pong.ReconnectInterval * 1000;
264
+ }
265
+ if (typeof pong.ReconnectNonce === "number" && pong.ReconnectNonce > 0) {
266
+ next.reconnectNonceMs = pong.ReconnectNonce * 1000;
267
+ }
268
+ } catch {
269
+ // A malformed pong only means the old intervals stay in effect.
270
+ }
271
+ }
272
+
273
+ #assemble(frame: WsFrame): Uint8Array | undefined {
274
+ const id = headerValue(frame, "message_id");
275
+ const total = Number(headerValue(frame, "sum") ?? "1");
276
+ const seq = Number(headerValue(frame, "seq") ?? "0");
277
+ if (!id || !frame.payload || !Number.isInteger(total) || total <= 1) return frame.payload;
278
+ if (!Number.isInteger(seq) || seq < 0 || seq >= total) return undefined;
279
+ const current = this.#fragments.get(id) ?? {
280
+ parts: Array.from({ length: total }),
281
+ received: 0,
282
+ timer: setTimeout(() => this.#fragments.delete(id), FRAGMENT_TTL_MS),
283
+ };
284
+ if (current.parts.length !== total) return undefined;
285
+ if (!current.parts[seq]) {
286
+ current.parts[seq] = frame.payload;
287
+ current.received += 1;
288
+ }
289
+ this.#fragments.set(id, current);
290
+ if (current.received < total) return undefined;
291
+ clearTimeout(current.timer);
292
+ this.#fragments.delete(id);
293
+ return Uint8Array.from(current.parts.flatMap((part) => [...(part ?? [])]));
294
+ }
295
+
296
+ #ack(frame: WsFrame, code: number): void {
297
+ const socket = this.#socket;
298
+ if (!socket) return;
299
+ const ack: WsFrame = {
300
+ ...frame,
301
+ headers: [...(frame.headers ?? []), { key: "biz_rt", value: "0" }],
302
+ payload: jsonPayload({ code }),
303
+ };
304
+ try {
305
+ socket.send(encodeFrame(ack));
306
+ } catch {
307
+ this.#options.log("inbound ack failed");
308
+ }
309
+ }
310
+
311
+ #ping(): void {
312
+ if (this.#stopped || !this.#discovered) return;
313
+ const socket = this.#socket;
314
+ if (!socket) return;
315
+ try {
316
+ socket.send(encodeFrame({
317
+ SeqID: 0,
318
+ LogID: 0,
319
+ service: this.#discovered.serviceId,
320
+ method: 0,
321
+ headers: [{ key: "type", value: "ping" }],
322
+ }));
323
+ } catch {
324
+ this.#options.log("inbound ping failed");
325
+ }
326
+ this.#pingTimer = setTimeout(() => this.#ping(), this.#discovered.pingMs);
327
+ }
328
+
329
+ #scheduleReconnect(): void {
330
+ if (this.#stopped || this.#connecting) return;
331
+ this.#connecting = true;
332
+ const next = this.#discovered;
333
+ const delay = (next?.reconnectNonceMs ?? DEFAULT_NONCE_MS) * Math.random()
334
+ + (next?.reconnectMs ?? DEFAULT_RECONNECT_MS);
335
+ this.#options.log(`inbound reconnecting in ${Math.round(delay)}ms`);
336
+ this.#reconnectTimer = setTimeout(() => {
337
+ void this.#reconnect();
338
+ }, delay);
339
+ }
340
+
341
+ async #reconnect(): Promise<void> {
342
+ this.#connecting = false;
343
+ if (this.#stopped) return;
344
+ this.#attempts += 1;
345
+ try {
346
+ this.#discovered = await discovery(this.#options);
347
+ if (this.#stopped) return;
348
+ await this.#connect();
349
+ this.#options.log(`inbound reconnected attempt=${this.#attempts}`);
350
+ } catch (error) {
351
+ this.#options.log(`inbound reconnect failed: ${error instanceof Error ? error.message : String(error)}`);
352
+ this.#scheduleReconnect();
353
+ }
354
+ }
355
+ }
@@ -0,0 +1,342 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { CardVersion } from "./feishu-card.ts";
3
+ import { buildCard } from "./feishu-card.ts";
4
+ import type { Endpoint } from "./protocol.ts";
5
+
6
+ const DEFAULT_BASE_URL = "https://open.feishu.cn";
7
+ const DEFAULT_TIMEOUT_MS = 10_000;
8
+ const DEFAULT_RATE_LIMIT_MS = 1000;
9
+ const TOKEN_REFRESH_MARGIN_MS = 30 * 60_000;
10
+ const FALLBACK_TOKEN_TTL_SECONDS = 7200;
11
+ const TOKEN_INVALID_CODE = 99991663;
12
+ const RATE_LIMIT_CODES = new Set([230020, 99991400]);
13
+
14
+ export type SendState = "sent" | "retryable" | "rate_limited" | "permanent" | "unsupported" | "unknown";
15
+
16
+ export interface SendReceipt {
17
+ state: SendState;
18
+ providerMessage?: { endpoint: Endpoint; nativeMessageId: string };
19
+ retryAfterMs?: number;
20
+ detail?: string;
21
+ }
22
+
23
+ export interface FeishuConfig {
24
+ appId: string;
25
+ appSecret: string;
26
+ baseUrl: string;
27
+ timeoutMs: number;
28
+ cardVersion: CardVersion;
29
+ inbound: boolean;
30
+ inboundChats: ReadonlySet<string>;
31
+ }
32
+
33
+ interface SendTarget {
34
+ roomId?: unknown;
35
+ room?: unknown;
36
+ }
37
+
38
+ export interface SendParams {
39
+ idempotencyKey?: unknown;
40
+ target?: SendTarget;
41
+ payload?: unknown;
42
+ }
43
+
44
+ interface RawResponse {
45
+ status: number;
46
+ headers: Headers;
47
+ body?: unknown;
48
+ }
49
+
50
+ class FeishuTimeoutError extends Error {
51
+ constructor() {
52
+ super("feishu request timed out");
53
+ this.name = "FeishuTimeoutError";
54
+ }
55
+ }
56
+
57
+ export class FeishuApiError extends Error {
58
+ readonly code: number;
59
+ readonly msg: string;
60
+ readonly scope: "token" | "send";
61
+
62
+ constructor(code: number, msg: string, scope: "token" | "send") {
63
+ super(`feishu ${scope} code ${code}: ${msg}`);
64
+ this.name = "FeishuApiError";
65
+ this.code = code;
66
+ this.msg = msg;
67
+ this.scope = scope;
68
+ }
69
+ }
70
+
71
+ function logLine(accountId: string, message: string): void {
72
+ console.error(`feishu adapter ${accountId}: ${message}`);
73
+ }
74
+
75
+ /** Stable 32-hex SHA-256 prefix used as the Feishu idempotent message uuid. */
76
+ export function deterministicUuid(idempotencyKey: string): string {
77
+ return createHash("sha256").update(idempotencyKey).digest("hex").slice(0, 32);
78
+ }
79
+
80
+ function isRecord(value: unknown): value is Record<string, unknown> {
81
+ return typeof value === "object" && value !== null && !Array.isArray(value);
82
+ }
83
+
84
+ async function fetchJson(url: string, init: RequestInit, timeoutMs: number): Promise<RawResponse> {
85
+ const controller = new AbortController();
86
+ let timedOut = false;
87
+ const timer = setTimeout(() => {
88
+ timedOut = true;
89
+ controller.abort();
90
+ }, timeoutMs);
91
+ try {
92
+ const response = await fetch(url, { ...init, signal: controller.signal });
93
+ const text = await response.text();
94
+ let body: unknown;
95
+ if (text.trim()) {
96
+ try {
97
+ body = JSON.parse(text);
98
+ } catch {
99
+ body = undefined;
100
+ }
101
+ }
102
+ return { status: response.status, headers: response.headers, body };
103
+ } catch (error) {
104
+ // A timeout means the request may already be in Feishu's hands.
105
+ if (timedOut) throw new FeishuTimeoutError();
106
+ throw error;
107
+ } finally {
108
+ clearTimeout(timer);
109
+ }
110
+ }
111
+
112
+ async function requestToken(config: FeishuConfig): Promise<{ token: string; expiresAt: number }> {
113
+ const raw = await fetchJson(
114
+ `${config.baseUrl}/open-apis/auth/v3/tenant_access_token/internal`,
115
+ {
116
+ method: "POST",
117
+ headers: { "Content-Type": "application/json; charset=utf-8" },
118
+ body: JSON.stringify({ app_id: config.appId, app_secret: config.appSecret }),
119
+ },
120
+ config.timeoutMs,
121
+ );
122
+ const body = raw.body;
123
+ if (!isRecord(body) || typeof body.code !== "number") {
124
+ throw new Error("feishu token response was malformed");
125
+ }
126
+ if (body.code !== 0) {
127
+ throw new FeishuApiError(body.code, typeof body.msg === "string" ? body.msg : "", "token");
128
+ }
129
+ if (typeof body.tenant_access_token !== "string" || body.tenant_access_token.length === 0) {
130
+ throw new Error("feishu token response was malformed");
131
+ }
132
+ const expire =
133
+ typeof body.expire === "number" && body.expire > 0 ? body.expire : FALLBACK_TOKEN_TTL_SECONDS;
134
+ return { token: body.tenant_access_token, expiresAt: Date.now() + expire * 1000 };
135
+ }
136
+
137
+ export async function ensureToken(config: FeishuConfig, state: TokenState, force = false): Promise<string> {
138
+ if (!force && state.token && state.tokenExpiresAt - Date.now() > TOKEN_REFRESH_MARGIN_MS) {
139
+ return state.token;
140
+ }
141
+ const fresh = await requestToken(config);
142
+ state.token = fresh.token;
143
+ state.tokenExpiresAt = fresh.expiresAt;
144
+ logLine(state.accountId, "tenant token acquired");
145
+ return fresh.token;
146
+ }
147
+
148
+ function errorCode(error: unknown): string | undefined {
149
+ const direct = (error as { code?: unknown } | null)?.code;
150
+ if (typeof direct === "string") return direct;
151
+ const cause = (error as { cause?: { code?: unknown } } | null)?.cause?.code;
152
+ return typeof cause === "string" ? cause : undefined;
153
+ }
154
+
155
+ function networkFailure(error: unknown): SendReceipt {
156
+ const code = errorCode(error);
157
+ return { state: "retryable", detail: code ? `feishu network error (${code})` : "feishu network error" };
158
+ }
159
+
160
+ function failureReceipt(error: unknown): SendReceipt {
161
+ if (error instanceof FeishuTimeoutError) {
162
+ return { state: "unknown", detail: error.message };
163
+ }
164
+ if (error instanceof FeishuApiError) {
165
+ if (RATE_LIMIT_CODES.has(error.code)) {
166
+ return { state: "rate_limited", retryAfterMs: DEFAULT_RATE_LIMIT_MS, detail: `feishu code ${error.code}` };
167
+ }
168
+ return { state: "permanent", detail: error.message };
169
+ }
170
+ if (error instanceof Error && error.message === "feishu token response was malformed") {
171
+ return { state: "permanent", detail: error.message };
172
+ }
173
+ return networkFailure(error);
174
+ }
175
+
176
+ function parseRetryAfter(value: string | null): number {
177
+ if (!value) return DEFAULT_RATE_LIMIT_MS;
178
+ const seconds = Number(value.trim());
179
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
180
+ const date = Date.parse(value);
181
+ if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
182
+ return DEFAULT_RATE_LIMIT_MS;
183
+ }
184
+
185
+ function apiCode(raw: RawResponse): number | undefined {
186
+ return isRecord(raw.body) && typeof raw.body.code === "number" ? raw.body.code : undefined;
187
+ }
188
+
189
+ /** A Feishu business error, as opposed to an HTTP transport failure. */
190
+ function isApiFailure(raw: RawResponse): boolean {
191
+ const code = apiCode(raw);
192
+ return raw.status !== 429 && raw.status < 500 && code !== undefined && code !== 0;
193
+ }
194
+
195
+ const CLIENT_ERROR_STATUSES = new Set([400, 401, 403, 404]);
196
+
197
+ function apiResponseDetail(body: unknown, status: number): string {
198
+ const code = isRecord(body) && typeof body.code === "number" ? body.code : undefined;
199
+ const msg = isRecord(body) && typeof body.msg === "string" ? body.msg : "";
200
+ if (code !== undefined && code !== 0) return msg ? `feishu code ${code}: ${msg}` : `feishu code ${code}`;
201
+ return `feishu http ${status}`;
202
+ }
203
+
204
+ function mapSendResponse(raw: RawResponse, endpoint: Endpoint): SendReceipt {
205
+ if (raw.status === 429) {
206
+ return { state: "rate_limited", retryAfterMs: parseRetryAfter(raw.headers.get("retry-after")) };
207
+ }
208
+ if (raw.status >= 500) {
209
+ return { state: "retryable", detail: `feishu http ${raw.status}` };
210
+ }
211
+ const body = raw.body;
212
+ const code = apiCode(raw);
213
+ if (code !== undefined && RATE_LIMIT_CODES.has(code)) {
214
+ return {
215
+ state: "rate_limited",
216
+ retryAfterMs: parseRetryAfter(raw.headers.get("retry-after")),
217
+ detail: `feishu code ${code}`,
218
+ };
219
+ }
220
+ if (CLIENT_ERROR_STATUSES.has(raw.status)) {
221
+ return { state: "permanent", detail: apiResponseDetail(body, raw.status) };
222
+ }
223
+ if (!isRecord(body) || typeof body.code !== "number") {
224
+ return { state: "unknown", detail: "feishu response was malformed" };
225
+ }
226
+ if (body.code === 0) {
227
+ const data = isRecord(body.data) ? body.data : undefined;
228
+ const messageId = data && typeof data.message_id === "string" ? data.message_id : undefined;
229
+ if (raw.status >= 200 && raw.status < 300 && messageId) {
230
+ return { state: "sent", providerMessage: { endpoint, nativeMessageId: messageId } };
231
+ }
232
+ return { state: "unknown", detail: "feishu response was malformed" };
233
+ }
234
+ const msg = typeof body.msg === "string" ? body.msg : "";
235
+ return { state: "permanent", detail: msg ? `feishu code ${body.code}: ${msg}` : `feishu code ${body.code}` };
236
+ }
237
+
238
+ /** A Feishu parent reference is usable only for this account's own chat. */
239
+ function replyParentId(payload: unknown, accountId: string): string | undefined {
240
+ if (!isRecord(payload) || !isRecord(payload.parent)) return undefined;
241
+ const parent = payload.parent;
242
+ if (!isRecord(parent.endpoint)) return undefined;
243
+ if (parent.endpoint.platform !== "feishu") return undefined;
244
+ if (typeof parent.endpoint.accountId === "string" && parent.endpoint.accountId !== accountId) {
245
+ return undefined;
246
+ }
247
+ return typeof parent.nativeMessageId === "string" && parent.nativeMessageId
248
+ ? parent.nativeMessageId
249
+ : undefined;
250
+ }
251
+
252
+ function postMessage(
253
+ config: FeishuConfig,
254
+ token: string,
255
+ body: string,
256
+ replyTo?: string,
257
+ ): Promise<RawResponse> {
258
+ const path = replyTo
259
+ ? `/open-apis/im/v1/messages/${encodeURIComponent(replyTo)}/reply`
260
+ : "/open-apis/im/v1/messages?receive_id_type=chat_id";
261
+ return fetchJson(
262
+ `${config.baseUrl}${path}`,
263
+ {
264
+ method: "POST",
265
+ headers: {
266
+ Authorization: `Bearer ${token}`,
267
+ "Content-Type": "application/json; charset=utf-8",
268
+ },
269
+ body,
270
+ },
271
+ config.timeoutMs,
272
+ );
273
+ }
274
+
275
+ export async function sendMessage(
276
+ config: FeishuConfig,
277
+ state: TokenState,
278
+ params: SendParams,
279
+ ): Promise<SendReceipt> {
280
+ const target = params.target;
281
+ const chatId = target && typeof target.roomId === "string" && target.roomId
282
+ ? target.roomId
283
+ : target && typeof target.room === "string"
284
+ ? target.room
285
+ : undefined;
286
+ if (!chatId) return { state: "permanent", detail: "send target requires a room" };
287
+ const text = isRecord(params.payload) && typeof params.payload.text === "string"
288
+ ? params.payload.text
289
+ : undefined;
290
+ if (text === undefined) return { state: "permanent", detail: "send payload.text must be a string" };
291
+ if (typeof params.idempotencyKey !== "string" || params.idempotencyKey.length === 0) {
292
+ return { state: "permanent", detail: "send requires an idempotency key" };
293
+ }
294
+
295
+ const endpoint = target as unknown as Endpoint;
296
+ // Card 2.0 renders block Markdown; card 1.0 keeps the 0.8.0 lark_md payload.
297
+ const card = buildCard(config.cardVersion, text);
298
+ const parentId = replyParentId(params.payload, state.accountId);
299
+ const message = {
300
+ msg_type: "interactive",
301
+ content: JSON.stringify(card),
302
+ uuid: deterministicUuid(params.idempotencyKey),
303
+ };
304
+ const body = JSON.stringify(parentId ? message : { receive_id: chatId, ...message });
305
+
306
+ let token: string;
307
+ let raw: RawResponse;
308
+ try {
309
+ token = await ensureToken(config, state);
310
+ raw = await postMessage(config, token, body, parentId);
311
+ } catch (error) {
312
+ return failureReceipt(error);
313
+ }
314
+
315
+ if (raw.status !== 429 && raw.status < 500 && apiCode(raw) === TOKEN_INVALID_CODE) {
316
+ try {
317
+ token = await ensureToken(config, state, true);
318
+ raw = await postMessage(config, token, body, parentId);
319
+ } catch (error) {
320
+ return failureReceipt(error);
321
+ }
322
+ // A token that is still rejected after a forced refresh will not fix itself.
323
+ if (isApiFailure(raw) && apiCode(raw) === TOKEN_INVALID_CODE) {
324
+ return { state: "permanent", detail: `feishu code ${TOKEN_INVALID_CODE}` };
325
+ }
326
+ }
327
+ return mapSendResponse(raw, endpoint);
328
+ }
329
+
330
+ export function startupFailureDetail(error: unknown): string {
331
+ if (error instanceof FeishuTimeoutError) return error.message;
332
+ if (error instanceof FeishuApiError) return error.message;
333
+ if (error instanceof Error && error.message === "feishu token response was malformed") return error.message;
334
+ const code = errorCode(error);
335
+ return code ? `feishu token request failed (${code})` : "feishu token request failed";
336
+ }
337
+
338
+ export interface TokenState {
339
+ accountId: string;
340
+ token?: string;
341
+ tokenExpiresAt: number;
342
+ }