@alexsun-top/opencode-chat-room 0.8.1 → 0.8.3

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 (125) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +1008 -274
  5. package/package.json +10 -7
  6. package/packages/chat-room-channeld/README.md +42 -15
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +150 -7
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +41 -11
  11. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  12. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  13. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  14. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  15. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  16. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  17. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  18. package/packages/chat-room-channeld/src/protocol.ts +53 -1
  19. package/packages/chat-room-channeld/src/rules.ts +7 -2
  20. package/packages/chat-room-channeld/src/state.ts +73 -97
  21. package/packages/chat-room-channeld/src/stats.ts +140 -109
  22. package/plugin.ts +1 -1
  23. package/server/assets/base.css +11 -3
  24. package/server/assets/chat/admin-badge.js +32 -30
  25. package/server/assets/chat/admin.js +198 -163
  26. package/server/assets/chat/announcements.js +295 -210
  27. package/server/assets/chat/attachment-store.js +106 -75
  28. package/server/assets/chat/attachments.js +686 -441
  29. package/server/assets/chat/chat-background.js +206 -0
  30. package/server/assets/chat/clipboard.js +44 -25
  31. package/server/assets/chat/confirm-dialog.js +36 -34
  32. package/server/assets/chat/copy-action.js +40 -40
  33. package/server/assets/chat/create-room-dialog.js +50 -48
  34. package/server/assets/chat/diagram-viewer.js +293 -228
  35. package/server/assets/chat/doc-preview.js +510 -388
  36. package/server/assets/chat/editor.js +423 -335
  37. package/server/assets/chat/events.js +637 -502
  38. package/server/assets/chat/files.js +476 -426
  39. package/server/assets/chat/history-loader.js +79 -73
  40. package/server/assets/chat/icons.js +9 -11
  41. package/server/assets/chat/image-zoom.js +239 -169
  42. package/server/assets/chat/index.js +6 -5
  43. package/server/assets/chat/install-prompt.js +86 -66
  44. package/server/assets/chat/integration-account-schema.js +101 -0
  45. package/server/assets/chat/integration-editor.js +162 -153
  46. package/server/assets/chat/integration-values.js +109 -100
  47. package/server/assets/chat/integrations.js +696 -479
  48. package/server/assets/chat/join-requests.js +408 -358
  49. package/server/assets/chat/locales/de.js +193 -194
  50. package/server/assets/chat/locales/es.js +193 -194
  51. package/server/assets/chat/locales/fr.js +193 -194
  52. package/server/assets/chat/locales/index.js +1 -2
  53. package/server/assets/chat/locales/it.js +193 -194
  54. package/server/assets/chat/locales/ja.js +193 -193
  55. package/server/assets/chat/locales/ko.js +193 -193
  56. package/server/assets/chat/markdown-footnotes.js +134 -102
  57. package/server/assets/chat/markdown.js +553 -386
  58. package/server/assets/chat/members.js +236 -197
  59. package/server/assets/chat/mentions.js +157 -133
  60. package/server/assets/chat/message-cache.js +40 -33
  61. package/server/assets/chat/message-polling.js +280 -227
  62. package/server/assets/chat/message-window.js +74 -55
  63. package/server/assets/chat/messages.js +552 -479
  64. package/server/assets/chat/office-preview.js +46 -45
  65. package/server/assets/chat/palette.js +450 -412
  66. package/server/assets/chat/panels.js +94 -58
  67. package/server/assets/chat/pwa.js +144 -73
  68. package/server/assets/chat/questions.js +372 -302
  69. package/server/assets/chat/recall.js +320 -273
  70. package/server/assets/chat/receipts.js +149 -122
  71. package/server/assets/chat/reminders.js +331 -216
  72. package/server/assets/chat/replies.js +165 -136
  73. package/server/assets/chat/resource-format.js +59 -62
  74. package/server/assets/chat/room-list.js +58 -55
  75. package/server/assets/chat/room-watcher.js +72 -50
  76. package/server/assets/chat/rooms.js +623 -505
  77. package/server/assets/chat/search.js +136 -114
  78. package/server/assets/chat/settings.js +229 -140
  79. package/server/assets/chat/shiki.js +61 -62
  80. package/server/assets/chat/shortcuts.js +212 -190
  81. package/server/assets/chat/side-pane.js +166 -131
  82. package/server/assets/chat/state.js +851 -707
  83. package/server/assets/chat/system-events.js +55 -27
  84. package/server/assets/chat/system-messages.js +59 -49
  85. package/server/assets/chat/task-form.js +178 -182
  86. package/server/assets/chat/task-row.js +158 -155
  87. package/server/assets/chat/tasks.js +653 -593
  88. package/server/assets/chat/viewport.js +32 -29
  89. package/server/assets/chat/window-controls.js +37 -0
  90. package/server/assets/code-highlight.css +22 -6
  91. package/server/assets/conversation.css +65 -16
  92. package/server/assets/doc-preview.css +6 -1
  93. package/server/assets/files.css +3 -0
  94. package/server/assets/monaco/integration-rules.css +1 -1
  95. package/server/assets/monaco/integration-rules.js +841 -533
  96. package/server/assets/responsive.css +32 -2
  97. package/server/assets/settings.css +117 -13
  98. package/server/assets/window-controls.css +36 -0
  99. package/server/channel-attachments.ts +133 -0
  100. package/server/channel-integration.ts +79 -26
  101. package/server/channels.ts +15 -5
  102. package/server/chat-server.ts +9 -1
  103. package/server/chat.html +73 -38
  104. package/server/manifest.webmanifest +1 -0
  105. package/server/routes/pages.ts +7 -5
  106. package/server/sw.js +346 -267
  107. package/src/center/center-client.ts +1 -1
  108. package/src/state/pg-database.ts +5 -5
  109. package/src/state/pg-migrate.ts +7 -7
  110. package/src/state/pg-worker.mjs +2 -17
  111. package/src/state/sqlite-database.ts +14 -5
  112. package/src/state/sqlite-rooms.ts +130 -23
  113. package/src/state/sqlite-state-store.ts +6 -5
  114. package/src/state/sqlite.ts +3 -3
  115. package/src/web/integration-rules-editor.ts +141 -5
  116. package/src/web/integration-rules.ts +6 -2
  117. package/src/web/integration-schema.ts +7 -6
  118. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  119. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  120. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  121. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  122. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  123. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  124. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  125. package/server/assets/chat/forward.js +0 -69
