@alexsun-top/opencode-chat-room 0.8.0 → 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.
- package/CHANGELOG.md +29 -0
- package/LICENSE +2 -2
- package/README.md +38 -6
- package/README.zh-CN.md +38 -6
- package/cli.ts +27 -1
- package/dist/cli.js +5074 -3212
- package/package.json +23 -3
- package/packages/chat-room-channeld/README.md +98 -25
- package/packages/chat-room-channeld/dist/feishu-adapter.js +912 -149
- package/packages/chat-room-channeld/src/adapter.ts +36 -2
- package/packages/chat-room-channeld/src/config.ts +63 -1
- package/packages/chat-room-channeld/src/delivery.ts +6 -1
- package/packages/chat-room-channeld/src/feishu-adapter.ts +122 -292
- package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
- package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
- package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
- package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
- package/packages/chat-room-channeld/src/host.ts +120 -2
- package/packages/chat-room-channeld/src/inbound.ts +26 -0
- package/packages/chat-room-channeld/src/state.ts +17 -0
- package/packages/chat-room-channeld/src/stats.ts +43 -1
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +15 -9
- package/server/assets/chat/announcements.js +70 -7
- package/server/assets/chat/doc-preview.js +184 -35
- package/server/assets/chat/events.js +3 -0
- package/server/assets/chat/files.js +46 -4
- package/server/assets/chat/index.js +2 -0
- package/server/assets/chat/integration-editor.js +163 -0
- package/server/assets/chat/integration-values.js +124 -0
- package/server/assets/chat/integrations.js +498 -0
- package/server/assets/chat/locales/de.js +40 -4
- package/server/assets/chat/locales/es.js +40 -4
- package/server/assets/chat/locales/fr.js +40 -4
- package/server/assets/chat/locales/it.js +40 -4
- package/server/assets/chat/locales/ja.js +40 -4
- package/server/assets/chat/locales/ko.js +40 -4
- package/server/assets/chat/markdown.js +22 -8
- package/server/assets/chat/messages.js +5 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/panels.js +36 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +15 -3
- package/server/assets/chat/reminders.js +69 -8
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/settings.js +30 -2
- package/server/assets/chat/side-pane.js +1 -2
- package/server/assets/chat/state.js +93 -10
- package/server/assets/chat/system-events.js +32 -0
- package/server/assets/chat/system-messages.js +23 -14
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +121 -33
- package/server/assets/code-highlight.css +55 -32
- package/server/assets/conversation.css +123 -23
- package/server/assets/doc-preview.css +35 -3
- package/server/assets/files.css +5 -0
- package/server/assets/fluent-icons.svg +2 -0
- package/server/assets/monaco/LICENSE +21 -0
- package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
- package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
- package/server/assets/monaco/editor.worker.js +45 -0
- package/server/assets/monaco/integration-rules.css +1 -0
- package/server/assets/monaco/integration-rules.js +1297 -0
- package/server/assets/monaco/json.worker.js +77 -0
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
- package/server/assets/office/docx.bundle.js +33 -0
- package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
- package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
- package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
- package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
- package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
- package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
- package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
- package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
- package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
- package/server/assets/office/pptx.bundle.js +104 -0
- package/server/assets/office/xlsx.bundle.js +141 -0
- package/server/assets/recall.css +5 -4
- package/server/assets/responsive.css +50 -11
- package/server/assets/settings.css +73 -1
- package/server/assets/tasks.css +57 -7
- package/server/channel-integration.ts +519 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +261 -18
- package/server/chat-server.ts +32 -580
- package/server/chat.html +187 -21
- package/server/http-server.ts +3 -182
- package/server/resource-routes.ts +16 -16
- package/server/routes/inbox.ts +100 -0
- package/server/routes/pages.ts +83 -0
- package/server/routes/questions.ts +39 -0
- package/server/routes/room-actions.ts +162 -0
- package/server/routes/rooms.ts +160 -0
- package/server/startup.ts +84 -0
- package/server/sw.js +4 -0
- package/server/task-routes.ts +1 -1
- package/src/center/center-client.ts +2 -10
- package/src/config/file-config.ts +7 -54
- package/src/platform/http-server.ts +182 -0
- package/src/protocol/addressing.ts +21 -0
- package/src/protocol/config.ts +58 -0
- package/src/protocol/room.ts +51 -0
- package/src/rooms/resources.ts +26 -16
- package/src/rooms/room-service.ts +2 -48
- package/src/rooms/storage.ts +329 -0
- package/src/rooms/tasks.ts +21 -5
- package/src/runtime/watch.ts +1 -1
- package/src/state/pg-database.ts +183 -0
- package/src/state/pg-migrate.ts +175 -0
- package/src/state/pg-sql.mjs +175 -0
- package/src/state/pg-worker.mjs +148 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +121 -0
- package/src/state/sqlite-legacy.ts +90 -0
- package/src/state/sqlite-members.ts +155 -0
- package/src/state/sqlite-messages.ts +288 -0
- package/src/state/sqlite-resources.ts +39 -0
- package/src/state/sqlite-rooms.ts +87 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +33 -0
- package/src/state/sqlite-state.ts +15 -897
- package/src/state/sqlite-tasks.ts +65 -0
- package/src/state/sqlite-transaction.ts +13 -0
- package/src/state/sqlite.ts +21 -1
- package/src/state/store.ts +5 -1
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- package/src/tui/i18n.mjs +38 -0
- package/src/tui/info-app.mjs +50 -51
- package/src/tui/info-content.mjs +79 -44
- package/src/tui/join-app.mjs +9 -9
- package/src/tui/locales/en.mjs +349 -0
- package/src/tui/locales/zh-CN.mjs +349 -0
- package/src/tui/main.mjs +85 -37
- package/src/tui/markdown.mjs +3 -2
- package/src/tui/mentions.mjs +3 -1
- package/src/tui/message-app.mjs +22 -21
- package/src/tui/message-view.mjs +2 -1
- package/src/tui/palette-app.mjs +9 -8
- package/src/tui/palette.mjs +30 -24
- package/src/tui/prefs.mjs +92 -0
- package/src/tui/reminder-app.mjs +18 -17
- package/src/tui/room-settings-app.mjs +30 -28
- package/src/tui/settings-app.mjs +153 -0
- package/src/tui/ui-content.mjs +65 -86
- package/src/tui/ui-help.mjs +73 -0
- package/src/tui/ui-overlay-view.mjs +23 -7
- package/src/tui/ui-suggest.mjs +6 -5
- package/src/tui/ui-theme.mjs +37 -33
- package/src/tui/ui-view.mjs +22 -7
- package/src/tui/ui.mjs +15 -3
- package/src/web/editor.worker.ts +1 -0
- package/src/web/integration-rules-editor.ts +439 -0
- package/src/web/integration-rules.ts +22 -0
- package/src/web/integration-schema.ts +228 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
|
@@ -1,133 +1,649 @@
|
|
|
1
1
|
// packages/chat-room-channeld/src/feishu-adapter.ts
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
2
|
import path from "node:path";
|
|
4
3
|
import { pathToFileURL } from "node:url";
|
|
5
4
|
|
|
6
|
-
// packages/chat-room-channeld/src/
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
var RPC_INTERNAL_ERROR = -32603;
|
|
15
|
-
function rpcResult(id, result) {
|
|
16
|
-
return { jsonrpc: "2.0", id, result };
|
|
5
|
+
// packages/chat-room-channeld/src/feishu-card.ts
|
|
6
|
+
function cardVersionFromEnv(value) {
|
|
7
|
+
const raw = (value ?? "").trim().toLowerCase();
|
|
8
|
+
if (!raw || raw === "1" || raw === "1.0")
|
|
9
|
+
return "1.0";
|
|
10
|
+
if (raw === "2" || raw === "2.0")
|
|
11
|
+
return "2.0";
|
|
12
|
+
throw new Error("FEISHU_CARD_VERSION must be 1.0 or 2.0");
|
|
17
13
|
}
|
|
18
|
-
function
|
|
19
|
-
|
|
20
|
-
|
|
14
|
+
function buildCard(version, text) {
|
|
15
|
+
if (version === "2.0") {
|
|
16
|
+
return {
|
|
17
|
+
schema: "2.0",
|
|
18
|
+
config: { update_multi: true },
|
|
19
|
+
body: { elements: [{ tag: "markdown", content: text }] }
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
config: { wide_screen_mode: true },
|
|
24
|
+
elements: [{ tag: "div", text: { tag: "lark_md", content: text } }]
|
|
25
|
+
};
|
|
21
26
|
}
|
|
22
27
|
|
|
23
|
-
// packages/chat-room-channeld/src/
|
|
24
|
-
function
|
|
25
|
-
|
|
28
|
+
// packages/chat-room-channeld/src/feishu-inbound.ts
|
|
29
|
+
function isRecord(value) {
|
|
30
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
31
|
+
}
|
|
32
|
+
function stringValue(value) {
|
|
33
|
+
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
34
|
+
}
|
|
35
|
+
function replaceMentions(text, mentions) {
|
|
36
|
+
if (!Array.isArray(mentions))
|
|
37
|
+
return text;
|
|
38
|
+
let next = text;
|
|
39
|
+
for (const item of mentions) {
|
|
40
|
+
if (!isRecord(item))
|
|
41
|
+
continue;
|
|
42
|
+
const key = stringValue(item.key);
|
|
43
|
+
const name = stringValue(item.name);
|
|
44
|
+
if (key && name)
|
|
45
|
+
next = next.split(key).join(`@${name}`);
|
|
46
|
+
}
|
|
47
|
+
return next;
|
|
48
|
+
}
|
|
49
|
+
function richText(value) {
|
|
50
|
+
if (!Array.isArray(value))
|
|
51
|
+
return;
|
|
52
|
+
const parts = [];
|
|
53
|
+
for (const line of value) {
|
|
54
|
+
if (!Array.isArray(line))
|
|
55
|
+
continue;
|
|
56
|
+
for (const item of line) {
|
|
57
|
+
if (!isRecord(item))
|
|
58
|
+
continue;
|
|
59
|
+
if (item.tag === "at") {
|
|
60
|
+
const name = stringValue(item.user_name) ?? stringValue(item.user_id);
|
|
61
|
+
if (name)
|
|
62
|
+
parts.push(`@${name}`);
|
|
63
|
+
} else {
|
|
64
|
+
const text = stringValue(item.text);
|
|
65
|
+
if (text)
|
|
66
|
+
parts.push(text);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
parts.push(`
|
|
70
|
+
`);
|
|
71
|
+
}
|
|
72
|
+
return parts.join("").trim() || undefined;
|
|
73
|
+
}
|
|
74
|
+
function messageText(messageType, raw, mentions) {
|
|
75
|
+
let parsed;
|
|
76
|
+
try {
|
|
77
|
+
parsed = JSON.parse(raw);
|
|
78
|
+
} catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (!isRecord(parsed))
|
|
82
|
+
return;
|
|
83
|
+
if (messageType === "text") {
|
|
84
|
+
const text = stringValue(parsed.text);
|
|
85
|
+
return text ? replaceMentions(text, mentions) : undefined;
|
|
86
|
+
}
|
|
87
|
+
if (messageType === "post") {
|
|
88
|
+
const post = isRecord(parsed.content) ? Object.values(parsed.content).find((item) => Array.isArray(item)) : parsed.content;
|
|
89
|
+
return richText(post);
|
|
90
|
+
}
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
function occurredAt(value) {
|
|
94
|
+
const text = stringValue(value);
|
|
95
|
+
if (!text || !/^\d{10,16}$/.test(text))
|
|
96
|
+
return;
|
|
97
|
+
const ms = Number(text);
|
|
98
|
+
const stamp = text.length <= 11 ? ms * 1000 : ms;
|
|
99
|
+
const date = new Date(stamp);
|
|
100
|
+
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
101
|
+
}
|
|
102
|
+
function parseInboundEvent(payload, options) {
|
|
103
|
+
let root;
|
|
104
|
+
try {
|
|
105
|
+
root = JSON.parse(payload);
|
|
106
|
+
} catch {
|
|
107
|
+
return { ignored: "malformed event JSON" };
|
|
108
|
+
}
|
|
109
|
+
if (!isRecord(root))
|
|
110
|
+
return { ignored: "malformed event JSON" };
|
|
111
|
+
const header = isRecord(root.header) ? root.header : undefined;
|
|
112
|
+
if (!header)
|
|
113
|
+
return { ignored: "missing event header" };
|
|
114
|
+
if (header.event_type !== "im.message.receive_v1")
|
|
115
|
+
return { ignored: "unsubscribed event type" };
|
|
116
|
+
if (stringValue(header.app_id) !== options.appId)
|
|
117
|
+
return { ignored: "event app mismatch" };
|
|
118
|
+
const body = isRecord(root.event) ? root.event : undefined;
|
|
119
|
+
const message = body && isRecord(body.message) ? body.message : undefined;
|
|
120
|
+
const sender = body && isRecord(body.sender) ? body.sender : undefined;
|
|
121
|
+
if (!body || !message || !sender)
|
|
122
|
+
return { ignored: "malformed message event" };
|
|
123
|
+
const chatType = stringValue(message.chat_type);
|
|
124
|
+
if (chatType !== "group" && chatType !== "topic_group")
|
|
125
|
+
return { ignored: "not a group message" };
|
|
126
|
+
const chatId = stringValue(message.chat_id);
|
|
127
|
+
const messageId = stringValue(message.message_id);
|
|
128
|
+
const messageType = stringValue(message.message_type);
|
|
129
|
+
if (!chatId || !messageId || !messageType)
|
|
130
|
+
return { ignored: "message identity is incomplete" };
|
|
131
|
+
if (!options.chats.has(chatId))
|
|
132
|
+
return { ignored: "chat is not in FEISHU_INBOUND_CHATS" };
|
|
133
|
+
const senderType = stringValue(sender.sender_type);
|
|
134
|
+
if (senderType !== "user")
|
|
135
|
+
return { ignored: "bot or unknown sender" };
|
|
136
|
+
const senderIds = isRecord(sender.sender_id) ? sender.sender_id : {};
|
|
137
|
+
if (stringValue(senderIds.app_id))
|
|
138
|
+
return { ignored: "bot sender" };
|
|
139
|
+
const nativeUserId = stringValue(senderIds.open_id) ?? stringValue(senderIds.user_id) ?? stringValue(senderIds.union_id);
|
|
140
|
+
if (!nativeUserId)
|
|
141
|
+
return { ignored: "sender identity is unavailable" };
|
|
142
|
+
const text = messageText(messageType, stringValue(message.content) ?? "", message.mentions);
|
|
26
143
|
if (!text)
|
|
27
|
-
|
|
28
|
-
|
|
144
|
+
return { ignored: `unsupported or empty ${messageType} message` };
|
|
145
|
+
const source = { platform: "feishu", accountId: options.accountId, roomId: chatId };
|
|
146
|
+
const parentId = stringValue(message.parent_id) ?? stringValue(message.root_id);
|
|
147
|
+
const parent = parentId ? { endpoint: source, nativeMessageId: parentId } : undefined;
|
|
148
|
+
const eventRef = { endpoint: source, nativeMessageId: messageId, text };
|
|
149
|
+
const providerEventId = stringValue(header.event_id) ?? messageId;
|
|
150
|
+
const eventId = `feishu-${options.accountId}-${providerEventId}`;
|
|
151
|
+
const createTime = occurredAt(message.create_time);
|
|
152
|
+
return {
|
|
153
|
+
event: {
|
|
154
|
+
schemaVersion: 1,
|
|
155
|
+
eventId,
|
|
156
|
+
kind: "message.created",
|
|
157
|
+
source,
|
|
158
|
+
actor: {
|
|
159
|
+
platform: "feishu",
|
|
160
|
+
identityNamespace: stringValue(senderIds.open_id) ? "open_id" : "user_id",
|
|
161
|
+
nativeUserId
|
|
162
|
+
},
|
|
163
|
+
providerEventId,
|
|
164
|
+
sourceDedupKey: `feishu:${options.accountId}:${providerEventId}`,
|
|
165
|
+
message: eventRef,
|
|
166
|
+
...parent ? { parent } : {},
|
|
167
|
+
...createTime ? { occurredAt: createTime } : {},
|
|
168
|
+
receivedAt: new Date().toISOString(),
|
|
169
|
+
content: { text }
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// packages/chat-room-channeld/src/feishu-ws-frames.ts
|
|
175
|
+
var utf8 = new TextEncoder;
|
|
176
|
+
function varint(value) {
|
|
177
|
+
let rest = BigInt(Math.max(0, Math.trunc(value)));
|
|
178
|
+
const out = [];
|
|
179
|
+
while (rest > 0x7fn) {
|
|
180
|
+
out.push(Number(rest & 0x7fn | 0x80n));
|
|
181
|
+
rest >>= 7n;
|
|
182
|
+
}
|
|
183
|
+
out.push(Number(rest));
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
function fieldKey(field, wire) {
|
|
187
|
+
return varint(field << 3 | wire);
|
|
188
|
+
}
|
|
189
|
+
function bytesField(field, value) {
|
|
190
|
+
return [...fieldKey(field, 2), ...varint(value.length), ...value];
|
|
191
|
+
}
|
|
192
|
+
function stringField(field, value) {
|
|
193
|
+
return bytesField(field, utf8.encode(value));
|
|
194
|
+
}
|
|
195
|
+
function numberField(field, value) {
|
|
196
|
+
return [...fieldKey(field, 0), ...varint(value)];
|
|
197
|
+
}
|
|
198
|
+
function encodeFrame(frame) {
|
|
199
|
+
const out = [];
|
|
200
|
+
out.push(...numberField(1, frame.SeqID ?? 0));
|
|
201
|
+
out.push(...numberField(2, frame.LogID ?? 0));
|
|
202
|
+
out.push(...numberField(3, frame.service ?? 0));
|
|
203
|
+
out.push(...numberField(4, frame.method ?? 0));
|
|
204
|
+
for (const header of frame.headers ?? []) {
|
|
205
|
+
const entry = [...stringField(1, header.key), ...stringField(2, header.value)];
|
|
206
|
+
out.push(...bytesField(5, Uint8Array.from(entry)));
|
|
207
|
+
}
|
|
208
|
+
if (frame.payload_encoding)
|
|
209
|
+
out.push(...stringField(6, frame.payload_encoding));
|
|
210
|
+
if (frame.payload_type)
|
|
211
|
+
out.push(...stringField(7, frame.payload_type));
|
|
212
|
+
if (frame.payload)
|
|
213
|
+
out.push(...bytesField(8, frame.payload));
|
|
214
|
+
if (frame.LogIDNew)
|
|
215
|
+
out.push(...stringField(9, frame.LogIDNew));
|
|
216
|
+
return Uint8Array.from(out);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
class Reader {
|
|
220
|
+
#bytes;
|
|
221
|
+
#offset = 0;
|
|
222
|
+
constructor(bytes) {
|
|
223
|
+
this.#bytes = bytes;
|
|
224
|
+
}
|
|
225
|
+
get done() {
|
|
226
|
+
return this.#offset >= this.#bytes.length;
|
|
227
|
+
}
|
|
228
|
+
varint() {
|
|
229
|
+
let value = 0n;
|
|
230
|
+
let shift = 0n;
|
|
231
|
+
for (;; ) {
|
|
232
|
+
if (this.#offset >= this.#bytes.length)
|
|
233
|
+
throw new Error("truncated varint");
|
|
234
|
+
const byte = this.#bytes[this.#offset++];
|
|
235
|
+
value |= BigInt(byte & 127) << shift;
|
|
236
|
+
if ((byte & 128) === 0)
|
|
237
|
+
return value;
|
|
238
|
+
shift += 7n;
|
|
239
|
+
if (shift > 70n)
|
|
240
|
+
throw new Error("varint is too long");
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
bytes(length) {
|
|
244
|
+
if (this.#offset + length > this.#bytes.length)
|
|
245
|
+
throw new Error("truncated frame field");
|
|
246
|
+
const slice = this.#bytes.subarray(this.#offset, this.#offset + length);
|
|
247
|
+
this.#offset += length;
|
|
248
|
+
return slice;
|
|
249
|
+
}
|
|
250
|
+
skip(wire) {
|
|
251
|
+
if (wire === 0)
|
|
252
|
+
this.varint();
|
|
253
|
+
else if (wire === 1)
|
|
254
|
+
this.bytes(8);
|
|
255
|
+
else if (wire === 2)
|
|
256
|
+
this.bytes(Number(this.varint()));
|
|
257
|
+
else if (wire === 5)
|
|
258
|
+
this.bytes(4);
|
|
259
|
+
else
|
|
260
|
+
throw new Error(`unsupported wire type ${wire}`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function decodeHeader(bytes) {
|
|
264
|
+
const reader = new Reader(bytes);
|
|
265
|
+
let key = "";
|
|
266
|
+
let value = "";
|
|
267
|
+
while (!reader.done) {
|
|
268
|
+
const tag = Number(reader.varint());
|
|
269
|
+
const field = tag >> 3;
|
|
270
|
+
const wire = tag & 7;
|
|
271
|
+
if (field === 1 && wire === 2)
|
|
272
|
+
key = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
273
|
+
else if (field === 2 && wire === 2)
|
|
274
|
+
value = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
275
|
+
else
|
|
276
|
+
reader.skip(wire);
|
|
277
|
+
}
|
|
278
|
+
return { key, value };
|
|
279
|
+
}
|
|
280
|
+
function decodeFrame(bytes) {
|
|
281
|
+
const reader = new Reader(bytes);
|
|
282
|
+
const frame = {};
|
|
283
|
+
while (!reader.done) {
|
|
284
|
+
const tag = Number(reader.varint());
|
|
285
|
+
const field = tag >> 3;
|
|
286
|
+
const wire = tag & 7;
|
|
287
|
+
switch (field) {
|
|
288
|
+
case 1:
|
|
289
|
+
frame.SeqID = Number(reader.varint());
|
|
290
|
+
break;
|
|
291
|
+
case 2:
|
|
292
|
+
frame.LogID = Number(reader.varint());
|
|
293
|
+
break;
|
|
294
|
+
case 3:
|
|
295
|
+
frame.service = Number(reader.varint());
|
|
296
|
+
break;
|
|
297
|
+
case 4:
|
|
298
|
+
frame.method = Number(reader.varint());
|
|
299
|
+
break;
|
|
300
|
+
case 5:
|
|
301
|
+
frame.headers = [...frame.headers ?? [], decodeHeader(reader.bytes(Number(reader.varint())))];
|
|
302
|
+
break;
|
|
303
|
+
case 6:
|
|
304
|
+
frame.payload_encoding = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
305
|
+
break;
|
|
306
|
+
case 7:
|
|
307
|
+
frame.payload_type = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
308
|
+
break;
|
|
309
|
+
case 8:
|
|
310
|
+
frame.payload = reader.bytes(Number(reader.varint()));
|
|
311
|
+
break;
|
|
312
|
+
case 9:
|
|
313
|
+
frame.LogIDNew = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
314
|
+
break;
|
|
315
|
+
default:
|
|
316
|
+
reader.skip(wire);
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return frame;
|
|
321
|
+
}
|
|
322
|
+
function headerValue(frame, key) {
|
|
323
|
+
return frame.headers?.find((header) => header.key === key)?.value;
|
|
324
|
+
}
|
|
325
|
+
function jsonPayload(value) {
|
|
326
|
+
return utf8.encode(JSON.stringify(value));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// packages/chat-room-channeld/src/feishu-live.ts
|
|
330
|
+
var DEFAULT_PING_MS = 120000;
|
|
331
|
+
var DEFAULT_RECONNECT_MS = 120000;
|
|
332
|
+
var DEFAULT_NONCE_MS = 30000;
|
|
333
|
+
var FRAGMENT_TTL_MS = 1e4;
|
|
334
|
+
var CONNECT_TIMEOUT_MS = 1e4;
|
|
335
|
+
function isRecord2(value) {
|
|
336
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
337
|
+
}
|
|
338
|
+
async function discovery(options) {
|
|
339
|
+
const controller = new AbortController;
|
|
340
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs);
|
|
341
|
+
let raw;
|
|
29
342
|
try {
|
|
30
|
-
|
|
343
|
+
const response = await fetch(`${options.baseUrl}/callback/ws/endpoint`, {
|
|
344
|
+
method: "POST",
|
|
345
|
+
headers: { "Content-Type": "application/json; charset=utf-8", locale: "zh" },
|
|
346
|
+
body: JSON.stringify({ AppID: options.appId, AppSecret: options.appSecret }),
|
|
347
|
+
signal: controller.signal
|
|
348
|
+
});
|
|
349
|
+
const text = await response.text();
|
|
350
|
+
let body;
|
|
351
|
+
try {
|
|
352
|
+
body = JSON.parse(text);
|
|
353
|
+
} catch {
|
|
354
|
+
body = undefined;
|
|
355
|
+
}
|
|
356
|
+
raw = { status: response.status, body };
|
|
31
357
|
} catch (error) {
|
|
32
|
-
|
|
358
|
+
const code = error?.cause?.code;
|
|
359
|
+
const detail = typeof code === "string" ? ` (${code})` : "";
|
|
360
|
+
throw new Error(`feishu long connection discovery failed${detail}`);
|
|
361
|
+
} finally {
|
|
362
|
+
clearTimeout(timer);
|
|
33
363
|
}
|
|
34
|
-
if (!
|
|
35
|
-
throw new Error(
|
|
364
|
+
if (!isRecord2(raw.body) || typeof raw.body.code !== "number") {
|
|
365
|
+
throw new Error(`feishu long connection discovery failed: http ${raw.status}`);
|
|
36
366
|
}
|
|
37
|
-
|
|
367
|
+
if (raw.body.code !== 0) {
|
|
368
|
+
const msg = typeof raw.body.msg === "string" && raw.body.msg ? `: ${raw.body.msg}` : "";
|
|
369
|
+
throw new Error(`feishu long connection unavailable: code ${raw.body.code}${msg}`);
|
|
370
|
+
}
|
|
371
|
+
const data = isRecord2(raw.body.data) ? raw.body.data : undefined;
|
|
372
|
+
const url = data && typeof data.URL === "string" ? data.URL : "";
|
|
373
|
+
if (!url.startsWith("ws://") && !url.startsWith("wss://")) {
|
|
374
|
+
throw new Error("feishu long connection discovery returned no WebSocket URL");
|
|
375
|
+
}
|
|
376
|
+
const parsed = new URL(url);
|
|
377
|
+
const serviceId = Number(parsed.searchParams.get("service_id"));
|
|
378
|
+
if (!Number.isInteger(serviceId)) {
|
|
379
|
+
throw new Error("feishu long connection URL is missing service_id");
|
|
380
|
+
}
|
|
381
|
+
const config = data && isRecord2(data.ClientConfig) ? data.ClientConfig : {};
|
|
382
|
+
const seconds = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value * 1000 : fallback;
|
|
383
|
+
return {
|
|
384
|
+
url,
|
|
385
|
+
serviceId,
|
|
386
|
+
pingMs: seconds(config.PingInterval, DEFAULT_PING_MS),
|
|
387
|
+
reconnectMs: seconds(config.ReconnectInterval, DEFAULT_RECONNECT_MS),
|
|
388
|
+
reconnectNonceMs: seconds(config.ReconnectNonce, DEFAULT_NONCE_MS)
|
|
389
|
+
};
|
|
38
390
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
391
|
+
|
|
392
|
+
class FeishuLiveConnection {
|
|
393
|
+
#options;
|
|
394
|
+
#fragments = new Map;
|
|
395
|
+
#socket;
|
|
396
|
+
#discovered;
|
|
397
|
+
#pingTimer;
|
|
398
|
+
#reconnectTimer;
|
|
399
|
+
#stopped = false;
|
|
400
|
+
#connecting = false;
|
|
401
|
+
#attempts = 0;
|
|
402
|
+
constructor(options) {
|
|
403
|
+
this.#options = options;
|
|
404
|
+
}
|
|
405
|
+
async start() {
|
|
406
|
+
this.#stopped = false;
|
|
407
|
+
this.#discovered = await discovery(this.#options);
|
|
408
|
+
await this.#connect();
|
|
409
|
+
this.#options.log(`inbound long connection ready service=${this.#discovered.serviceId}`);
|
|
410
|
+
}
|
|
411
|
+
async stop() {
|
|
412
|
+
this.#stopped = true;
|
|
413
|
+
if (this.#pingTimer)
|
|
414
|
+
clearTimeout(this.#pingTimer);
|
|
415
|
+
if (this.#reconnectTimer)
|
|
416
|
+
clearTimeout(this.#reconnectTimer);
|
|
417
|
+
this.#pingTimer = undefined;
|
|
418
|
+
this.#reconnectTimer = undefined;
|
|
419
|
+
for (const fragment of this.#fragments.values())
|
|
420
|
+
clearTimeout(fragment.timer);
|
|
421
|
+
this.#fragments.clear();
|
|
422
|
+
const socket = this.#socket;
|
|
423
|
+
this.#socket = undefined;
|
|
424
|
+
if (socket) {
|
|
425
|
+
try {
|
|
426
|
+
socket.close();
|
|
427
|
+
} catch {}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
#connect() {
|
|
431
|
+
const factory = this.#options.socketFactory;
|
|
432
|
+
const Ctor = factory ? undefined : globalThis.WebSocket;
|
|
433
|
+
if (!factory && !Ctor) {
|
|
434
|
+
return Promise.reject(new Error("feishu long connection requires a WebSocket client"));
|
|
435
|
+
}
|
|
436
|
+
const discovered = this.#discovered;
|
|
437
|
+
if (!discovered)
|
|
438
|
+
return Promise.reject(new Error("feishu long connection is not discovered"));
|
|
439
|
+
const create = factory ?? ((url) => new Ctor(url));
|
|
440
|
+
return new Promise((resolve, reject) => {
|
|
441
|
+
const socket = create(discovered.url);
|
|
442
|
+
socket.binaryType = "arraybuffer";
|
|
443
|
+
let settled = false;
|
|
444
|
+
const timer = setTimeout(() => {
|
|
445
|
+
if (settled)
|
|
446
|
+
return;
|
|
447
|
+
settled = true;
|
|
448
|
+
try {
|
|
449
|
+
socket.close();
|
|
450
|
+
} catch {}
|
|
451
|
+
reject(new Error("feishu long connection timed out"));
|
|
452
|
+
}, CONNECT_TIMEOUT_MS);
|
|
453
|
+
socket.addEventListener("open", () => {
|
|
454
|
+
if (settled)
|
|
455
|
+
return;
|
|
456
|
+
settled = true;
|
|
457
|
+
clearTimeout(timer);
|
|
458
|
+
if (this.#stopped) {
|
|
459
|
+
try {
|
|
460
|
+
socket.close();
|
|
461
|
+
} catch {}
|
|
462
|
+
reject(new Error("feishu long connection stopped"));
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
this.#attempts = 0;
|
|
466
|
+
this.#socket = socket;
|
|
467
|
+
this.#attach(socket);
|
|
468
|
+
this.#ping();
|
|
469
|
+
resolve();
|
|
470
|
+
});
|
|
471
|
+
socket.addEventListener("error", () => {
|
|
472
|
+
if (settled)
|
|
473
|
+
return;
|
|
474
|
+
settled = true;
|
|
475
|
+
clearTimeout(timer);
|
|
476
|
+
reject(new Error("feishu long connection failed"));
|
|
477
|
+
});
|
|
478
|
+
socket.addEventListener("close", () => {
|
|
479
|
+
if (settled)
|
|
480
|
+
return;
|
|
481
|
+
settled = true;
|
|
482
|
+
clearTimeout(timer);
|
|
483
|
+
reject(new Error("feishu long connection closed during handshake"));
|
|
484
|
+
});
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
#attach(socket) {
|
|
488
|
+
socket.addEventListener("message", (event) => {
|
|
489
|
+
this.#onSocketMessage(event.data).catch((error) => {
|
|
490
|
+
this.#options.log(`inbound frame failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
491
|
+
});
|
|
492
|
+
});
|
|
493
|
+
socket.addEventListener("error", () => {
|
|
494
|
+
this.#options.log("inbound socket error");
|
|
495
|
+
});
|
|
496
|
+
socket.addEventListener("close", () => {
|
|
497
|
+
if (this.#socket !== socket)
|
|
498
|
+
return;
|
|
499
|
+
this.#socket = undefined;
|
|
500
|
+
if (this.#pingTimer)
|
|
501
|
+
clearTimeout(this.#pingTimer);
|
|
502
|
+
this.#pingTimer = undefined;
|
|
503
|
+
this.#scheduleReconnect();
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
async#onSocketMessage(data) {
|
|
507
|
+
let bytes;
|
|
508
|
+
if (data instanceof ArrayBuffer)
|
|
509
|
+
bytes = new Uint8Array(data);
|
|
510
|
+
else if (ArrayBuffer.isView(data))
|
|
511
|
+
bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
512
|
+
else if (typeof Blob !== "undefined" && data instanceof Blob)
|
|
513
|
+
bytes = new Uint8Array(await data.arrayBuffer());
|
|
514
|
+
else
|
|
515
|
+
return;
|
|
516
|
+
const frame = decodeFrame(bytes);
|
|
517
|
+
if (frame.method === 0) {
|
|
518
|
+
this.#onControl(frame);
|
|
51
519
|
return;
|
|
52
|
-
try {
|
|
53
|
-
onMessage(parseFrame(text));
|
|
54
|
-
} catch (error) {
|
|
55
|
-
onError(error instanceof Error ? error : new Error(String(error)));
|
|
56
520
|
}
|
|
57
|
-
|
|
58
|
-
const consume = (segment) => {
|
|
59
|
-
const decoded = decoder.write(segment);
|
|
60
|
-
if (discarding)
|
|
521
|
+
if (frame.method !== 1)
|
|
61
522
|
return;
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
523
|
+
const type = headerValue(frame, "type");
|
|
524
|
+
if (type !== "event")
|
|
525
|
+
return;
|
|
526
|
+
const payload = this.#assemble(frame);
|
|
527
|
+
if (!payload)
|
|
67
528
|
return;
|
|
529
|
+
const text = new TextDecoder().decode(payload);
|
|
530
|
+
let ok = false;
|
|
531
|
+
try {
|
|
532
|
+
ok = await this.#options.onEvent(text);
|
|
533
|
+
} catch {
|
|
534
|
+
ok = false;
|
|
68
535
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
if (newline === -1)
|
|
536
|
+
this.#ack(frame, ok ? 200 : 500);
|
|
537
|
+
}
|
|
538
|
+
#onControl(frame) {
|
|
539
|
+
if (headerValue(frame, "type") !== "pong" || !frame.payload)
|
|
540
|
+
return;
|
|
541
|
+
try {
|
|
542
|
+
const pong = JSON.parse(new TextDecoder().decode(frame.payload));
|
|
543
|
+
const next = this.#discovered;
|
|
544
|
+
if (!next)
|
|
79
545
|
return;
|
|
80
|
-
|
|
81
|
-
|
|
546
|
+
if (typeof pong.PingInterval === "number" && pong.PingInterval > 0)
|
|
547
|
+
next.pingMs = pong.PingInterval * 1000;
|
|
548
|
+
if (typeof pong.ReconnectInterval === "number" && pong.ReconnectInterval > 0) {
|
|
549
|
+
next.reconnectMs = pong.ReconnectInterval * 1000;
|
|
550
|
+
}
|
|
551
|
+
if (typeof pong.ReconnectNonce === "number" && pong.ReconnectNonce > 0) {
|
|
552
|
+
next.reconnectNonceMs = pong.ReconnectNonce * 1000;
|
|
553
|
+
}
|
|
554
|
+
} catch {}
|
|
555
|
+
}
|
|
556
|
+
#assemble(frame) {
|
|
557
|
+
const id = headerValue(frame, "message_id");
|
|
558
|
+
const total = Number(headerValue(frame, "sum") ?? "1");
|
|
559
|
+
const seq = Number(headerValue(frame, "seq") ?? "0");
|
|
560
|
+
if (!id || !frame.payload || !Number.isInteger(total) || total <= 1)
|
|
561
|
+
return frame.payload;
|
|
562
|
+
if (!Number.isInteger(seq) || seq < 0 || seq >= total)
|
|
563
|
+
return;
|
|
564
|
+
const current = this.#fragments.get(id) ?? {
|
|
565
|
+
parts: Array.from({ length: total }),
|
|
566
|
+
received: 0,
|
|
567
|
+
timer: setTimeout(() => this.#fragments.delete(id), FRAGMENT_TTL_MS)
|
|
568
|
+
};
|
|
569
|
+
if (current.parts.length !== total)
|
|
570
|
+
return;
|
|
571
|
+
if (!current.parts[seq]) {
|
|
572
|
+
current.parts[seq] = frame.payload;
|
|
573
|
+
current.received += 1;
|
|
82
574
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
super(message);
|
|
90
|
-
this.name = "AdapterGoneError";
|
|
575
|
+
this.#fragments.set(id, current);
|
|
576
|
+
if (current.received < total)
|
|
577
|
+
return;
|
|
578
|
+
clearTimeout(current.timer);
|
|
579
|
+
this.#fragments.delete(id);
|
|
580
|
+
return Uint8Array.from(current.parts.flatMap((part) => [...part ?? []]));
|
|
91
581
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
582
|
+
#ack(frame, code) {
|
|
583
|
+
const socket = this.#socket;
|
|
584
|
+
if (!socket)
|
|
585
|
+
return;
|
|
586
|
+
const ack = {
|
|
587
|
+
...frame,
|
|
588
|
+
headers: [...frame.headers ?? [], { key: "biz_rt", value: "0" }],
|
|
589
|
+
payload: jsonPayload({ code })
|
|
590
|
+
};
|
|
591
|
+
try {
|
|
592
|
+
socket.send(encodeFrame(ack));
|
|
593
|
+
} catch {
|
|
594
|
+
this.#options.log("inbound ack failed");
|
|
595
|
+
}
|
|
103
596
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
597
|
+
#ping() {
|
|
598
|
+
if (this.#stopped || !this.#discovered)
|
|
599
|
+
return;
|
|
600
|
+
const socket = this.#socket;
|
|
601
|
+
if (!socket)
|
|
602
|
+
return;
|
|
603
|
+
try {
|
|
604
|
+
socket.send(encodeFrame({
|
|
605
|
+
SeqID: 0,
|
|
606
|
+
LogID: 0,
|
|
607
|
+
service: this.#discovered.serviceId,
|
|
608
|
+
method: 0,
|
|
609
|
+
headers: [{ key: "type", value: "ping" }]
|
|
610
|
+
}));
|
|
611
|
+
} catch {
|
|
612
|
+
this.#options.log("inbound ping failed");
|
|
613
|
+
}
|
|
614
|
+
this.#pingTimer = setTimeout(() => this.#ping(), this.#discovered.pingMs);
|
|
107
615
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
616
|
+
#scheduleReconnect() {
|
|
617
|
+
if (this.#stopped || this.#connecting)
|
|
618
|
+
return;
|
|
619
|
+
this.#connecting = true;
|
|
620
|
+
const next = this.#discovered;
|
|
621
|
+
const delay = (next?.reconnectNonceMs ?? DEFAULT_NONCE_MS) * Math.random() + (next?.reconnectMs ?? DEFAULT_RECONNECT_MS);
|
|
622
|
+
this.#options.log(`inbound reconnecting in ${Math.round(delay)}ms`);
|
|
623
|
+
this.#reconnectTimer = setTimeout(() => {
|
|
624
|
+
this.#reconnect();
|
|
625
|
+
}, delay);
|
|
112
626
|
}
|
|
113
|
-
|
|
114
|
-
|
|
627
|
+
async#reconnect() {
|
|
628
|
+
this.#connecting = false;
|
|
629
|
+
if (this.#stopped)
|
|
630
|
+
return;
|
|
631
|
+
this.#attempts += 1;
|
|
115
632
|
try {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
});
|
|
633
|
+
this.#discovered = await discovery(this.#options);
|
|
634
|
+
if (this.#stopped)
|
|
635
|
+
return;
|
|
636
|
+
await this.#connect();
|
|
637
|
+
this.#options.log(`inbound reconnected attempt=${this.#attempts}`);
|
|
122
638
|
} catch (error) {
|
|
123
|
-
|
|
639
|
+
this.#options.log(`inbound reconnect failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
640
|
+
this.#scheduleReconnect();
|
|
124
641
|
}
|
|
125
|
-
}
|
|
642
|
+
}
|
|
126
643
|
}
|
|
127
644
|
|
|
128
|
-
// packages/chat-room-channeld/src/feishu-
|
|
129
|
-
|
|
130
|
-
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
645
|
+
// packages/chat-room-channeld/src/feishu-send.ts
|
|
646
|
+
import { createHash } from "node:crypto";
|
|
131
647
|
var DEFAULT_RATE_LIMIT_MS = 1000;
|
|
132
648
|
var TOKEN_REFRESH_MARGIN_MS = 30 * 60000;
|
|
133
649
|
var FALLBACK_TOKEN_TTL_SECONDS = 7200;
|
|
@@ -147,10 +663,10 @@ class FeishuApiError extends Error {
|
|
|
147
663
|
scope;
|
|
148
664
|
constructor(code, msg, scope) {
|
|
149
665
|
super(`feishu ${scope} code ${code}: ${msg}`);
|
|
666
|
+
this.name = "FeishuApiError";
|
|
150
667
|
this.code = code;
|
|
151
668
|
this.msg = msg;
|
|
152
669
|
this.scope = scope;
|
|
153
|
-
this.name = "FeishuApiError";
|
|
154
670
|
}
|
|
155
671
|
}
|
|
156
672
|
function logLine(accountId, message) {
|
|
@@ -159,25 +675,9 @@ function logLine(accountId, message) {
|
|
|
159
675
|
function deterministicUuid(idempotencyKey) {
|
|
160
676
|
return createHash("sha256").update(idempotencyKey).digest("hex").slice(0, 32);
|
|
161
677
|
}
|
|
162
|
-
function
|
|
678
|
+
function isRecord3(value) {
|
|
163
679
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
164
680
|
}
|
|
165
|
-
function configFromEnv(env) {
|
|
166
|
-
const appId = env.FEISHU_APP_ID;
|
|
167
|
-
const appSecret = env.FEISHU_APP_SECRET;
|
|
168
|
-
const missing = [];
|
|
169
|
-
if (!appId)
|
|
170
|
-
missing.push("FEISHU_APP_ID");
|
|
171
|
-
if (!appSecret)
|
|
172
|
-
missing.push("FEISHU_APP_SECRET");
|
|
173
|
-
if (!appId || !appSecret) {
|
|
174
|
-
return { error: `feishu adapter requires ${missing.join(" and ")}` };
|
|
175
|
-
}
|
|
176
|
-
const timeout = Number(env.FEISHU_HTTP_TIMEOUT_MS);
|
|
177
|
-
const timeoutMs = Number.isInteger(timeout) && timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS;
|
|
178
|
-
const baseUrl = (env.FEISHU_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
179
|
-
return { appId, appSecret, baseUrl, timeoutMs };
|
|
180
|
-
}
|
|
181
681
|
async function fetchJson(url, init, timeoutMs) {
|
|
182
682
|
const controller = new AbortController;
|
|
183
683
|
let timedOut = false;
|
|
@@ -212,7 +712,7 @@ async function requestToken(config) {
|
|
|
212
712
|
body: JSON.stringify({ app_id: config.appId, app_secret: config.appSecret })
|
|
213
713
|
}, config.timeoutMs);
|
|
214
714
|
const body = raw.body;
|
|
215
|
-
if (!
|
|
715
|
+
if (!isRecord3(body) || typeof body.code !== "number") {
|
|
216
716
|
throw new Error("feishu token response was malformed");
|
|
217
717
|
}
|
|
218
718
|
if (body.code !== 0) {
|
|
@@ -272,7 +772,7 @@ function parseRetryAfter(value) {
|
|
|
272
772
|
return DEFAULT_RATE_LIMIT_MS;
|
|
273
773
|
}
|
|
274
774
|
function apiCode(raw) {
|
|
275
|
-
return
|
|
775
|
+
return isRecord3(raw.body) && typeof raw.body.code === "number" ? raw.body.code : undefined;
|
|
276
776
|
}
|
|
277
777
|
function isApiFailure(raw) {
|
|
278
778
|
const code = apiCode(raw);
|
|
@@ -280,8 +780,8 @@ function isApiFailure(raw) {
|
|
|
280
780
|
}
|
|
281
781
|
var CLIENT_ERROR_STATUSES = new Set([400, 401, 403, 404]);
|
|
282
782
|
function apiResponseDetail(body, status) {
|
|
283
|
-
const code =
|
|
284
|
-
const msg =
|
|
783
|
+
const code = isRecord3(body) && typeof body.code === "number" ? body.code : undefined;
|
|
784
|
+
const msg = isRecord3(body) && typeof body.msg === "string" ? body.msg : "";
|
|
285
785
|
if (code !== undefined && code !== 0)
|
|
286
786
|
return msg ? `feishu code ${code}: ${msg}` : `feishu code ${code}`;
|
|
287
787
|
return `feishu http ${status}`;
|
|
@@ -305,11 +805,11 @@ function mapSendResponse(raw, endpoint) {
|
|
|
305
805
|
if (CLIENT_ERROR_STATUSES.has(raw.status)) {
|
|
306
806
|
return { state: "permanent", detail: apiResponseDetail(body, raw.status) };
|
|
307
807
|
}
|
|
308
|
-
if (!
|
|
808
|
+
if (!isRecord3(body) || typeof body.code !== "number") {
|
|
309
809
|
return { state: "unknown", detail: "feishu response was malformed" };
|
|
310
810
|
}
|
|
311
811
|
if (body.code === 0) {
|
|
312
|
-
const data =
|
|
812
|
+
const data = isRecord3(body.data) ? body.data : undefined;
|
|
313
813
|
const messageId = data && typeof data.message_id === "string" ? data.message_id : undefined;
|
|
314
814
|
if (raw.status >= 200 && raw.status < 300 && messageId) {
|
|
315
815
|
return { state: "sent", providerMessage: { endpoint, nativeMessageId: messageId } };
|
|
@@ -319,8 +819,22 @@ function mapSendResponse(raw, endpoint) {
|
|
|
319
819
|
const msg = typeof body.msg === "string" ? body.msg : "";
|
|
320
820
|
return { state: "permanent", detail: msg ? `feishu code ${body.code}: ${msg}` : `feishu code ${body.code}` };
|
|
321
821
|
}
|
|
322
|
-
function
|
|
323
|
-
|
|
822
|
+
function replyParentId(payload, accountId) {
|
|
823
|
+
if (!isRecord3(payload) || !isRecord3(payload.parent))
|
|
824
|
+
return;
|
|
825
|
+
const parent = payload.parent;
|
|
826
|
+
if (!isRecord3(parent.endpoint))
|
|
827
|
+
return;
|
|
828
|
+
if (parent.endpoint.platform !== "feishu")
|
|
829
|
+
return;
|
|
830
|
+
if (typeof parent.endpoint.accountId === "string" && parent.endpoint.accountId !== accountId) {
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
return typeof parent.nativeMessageId === "string" && parent.nativeMessageId ? parent.nativeMessageId : undefined;
|
|
834
|
+
}
|
|
835
|
+
function postMessage(config, token, body, replyTo) {
|
|
836
|
+
const path = replyTo ? `/open-apis/im/v1/messages/${encodeURIComponent(replyTo)}/reply` : "/open-apis/im/v1/messages?receive_id_type=chat_id";
|
|
837
|
+
return fetchJson(`${config.baseUrl}${path}`, {
|
|
324
838
|
method: "POST",
|
|
325
839
|
headers: {
|
|
326
840
|
Authorization: `Bearer ${token}`,
|
|
@@ -334,35 +848,33 @@ async function sendMessage(config, state, params) {
|
|
|
334
848
|
const chatId = target && typeof target.roomId === "string" && target.roomId ? target.roomId : target && typeof target.room === "string" ? target.room : undefined;
|
|
335
849
|
if (!chatId)
|
|
336
850
|
return { state: "permanent", detail: "send target requires a room" };
|
|
337
|
-
const text =
|
|
851
|
+
const text = isRecord3(params.payload) && typeof params.payload.text === "string" ? params.payload.text : undefined;
|
|
338
852
|
if (text === undefined)
|
|
339
853
|
return { state: "permanent", detail: "send payload.text must be a string" };
|
|
340
854
|
if (typeof params.idempotencyKey !== "string" || params.idempotencyKey.length === 0) {
|
|
341
855
|
return { state: "permanent", detail: "send requires an idempotency key" };
|
|
342
856
|
}
|
|
343
857
|
const endpoint = target;
|
|
344
|
-
const card =
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
};
|
|
348
|
-
const body = JSON.stringify({
|
|
349
|
-
receive_id: chatId,
|
|
858
|
+
const card = buildCard(config.cardVersion, text);
|
|
859
|
+
const parentId = replyParentId(params.payload, state.accountId);
|
|
860
|
+
const message = {
|
|
350
861
|
msg_type: "interactive",
|
|
351
862
|
content: JSON.stringify(card),
|
|
352
863
|
uuid: deterministicUuid(params.idempotencyKey)
|
|
353
|
-
}
|
|
864
|
+
};
|
|
865
|
+
const body = JSON.stringify(parentId ? message : { receive_id: chatId, ...message });
|
|
354
866
|
let token;
|
|
355
867
|
let raw;
|
|
356
868
|
try {
|
|
357
869
|
token = await ensureToken(config, state);
|
|
358
|
-
raw = await postMessage(config, token, body);
|
|
870
|
+
raw = await postMessage(config, token, body, parentId);
|
|
359
871
|
} catch (error) {
|
|
360
872
|
return failureReceipt(error);
|
|
361
873
|
}
|
|
362
874
|
if (raw.status !== 429 && raw.status < 500 && apiCode(raw) === TOKEN_INVALID_CODE) {
|
|
363
875
|
try {
|
|
364
876
|
token = await ensureToken(config, state, true);
|
|
365
|
-
raw = await postMessage(config, token, body);
|
|
877
|
+
raw = await postMessage(config, token, body, parentId);
|
|
366
878
|
} catch (error) {
|
|
367
879
|
return failureReceipt(error);
|
|
368
880
|
}
|
|
@@ -382,22 +894,248 @@ function startupFailureDetail(error) {
|
|
|
382
894
|
const code = errorCode(error);
|
|
383
895
|
return code ? `feishu token request failed (${code})` : "feishu token request failed";
|
|
384
896
|
}
|
|
897
|
+
|
|
898
|
+
// packages/chat-room-channeld/src/framing.ts
|
|
899
|
+
import { StringDecoder } from "node:string_decoder";
|
|
900
|
+
|
|
901
|
+
// packages/chat-room-channeld/src/protocol.ts
|
|
902
|
+
var PROTOCOL_VERSION = 1;
|
|
903
|
+
var EVENT_SCHEMA_VERSION = 1;
|
|
904
|
+
var MAX_FRAME_BYTES = 1048576;
|
|
905
|
+
var ADAPTER_ID_PREFIX = "adapter-";
|
|
906
|
+
var RPC_METHOD_NOT_FOUND = -32601;
|
|
907
|
+
var RPC_INTERNAL_ERROR = -32603;
|
|
908
|
+
function adapterRequestId(sequence) {
|
|
909
|
+
return `${ADAPTER_ID_PREFIX}${sequence}`;
|
|
910
|
+
}
|
|
911
|
+
function rpcRequest(id, method, params) {
|
|
912
|
+
return params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
|
|
913
|
+
}
|
|
914
|
+
function rpcResult(id, result) {
|
|
915
|
+
return { jsonrpc: "2.0", id, result };
|
|
916
|
+
}
|
|
917
|
+
function rpcError(id, code, message, data) {
|
|
918
|
+
const error = data === undefined ? { code, message } : { code, message, data };
|
|
919
|
+
return { jsonrpc: "2.0", id, error };
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// packages/chat-room-channeld/src/framing.ts
|
|
923
|
+
function parseFrame(line) {
|
|
924
|
+
const text = line.trim();
|
|
925
|
+
if (!text)
|
|
926
|
+
throw new Error("empty frame");
|
|
927
|
+
let value;
|
|
928
|
+
try {
|
|
929
|
+
value = JSON.parse(text);
|
|
930
|
+
} catch (error) {
|
|
931
|
+
throw new Error(`invalid JSON frame: ${error instanceof Error ? error.message : String(error)}`);
|
|
932
|
+
}
|
|
933
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
934
|
+
throw new Error("frame must be a JSON object");
|
|
935
|
+
}
|
|
936
|
+
return value;
|
|
937
|
+
}
|
|
938
|
+
function createFrameReader(onMessage, onError) {
|
|
939
|
+
const decoder = new StringDecoder("utf8");
|
|
940
|
+
let parts = [];
|
|
941
|
+
let bytes = 0;
|
|
942
|
+
let discarding = false;
|
|
943
|
+
const dispatch = () => {
|
|
944
|
+
const text = discarding ? "" : parts.join("");
|
|
945
|
+
const wasDiscarding = discarding;
|
|
946
|
+
parts = [];
|
|
947
|
+
bytes = 0;
|
|
948
|
+
discarding = false;
|
|
949
|
+
if (wasDiscarding || !text.trim())
|
|
950
|
+
return;
|
|
951
|
+
try {
|
|
952
|
+
onMessage(parseFrame(text));
|
|
953
|
+
} catch (error) {
|
|
954
|
+
onError(error instanceof Error ? error : new Error(String(error)));
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
const consume = (segment) => {
|
|
958
|
+
const decoded = decoder.write(segment);
|
|
959
|
+
if (discarding)
|
|
960
|
+
return;
|
|
961
|
+
if (bytes + segment.length > MAX_FRAME_BYTES) {
|
|
962
|
+
parts = [];
|
|
963
|
+
bytes = 0;
|
|
964
|
+
discarding = true;
|
|
965
|
+
onError(new Error(`frame exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES} bytes)`));
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
bytes += segment.length;
|
|
969
|
+
parts.push(decoded);
|
|
970
|
+
};
|
|
971
|
+
return (chunk) => {
|
|
972
|
+
let start = 0;
|
|
973
|
+
while (start <= chunk.length) {
|
|
974
|
+
const newline = chunk.indexOf(10, start);
|
|
975
|
+
const end = newline === -1 ? chunk.length : newline;
|
|
976
|
+
consume(chunk.subarray(start, end));
|
|
977
|
+
if (newline === -1)
|
|
978
|
+
return;
|
|
979
|
+
dispatch();
|
|
980
|
+
start = newline + 1;
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
class AdapterGoneError extends Error {
|
|
986
|
+
code = "ADAPTER_GONE";
|
|
987
|
+
constructor(message) {
|
|
988
|
+
super(message);
|
|
989
|
+
this.name = "AdapterGoneError";
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
var GONE_CODES = new Set(["EPIPE", "ERR_STREAM_DESTROYED", "ERR_STREAM_WRITE_AFTER_END"]);
|
|
993
|
+
function writeError(error) {
|
|
994
|
+
const code = error?.code;
|
|
995
|
+
if (code && GONE_CODES.has(code))
|
|
996
|
+
return new AdapterGoneError(`adapter stream is gone (${code})`);
|
|
997
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
998
|
+
}
|
|
999
|
+
function writeFrame(stream, value) {
|
|
1000
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1001
|
+
throw new TypeError("frame must be a JSON object");
|
|
1002
|
+
}
|
|
1003
|
+
const writable = stream;
|
|
1004
|
+
if (writable.destroyed || writable.writableEnded) {
|
|
1005
|
+
throw new AdapterGoneError("adapter stream is closed");
|
|
1006
|
+
}
|
|
1007
|
+
const line = `${JSON.stringify(value)}
|
|
1008
|
+
`;
|
|
1009
|
+
if (Buffer.byteLength(line, "utf8") > MAX_FRAME_BYTES) {
|
|
1010
|
+
throw new RangeError(`frame exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES} bytes)`);
|
|
1011
|
+
}
|
|
1012
|
+
return new Promise((resolve, reject) => {
|
|
1013
|
+
const fail = (error) => reject(writeError(error));
|
|
1014
|
+
try {
|
|
1015
|
+
stream.write(line, (error) => {
|
|
1016
|
+
if (error)
|
|
1017
|
+
fail(error);
|
|
1018
|
+
else
|
|
1019
|
+
resolve();
|
|
1020
|
+
});
|
|
1021
|
+
} catch (error) {
|
|
1022
|
+
fail(error);
|
|
1023
|
+
}
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// packages/chat-room-channeld/src/feishu-adapter.ts
|
|
1028
|
+
var DEFAULT_BASE_URL = "https://open.feishu.cn";
|
|
1029
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
1030
|
+
function logLine2(accountId, message) {
|
|
1031
|
+
console.error(`feishu adapter ${accountId}: ${message}`);
|
|
1032
|
+
}
|
|
1033
|
+
function configFromEnv(env) {
|
|
1034
|
+
const appId = env.FEISHU_APP_ID;
|
|
1035
|
+
const appSecret = env.FEISHU_APP_SECRET;
|
|
1036
|
+
const missing = [];
|
|
1037
|
+
if (!appId)
|
|
1038
|
+
missing.push("FEISHU_APP_ID");
|
|
1039
|
+
if (!appSecret)
|
|
1040
|
+
missing.push("FEISHU_APP_SECRET");
|
|
1041
|
+
if (!appId || !appSecret) {
|
|
1042
|
+
return { error: `feishu adapter requires ${missing.join(" and ")}` };
|
|
1043
|
+
}
|
|
1044
|
+
const timeout = Number(env.FEISHU_HTTP_TIMEOUT_MS);
|
|
1045
|
+
const timeoutMs = Number.isInteger(timeout) && timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS;
|
|
1046
|
+
const baseUrl = (env.FEISHU_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
1047
|
+
let cardVersion;
|
|
1048
|
+
try {
|
|
1049
|
+
cardVersion = cardVersionFromEnv(env.FEISHU_CARD_VERSION);
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
1052
|
+
}
|
|
1053
|
+
const inbound = env.FEISHU_INBOUND === "1";
|
|
1054
|
+
const inboundChats = new Set((env.FEISHU_INBOUND_CHATS ?? "").split(/[,\s]+/).map((item) => item.trim()).filter(Boolean));
|
|
1055
|
+
if (inbound && inboundChats.size === 0) {
|
|
1056
|
+
return {
|
|
1057
|
+
error: "FEISHU_INBOUND=1 requires FEISHU_INBOUND_CHATS (comma-separated group chat ids)"
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
return { appId, appSecret, baseUrl, timeoutMs, cardVersion, inbound, inboundChats };
|
|
1061
|
+
}
|
|
1062
|
+
var INGEST_TIMEOUT_MS = 5000;
|
|
1063
|
+
function emitIngest(state, event) {
|
|
1064
|
+
const id = adapterRequestId(++state.sequence);
|
|
1065
|
+
return new Promise((resolve) => {
|
|
1066
|
+
const timer = setTimeout(() => {
|
|
1067
|
+
state.pending.delete(id);
|
|
1068
|
+
logLine2(state.accountId, "inbound ingest timed out");
|
|
1069
|
+
resolve(false);
|
|
1070
|
+
}, INGEST_TIMEOUT_MS);
|
|
1071
|
+
state.pending.set(id, (result) => {
|
|
1072
|
+
clearTimeout(timer);
|
|
1073
|
+
if (result.error)
|
|
1074
|
+
logLine2(state.accountId, `inbound ingest failed: ${result.error}`);
|
|
1075
|
+
resolve(!result.error);
|
|
1076
|
+
});
|
|
1077
|
+
writeFrame(process.stdout, rpcRequest(id, "ingest", event)).catch(() => {
|
|
1078
|
+
clearTimeout(timer);
|
|
1079
|
+
state.pending.delete(id);
|
|
1080
|
+
resolve(false);
|
|
1081
|
+
});
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
async function startInbound(config, state) {
|
|
1085
|
+
const live = new FeishuLiveConnection({
|
|
1086
|
+
appId: config.appId,
|
|
1087
|
+
appSecret: config.appSecret,
|
|
1088
|
+
baseUrl: config.baseUrl,
|
|
1089
|
+
timeoutMs: config.timeoutMs,
|
|
1090
|
+
log: (message) => logLine2(state.accountId, message),
|
|
1091
|
+
onEvent: async (payload) => {
|
|
1092
|
+
const parsed = parseInboundEvent(payload, {
|
|
1093
|
+
accountId: state.accountId,
|
|
1094
|
+
appId: config.appId,
|
|
1095
|
+
chats: config.inboundChats
|
|
1096
|
+
});
|
|
1097
|
+
if (!parsed.event) {
|
|
1098
|
+
if (parsed.ignored)
|
|
1099
|
+
logLine2(state.accountId, `inbound ignored: ${parsed.ignored}`);
|
|
1100
|
+
return true;
|
|
1101
|
+
}
|
|
1102
|
+
return emitIngest(state, parsed.event);
|
|
1103
|
+
}
|
|
1104
|
+
});
|
|
1105
|
+
await live.start();
|
|
1106
|
+
state.inbound = live;
|
|
1107
|
+
await notifyInbound(state, "ready");
|
|
1108
|
+
}
|
|
1109
|
+
async function notifyInbound(state, inbound, detail) {
|
|
1110
|
+
const id = adapterRequestId(++state.sequence);
|
|
1111
|
+
const params = detail === undefined ? { inbound } : { inbound, detail };
|
|
1112
|
+
try {
|
|
1113
|
+
await writeFrame(process.stdout, rpcRequest(id, "status", params));
|
|
1114
|
+
} catch {}
|
|
1115
|
+
}
|
|
385
1116
|
async function handleRequest(message, state) {
|
|
386
1117
|
const rawId = message.id;
|
|
387
1118
|
if (rawId === undefined) {
|
|
388
1119
|
const failure = message.error;
|
|
389
1120
|
if (failure)
|
|
390
|
-
|
|
1121
|
+
logLine2(state.accountId, `request failed: ${failure.message ?? "error"}`);
|
|
391
1122
|
return;
|
|
392
1123
|
}
|
|
393
1124
|
if (typeof rawId !== "string" && typeof rawId !== "number") {
|
|
394
|
-
|
|
1125
|
+
logLine2(state.accountId, "request id must be a string or number");
|
|
395
1126
|
return;
|
|
396
1127
|
}
|
|
397
1128
|
const id = rawId;
|
|
398
1129
|
const method = message.method;
|
|
399
|
-
if (typeof method !== "string")
|
|
1130
|
+
if (typeof method !== "string") {
|
|
1131
|
+
const resolver = state.pending.get(String(id));
|
|
1132
|
+
if (resolver) {
|
|
1133
|
+
state.pending.delete(String(id));
|
|
1134
|
+
const failure = message.error;
|
|
1135
|
+
resolver(failure ? { error: failure.message ?? "host ingest failed" } : {});
|
|
1136
|
+
}
|
|
400
1137
|
return;
|
|
1138
|
+
}
|
|
401
1139
|
if (method === "initialize") {
|
|
402
1140
|
const config = configFromEnv(process.env);
|
|
403
1141
|
if ("error" in config) {
|
|
@@ -411,7 +1149,14 @@ async function handleRequest(message, state) {
|
|
|
411
1149
|
maxFrameBytes: MAX_FRAME_BYTES,
|
|
412
1150
|
accounts: {
|
|
413
1151
|
[state.accountId]: {
|
|
414
|
-
send: {
|
|
1152
|
+
send: {
|
|
1153
|
+
text: true,
|
|
1154
|
+
format: ["text", "markdown"],
|
|
1155
|
+
reply: "native",
|
|
1156
|
+
idempotency: "persistent_delivery_key",
|
|
1157
|
+
card: ["1.0", "2.0"]
|
|
1158
|
+
},
|
|
1159
|
+
...config.inbound ? { ingress: "durable_outbox" } : {}
|
|
415
1160
|
}
|
|
416
1161
|
}
|
|
417
1162
|
}));
|
|
@@ -426,13 +1171,23 @@ async function handleRequest(message, state) {
|
|
|
426
1171
|
await ensureToken(state.config, state);
|
|
427
1172
|
} catch (error) {
|
|
428
1173
|
const detail = startupFailureDetail(error);
|
|
429
|
-
|
|
1174
|
+
logLine2(state.accountId, `token validation failed: ${detail}`);
|
|
430
1175
|
await writeFrame(process.stdout, rpcError(id, RPC_INTERNAL_ERROR, detail));
|
|
431
1176
|
return;
|
|
432
1177
|
}
|
|
1178
|
+
if (state.config.inbound) {
|
|
1179
|
+
try {
|
|
1180
|
+
await startInbound(state.config, state);
|
|
1181
|
+
} catch (error) {
|
|
1182
|
+
const detail = error instanceof FeishuApiError ? startupFailureDetail(error) : error instanceof Error ? error.message : String(error);
|
|
1183
|
+
const hint = `${detail} (requires long-connection event subscription for im.message.receive_v1 and the bot in an allowlisted group)`;
|
|
1184
|
+
logLine2(state.accountId, `inbound disabled; outbound stays active: ${hint}`);
|
|
1185
|
+
await notifyInbound(state, "failed", detail);
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
433
1188
|
state.started = true;
|
|
434
1189
|
await writeFrame(process.stdout, rpcResult(id, { ready: true }));
|
|
435
|
-
|
|
1190
|
+
logLine2(state.accountId, "ready (tenant token validated)");
|
|
436
1191
|
return;
|
|
437
1192
|
}
|
|
438
1193
|
if (method === "send") {
|
|
@@ -442,9 +1197,9 @@ async function handleRequest(message, state) {
|
|
|
442
1197
|
}
|
|
443
1198
|
const receipt = await sendMessage(state.config, state, message.params ?? {});
|
|
444
1199
|
if (receipt.state === "sent" && receipt.providerMessage) {
|
|
445
|
-
|
|
1200
|
+
logLine2(state.accountId, `send succeeded native=${receipt.providerMessage.nativeMessageId}`);
|
|
446
1201
|
} else {
|
|
447
|
-
|
|
1202
|
+
logLine2(state.accountId, `send ${receipt.state}${receipt.detail ? `: ${receipt.detail}` : ""}`);
|
|
448
1203
|
}
|
|
449
1204
|
await writeFrame(process.stdout, rpcResult(id, receipt));
|
|
450
1205
|
return;
|
|
@@ -454,6 +1209,7 @@ async function handleRequest(message, state) {
|
|
|
454
1209
|
return;
|
|
455
1210
|
}
|
|
456
1211
|
if (method === "shutdown") {
|
|
1212
|
+
await state.inbound?.stop();
|
|
457
1213
|
await writeFrame(process.stdout, rpcResult(id, {}));
|
|
458
1214
|
process.exit(0);
|
|
459
1215
|
}
|
|
@@ -463,15 +1219,22 @@ function runFeishuAdapter() {
|
|
|
463
1219
|
const state = {
|
|
464
1220
|
accountId: process.env.CHANNELD_ACCOUNT_ID ?? "feishu",
|
|
465
1221
|
tokenExpiresAt: 0,
|
|
466
|
-
started: false
|
|
1222
|
+
started: false,
|
|
1223
|
+
pending: new Map,
|
|
1224
|
+
sequence: 0
|
|
467
1225
|
};
|
|
468
1226
|
const read = createFrameReader((message) => {
|
|
469
1227
|
handleRequest(message, state).catch((error) => {
|
|
470
|
-
|
|
1228
|
+
logLine2(state.accountId, `handler failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
471
1229
|
});
|
|
472
|
-
}, (error) =>
|
|
1230
|
+
}, (error) => logLine2(state.accountId, `frame error: ${error.message}`));
|
|
473
1231
|
process.stdin.on("data", (chunk) => read(chunk));
|
|
474
|
-
|
|
1232
|
+
logLine2(state.accountId, "ready on stdio");
|
|
1233
|
+
const finish = () => {
|
|
1234
|
+
state.inbound?.stop();
|
|
1235
|
+
};
|
|
1236
|
+
process.stdin.once("end", finish);
|
|
1237
|
+
process.stdin.once("close", finish);
|
|
475
1238
|
return new Promise((resolve) => {
|
|
476
1239
|
process.stdin.once("end", resolve);
|
|
477
1240
|
process.stdin.once("close", resolve);
|