@@ -1,303 +0,0 @@
1
- import path from "node:path";
2
- import { pathToFileURL } from "node:url";
3
- import { cardVersionFromEnv, type CardVersion } from "./feishu-card.ts";
4
- import { parseInboundEvent } from "./feishu-inbound.ts";
5
- import { FeishuLiveConnection } from "./feishu-live.ts";
6
- import {
7
- ensureToken,
8
- FeishuApiError,
9
- sendMessage,
10
- startupFailureDetail,
11
- type FeishuConfig,
12
- type SendParams,
13
- type SendReceipt,
14
- type TokenState,
15
- } from "./feishu-send.ts";
16
- import { createFrameReader, writeFrame } from "./framing.ts";
17
- import {
18
- EVENT_SCHEMA_VERSION,
19
- MAX_FRAME_BYTES,
20
- PROTOCOL_VERSION,
21
- RPC_INTERNAL_ERROR,
22
- RPC_METHOD_NOT_FOUND,
23
- adapterRequestId,
24
- rpcError,
25
- rpcRequest,
26
- rpcResult,
27
- type IngestEvent,
28
- } from "./protocol.ts";
29
-
30
- export { deterministicUuid } from "./feishu-send.ts";
31
-
32
- const DEFAULT_BASE_URL = "https://open.feishu.cn";
33
- const DEFAULT_TIMEOUT_MS = 10_000;
34
-
35
- interface AdapterState extends TokenState {
36
- config?: FeishuConfig;
37
- started: boolean;
38
- inbound?: FeishuLiveConnection;
39
- pending: Map<string, (result: { duplicate?: boolean; error?: string }) => void>;
40
- sequence: number;
41
- }
42
-
43
- function logLine(accountId: string, message: string): void {
44
- console.error(`feishu adapter ${accountId}: ${message}`);
45
- }
46
-
47
- function configFromEnv(env: NodeJS.ProcessEnv): FeishuConfig | { error: string } {
48
- const appId = env.FEISHU_APP_ID;
49
- const appSecret = env.FEISHU_APP_SECRET;
50
- const missing: string[] = [];
51
- if (!appId) missing.push("FEISHU_APP_ID");
52
- if (!appSecret) missing.push("FEISHU_APP_SECRET");
53
- if (!appId || !appSecret) {
54
- return { error: `feishu adapter requires ${missing.join(" and ")}` };
55
- }
56
- const timeout = Number(env.FEISHU_HTTP_TIMEOUT_MS);
57
- const timeoutMs = Number.isInteger(timeout) && timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS;
58
- const baseUrl = (env.FEISHU_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
59
- let cardVersion: CardVersion;
60
- try {
61
- cardVersion = cardVersionFromEnv(env.FEISHU_CARD_VERSION);
62
- } catch (error) {
63
- return { error: error instanceof Error ? error.message : String(error) };
64
- }
65
- const inbound = env.FEISHU_INBOUND === "1";
66
- const inboundChats = new Set(
67
- (env.FEISHU_INBOUND_CHATS ?? "").split(/[,\s]+/).map((item) => item.trim()).filter(Boolean),
68
- );
69
- if (inbound && inboundChats.size === 0) {
70
- return {
71
- error: "FEISHU_INBOUND=1 requires FEISHU_INBOUND_CHATS (comma-separated group chat ids)",
72
- };
73
- }
74
- return { appId, appSecret, baseUrl, timeoutMs, cardVersion, inbound, inboundChats };
75
- }
76
-
77
-
78
- const INGEST_TIMEOUT_MS = 5000;
79
-
80
- /** Emit one ingest request and wait for the host commit; false means no ack. */
81
- function emitIngest(state: AdapterState, event: IngestEvent): Promise<boolean> {
82
- const id = adapterRequestId(++state.sequence);
83
- return new Promise((resolve) => {
84
- const timer = setTimeout(() => {
85
- state.pending.delete(id);
86
- logLine(state.accountId, "inbound ingest timed out");
87
- resolve(false);
88
- }, INGEST_TIMEOUT_MS);
89
- state.pending.set(id, (result) => {
90
- clearTimeout(timer);
91
- if (result.error) logLine(state.accountId, `inbound ingest failed: ${result.error}`);
92
- resolve(!result.error);
93
- });
94
- void writeFrame(process.stdout, rpcRequest(id, "ingest", event)).catch(() => {
95
- clearTimeout(timer);
96
- state.pending.delete(id);
97
- resolve(false);
98
- });
99
- });
100
- }
101
-
102
- async function startInbound(config: FeishuConfig, state: AdapterState): Promise<void> {
103
- const live = new FeishuLiveConnection({
104
- appId: config.appId,
105
- appSecret: config.appSecret,
106
- baseUrl: config.baseUrl,
107
- timeoutMs: config.timeoutMs,
108
- log: (message) => logLine(state.accountId, message),
109
- onEvent: async (payload) => {
110
- const parsed = parseInboundEvent(payload, {
111
- accountId: state.accountId,
112
- appId: config.appId,
113
- chats: config.inboundChats,
114
- });
115
- if (!parsed.event) {
116
- if (parsed.ignored) logLine(state.accountId, `inbound ignored: ${parsed.ignored}`);
117
- return true;
118
- }
119
- return emitIngest(state, parsed.event);
120
- },
121
- });
122
- await live.start();
123
- state.inbound = live;
124
- await notifyInbound(state, "ready");
125
- }
126
-
127
- /** Report inbound health without blocking the adapter's outbound path. */
128
- async function notifyInbound(state: AdapterState, inbound: "ready" | "failed", detail?: string): Promise<void> {
129
- const id = adapterRequestId(++state.sequence);
130
- const params = detail === undefined ? { inbound } : { inbound, detail };
131
- try {
132
- await writeFrame(process.stdout, rpcRequest(id, "status", params));
133
- } catch {
134
- // A status frame must never fail the adapter.
135
- }
136
- }
137
-
138
- async function handleRequest(message: Record<string, unknown>, state: AdapterState): Promise<void> {
139
- const rawId = message.id;
140
- if (rawId === undefined) {
141
- const failure = message.error as { message?: string } | undefined;
142
- if (failure) logLine(state.accountId, `request failed: ${failure.message ?? "error"}`);
143
- return;
144
- }
145
- if (typeof rawId !== "string" && typeof rawId !== "number") {
146
- logLine(state.accountId, "request id must be a string or number");
147
- return;
148
- }
149
- const id = rawId;
150
- const method = message.method;
151
- if (typeof method !== "string") {
152
- // Response to an adapter-initiated ingest request.
153
- const resolver = state.pending.get(String(id));
154
- if (resolver) {
155
- state.pending.delete(String(id));
156
- const failure = message.error as { message?: string } | undefined;
157
- resolver(failure ? { error: failure.message ?? "host ingest failed" } : {});
158
- }
159
- return;
160
- }
161
-
162
- if (method === "initialize") {
163
- const config = configFromEnv(process.env);
164
- if ("error" in config) {
165
- await writeFrame(process.stdout, rpcError(id, RPC_INTERNAL_ERROR, config.error));
166
- return;
167
- }
168
- state.config = config;
169
- await writeFrame(
170
- process.stdout,
171
- rpcResult(id, {
172
- version: PROTOCOL_VERSION,
173
- eventSchema: EVENT_SCHEMA_VERSION,
174
- maxFrameBytes: MAX_FRAME_BYTES,
175
- accounts: {
176
- [state.accountId]: {
177
- send: {
178
- text: true,
179
- format: ["text", "markdown"],
180
- reply: "native",
181
- idempotency: "persistent_delivery_key",
182
- card: ["1.0", "2.0"],
183
- },
184
- ...(config.inbound ? { ingress: "durable_outbox" } : {}),
185
- },
186
- },
187
- }),
188
- );
189
- return;
190
- }
191
-
192
- if (method === "start") {
193
- if (!state.config) {
194
- await writeFrame(
195
- process.stdout,
196
- rpcError(id, RPC_INTERNAL_ERROR, "feishu adapter requires FEISHU_APP_ID and FEISHU_APP_SECRET"),
197
- );
198
- return;
199
- }
200
- try {
201
- await ensureToken(state.config, state);
202
- } catch (error) {
203
- const detail = startupFailureDetail(error);
204
- logLine(state.accountId, `token validation failed: ${detail}`);
205
- await writeFrame(process.stdout, rpcError(id, RPC_INTERNAL_ERROR, detail));
206
- return;
207
- }
208
- if (state.config.inbound) {
209
- try {
210
- await startInbound(state.config, state);
211
- } catch (error) {
212
- // Inbound is opt-in but must never take the working outbound path down.
213
- const detail = error instanceof FeishuApiError
214
- ? startupFailureDetail(error)
215
- : error instanceof Error ? error.message : String(error);
216
- const hint = `${detail} (requires long-connection event subscription for im.message.receive_v1 and the bot in an allowlisted group)`;
217
- logLine(state.accountId, `inbound disabled; outbound stays active: ${hint}`);
218
- await notifyInbound(state, "failed", detail);
219
- }
220
- }
221
- state.started = true;
222
- await writeFrame(process.stdout, rpcResult(id, { ready: true }));
223
- logLine(state.accountId, "ready (tenant token validated)");
224
- return;
225
- }
226
-
227
- if (method === "send") {
228
- if (!state.started || !state.config) {
229
- await writeFrame(
230
- process.stdout,
231
- rpcResult(id, { state: "unknown", detail: "adapter is not started" } satisfies SendReceipt),
232
- );
233
- return;
234
- }
235
- const receipt = await sendMessage(state.config, state, (message.params ?? {}) as SendParams);
236
- if (receipt.state === "sent" && receipt.providerMessage) {
237
- logLine(state.accountId, `send succeeded native=${receipt.providerMessage.nativeMessageId}`);
238
- } else {
239
- logLine(state.accountId, `send ${receipt.state}${receipt.detail ? `: ${receipt.detail}` : ""}`);
240
- }
241
- await writeFrame(process.stdout, rpcResult(id, receipt));
242
- return;
243
- }
244
-
245
- if (method === "ping") {
246
- await writeFrame(process.stdout, rpcResult(id, { pong: true }));
247
- return;
248
- }
249
-
250
- if (method === "shutdown") {
251
- await state.inbound?.stop();
252
- await writeFrame(process.stdout, rpcResult(id, {}));
253
- process.exit(0);
254
- }
255
-
256
- await writeFrame(process.stdout, rpcError(id, RPC_METHOD_NOT_FOUND, `method not found: ${method}`));
257
- }
258
-
259
- export function runFeishuAdapter(): Promise<void> {
260
- const state: AdapterState = {
261
- accountId: process.env.CHANNELD_ACCOUNT_ID ?? "feishu",
262
- tokenExpiresAt: 0,
263
- started: false,
264
- pending: new Map(),
265
- sequence: 0,
266
- };
267
- const read = createFrameReader(
268
- (message) => {
269
- void handleRequest(message, state).catch((error: unknown) => {
270
- logLine(state.accountId, `handler failed: ${error instanceof Error ? error.message : String(error)}`);
271
- });
272
- },
273
- (error) => logLine(state.accountId, `frame error: ${error.message}`),
274
- );
275
- process.stdin.on("data", (chunk: Buffer) => read(chunk));
276
- logLine(state.accountId, "ready on stdio");
277
- const finish = (): void => {
278
- void state.inbound?.stop();
279
- };
280
- process.stdin.once("end", finish);
281
- process.stdin.once("close", finish);
282
- return new Promise((resolve) => {
283
- process.stdin.once("end", resolve);
284
- process.stdin.once("close", resolve);
285
- });
286
- }
287
-
288
- function isDirectRun(): boolean {
289
- const entry = process.argv[1];
290
- if (!entry) return false;
291
- try {
292
- return pathToFileURL(path.resolve(entry)).href === import.meta.url;
293
- } catch {
294
- return false;
295
- }
296
- }
297
-
298
- if (isDirectRun()) {
299
- runFeishuAdapter().catch((error: unknown) => {
300
- console.error(`feishu adapter failed: ${error instanceof Error ? error.message : String(error)}`);
301
- process.exit(1);
302
- });
303
- }
@@ -1,27 +0,0 @@
1
- export type CardVersion = "1.0" | "2.0";
2
-
3
- /**
4
- * FEISHU_CARD_VERSION is opt-in: card 1.0 keeps the 0.8.0 payload because some
5
- * tenants still render card 2.0 differently. Card 2.0 is required for headings,
6
- * lists, and fenced code as block Markdown.
7
- */
8
- export function cardVersionFromEnv(value: string | undefined): CardVersion {
9
- const raw = (value ?? "").trim().toLowerCase();
10
- if (!raw || raw === "1" || raw === "1.0") return "1.0";
11
- if (raw === "2" || raw === "2.0") return "2.0";
12
- throw new Error("FEISHU_CARD_VERSION must be 1.0 or 2.0");
13
- }
14
-
15
- export function buildCard(version: CardVersion, text: string): unknown {
16
- if (version === "2.0") {
17
- return {
18
- schema: "2.0",
19
- config: { update_multi: true },
20
- body: { elements: [{ tag: "markdown", content: text }] },
21
- };
22
- }
23
- return {
24
- config: { wide_screen_mode: true },
25
- elements: [{ tag: "div", text: { tag: "lark_md", content: text } }],
26
- };
27
- }
@@ -1,158 +0,0 @@
1
- import type { IngestEvent, MessageRef } from "./protocol.ts";
2
-
3
- export interface InboundOptions {
4
- accountId: string;
5
- appId: string;
6
- /** Group chat ids explicitly allowed by the operator. */
7
- chats: ReadonlySet<string>;
8
- }
9
-
10
- export interface ParsedInbound {
11
- event?: IngestEvent;
12
- ignored?: string;
13
- }
14
-
15
- function isRecord(value: unknown): value is Record<string, unknown> {
16
- return typeof value === "object" && value !== null && !Array.isArray(value);
17
- }
18
-
19
- function stringValue(value: unknown): string | undefined {
20
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
21
- }
22
-
23
- function replaceMentions(text: string, mentions: unknown): string {
24
- if (!Array.isArray(mentions)) return text;
25
- let next = text;
26
- for (const item of mentions) {
27
- if (!isRecord(item)) continue;
28
- const key = stringValue(item.key);
29
- const name = stringValue(item.name);
30
- if (key && name) next = next.split(key).join(`@${name}`);
31
- }
32
- return next;
33
- }
34
-
35
- function richText(value: unknown): string | undefined {
36
- if (!Array.isArray(value)) return undefined;
37
- const parts: string[] = [];
38
- for (const line of value) {
39
- if (!Array.isArray(line)) continue;
40
- for (const item of line) {
41
- if (!isRecord(item)) continue;
42
- if (item.tag === "at") {
43
- const name = stringValue(item.user_name) ?? stringValue(item.user_id);
44
- if (name) parts.push(`@${name}`);
45
- } else {
46
- const text = stringValue(item.text);
47
- if (text) parts.push(text);
48
- }
49
- }
50
- parts.push("\n");
51
- }
52
- return parts.join("").trim() || undefined;
53
- }
54
-
55
- function messageText(messageType: string, raw: string, mentions: unknown): string | undefined {
56
- let parsed: unknown;
57
- try {
58
- parsed = JSON.parse(raw);
59
- } catch {
60
- return undefined;
61
- }
62
- if (!isRecord(parsed)) return undefined;
63
- if (messageType === "text") {
64
- const text = stringValue(parsed.text);
65
- return text ? replaceMentions(text, mentions) : undefined;
66
- }
67
- if (messageType === "post") {
68
- const post = isRecord(parsed.content)
69
- ? Object.values(parsed.content).find((item) => Array.isArray(item))
70
- : parsed.content;
71
- return richText(post);
72
- }
73
- return undefined;
74
- }
75
-
76
- function occurredAt(value: unknown): string | undefined {
77
- const text = stringValue(value);
78
- if (!text || !/^\d{10,16}$/.test(text)) return undefined;
79
- const ms = Number(text);
80
- const stamp = text.length <= 11 ? ms * 1000 : ms;
81
- const date = new Date(stamp);
82
- return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
83
- }
84
-
85
- /**
86
- * Map one Feishu `im.message.receive_v1` payload to a Channel D ingest event.
87
- * Only allowlisted group text/post messages from human senders are relayed.
88
- */
89
- export function parseInboundEvent(payload: string, options: InboundOptions): ParsedInbound {
90
- let root: unknown;
91
- try {
92
- root = JSON.parse(payload);
93
- } catch {
94
- return { ignored: "malformed event JSON" };
95
- }
96
- if (!isRecord(root)) return { ignored: "malformed event JSON" };
97
- const header = isRecord(root.header) ? root.header : undefined;
98
- if (!header) return { ignored: "missing event header" };
99
- if (header.event_type !== "im.message.receive_v1") return { ignored: "unsubscribed event type" };
100
- if (stringValue(header.app_id) !== options.appId) return { ignored: "event app mismatch" };
101
-
102
- const body = isRecord(root.event) ? root.event : undefined;
103
- const message = body && isRecord(body.message) ? body.message : undefined;
104
- const sender = body && isRecord(body.sender) ? body.sender : undefined;
105
- if (!body || !message || !sender) return { ignored: "malformed message event" };
106
-
107
- const chatType = stringValue(message.chat_type);
108
- if (chatType !== "group" && chatType !== "topic_group") return { ignored: "not a group message" };
109
- const chatId = stringValue(message.chat_id);
110
- const messageId = stringValue(message.message_id);
111
- const messageType = stringValue(message.message_type);
112
- if (!chatId || !messageId || !messageType) return { ignored: "message identity is incomplete" };
113
- if (!options.chats.has(chatId)) return { ignored: "chat is not in FEISHU_INBOUND_CHATS" };
114
-
115
- const senderType = stringValue(sender.sender_type);
116
- if (senderType !== "user") return { ignored: "bot or unknown sender" };
117
- const senderIds = isRecord(sender.sender_id) ? sender.sender_id : {};
118
- if (stringValue(senderIds.app_id)) return { ignored: "bot sender" };
119
- const nativeUserId = stringValue(senderIds.open_id)
120
- ?? stringValue(senderIds.user_id)
121
- ?? stringValue(senderIds.union_id);
122
- if (!nativeUserId) return { ignored: "sender identity is unavailable" };
123
-
124
- const text = messageText(messageType, stringValue(message.content) ?? "", message.mentions);
125
- if (!text) return { ignored: `unsupported or empty ${messageType} message` };
126
-
127
- const source = { platform: "feishu", accountId: options.accountId, roomId: chatId };
128
- const parentId = stringValue(message.parent_id) ?? stringValue(message.root_id);
129
- const parent: MessageRef | undefined = parentId
130
- ? { endpoint: source, nativeMessageId: parentId }
131
- : undefined;
132
- const eventRef: MessageRef = { endpoint: source, nativeMessageId: messageId, text };
133
- const providerEventId = stringValue(header.event_id) ?? messageId;
134
- const eventId = `feishu-${options.accountId}-${providerEventId}`;
135
- const createTime = occurredAt(message.create_time);
136
-
137
- return {
138
- event: {
139
- schemaVersion: 1,
140
- eventId,
141
- kind: "message.created",
142
- source,
143
- actor: {
144
- platform: "feishu",
145
- identityNamespace: stringValue(senderIds.open_id) ? "open_id" : "user_id",
146
- nativeUserId,
147
- },
148
- providerEventId,
149
- // Feishu event ids are stable across retries; fall back to the message id.
150
- sourceDedupKey: `feishu:${options.accountId}:${providerEventId}`,
151
- message: eventRef,
152
- ...(parent ? { parent } : {}),
153
- ...(createTime ? { occurredAt: createTime } : {}),
154
- receivedAt: new Date().toISOString(),
155
- content: { text },
156
- },
157
- };
158
- }