dsh-netchat 0.0.0-stage → 0.3.19
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/README.md +147 -2
- package/client/client.js +696 -0
- package/cordis.patch.yml +4 -0
- package/lib/host.mjs +234 -0
- package/lib/index.js +243 -0
- package/lib/runtime.mjs +9 -0
- package/lib/shared.mjs +28 -0
- package/package.json +34 -4
- package/shared/core/client.mjs +301 -0
- package/shared/core/consts.mjs +71 -0
- package/shared/core/datadir.mjs +92 -0
- package/shared/core/feishu-frame.mjs +190 -0
- package/shared/core/feishu.mjs +878 -0
- package/shared/core/hostbridge.mjs +115 -0
- package/shared/core/netchat.mjs +2542 -0
- package/shared/core/ops.mjs +803 -0
- package/shared/core/protocol.mjs +132 -0
- package/shared/core/util.mjs +184 -0
- package/shared/core/wsstream.mjs +204 -0
- package/shared/mcp/server.mjs +212 -0
- package/shared/skills/net-chat/SKILL.md +110 -0
- package/shared/ui/panel.html +2652 -0
|
@@ -0,0 +1,878 @@
|
|
|
1
|
+
// Feishu (飞书) as this machine's owner's own channel, when they are away from the machine.
|
|
2
|
+
//
|
|
3
|
+
// This talks to Feishu directly, with no SDK and no CLI: the long connection is the WebSocket
|
|
4
|
+
// protocol the official SDK uses (handshake at /callback/ws/endpoint, protobuf frames — see
|
|
5
|
+
// feishu-frame.mjs — over a small WebSocket client in wsstream.mjs), and sending, uploading and
|
|
6
|
+
// downloading are plain HTTPS calls with a tenant token. Everything is node:*.
|
|
7
|
+
//
|
|
8
|
+
// The model: each machine binds its own owner's Feishu account (the binding is done on that
|
|
9
|
+
// machine, by its owner, for themselves). With "notify Feishu" on for a binding, what happens in
|
|
10
|
+
// the threads of tasks this machine sent — the other side's questions, messages and receipts, and
|
|
11
|
+
// what is written back — is also said in that chat, and what the owner writes there goes back
|
|
12
|
+
// into the thread. So a question can be answered from the panel or from Feishu, whichever is at
|
|
13
|
+
// hand:
|
|
14
|
+
//
|
|
15
|
+
// - A user writes to the bot in a p2p chat. The first time, that only puts them on the
|
|
16
|
+
// "pending" list: binding is explicit, done by this machine's owner (panel or tool).
|
|
17
|
+
// - When the other side asks a question in a task's thread, or sends a message, or reports
|
|
18
|
+
// progress, it is sent to the chat of every binding with notify on. A question carries its
|
|
19
|
+
// choices as a numbered list; a reply by number or by the option's text answers it in the thread.
|
|
20
|
+
// - Anything else they write goes into the thread of the open task as a supplement; with
|
|
21
|
+
// nothing open, the bridge says so rather than starting anything.
|
|
22
|
+
// - Files and images they send are downloaded next to the records and named in the message.
|
|
23
|
+
//
|
|
24
|
+
// Group chats are ignored on purpose: a group is many people, and a task has one author.
|
|
25
|
+
import { randomInt } from "node:crypto";
|
|
26
|
+
import { mkdirSync, renameSync, writeFileSync } from "node:fs";
|
|
27
|
+
import { readFile } from "node:fs/promises";
|
|
28
|
+
import { join } from "node:path";
|
|
29
|
+
|
|
30
|
+
import * as C from "./consts.mjs";
|
|
31
|
+
import { FragmentCache, MESSAGE_EVENT, MESSAGE_PING, MESSAGE_PONG, METHOD_DATA, ackFor, decodeFrame, encodeFrame, headerKeys, pingFrame } from "./feishu-frame.mjs";
|
|
32
|
+
import { NetChatError, clip, describeError, nowIso, readJson, writeJsonAtomic } from "./util.mjs";
|
|
33
|
+
import { WsConnection } from "./wsstream.mjs";
|
|
34
|
+
|
|
35
|
+
export const FEISHU_EVENT = "im.message.receive_v1";
|
|
36
|
+
export const FEISHU_FILE = "feishu.json";
|
|
37
|
+
/** Where a Feishu user appears in `from.name`; the open_id is in `from.id`. */
|
|
38
|
+
export const FEISHU_ROLE = "飞书";
|
|
39
|
+
export const FEISHU_DOMAIN = "https://open.feishu.cn";
|
|
40
|
+
const OPEN_ID = /^ou_[A-Za-z0-9]+$/;
|
|
41
|
+
const MESSAGE_ID = /^om_[A-Za-z0-9]+$/;
|
|
42
|
+
const RESOURCE_KEY = /^(img|file)_[A-Za-z0-9_]+$/;
|
|
43
|
+
const SEEN_LIMIT = 4000;
|
|
44
|
+
/** Feishu caps a file message at 30 MB; refusing before the upload saves the round trip. */
|
|
45
|
+
const MAX_UPLOAD_BYTES = 30 * 1024 * 1024;
|
|
46
|
+
const APP_ID = /^cli_[0-9a-fA-F]{16}$/;
|
|
47
|
+
/**
|
|
48
|
+
* The app this build ships with, used when the records hold no credentials of their own: a fresh
|
|
49
|
+
* installation is connected without the owner having to create an app first. Anything saved in
|
|
50
|
+
* feishu.json replaces it, and clearing it there (empty strings saved) turns the bridge off.
|
|
51
|
+
*/
|
|
52
|
+
export const DEFAULT_APP = Object.freeze({ appId: "cli_ab87a01065f89c1e", appSecret: "Uj4vZHyaCQw3Udg9ulAv7fZKi58YqyPC" });
|
|
53
|
+
|
|
54
|
+
// ---- records ------------------------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Per file, the last change still being written by this process (see FeishuBook.update): a change
|
|
58
|
+
* waits for it, so that two read-modify-write cycles on one file cannot interleave here.
|
|
59
|
+
*/
|
|
60
|
+
const writeFeishuChains = new Map();
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The records: the app credentials, whose Feishu is bound on this machine (its owner's) and
|
|
64
|
+
* whether each is told what happens in the threads, who is waiting to be, and which message ids
|
|
65
|
+
* were handled. Kept in one file next to the other records, written atomically like them. The
|
|
66
|
+
* secret never leaves this machine through any API: `publicView` reports only that there is one.
|
|
67
|
+
*/
|
|
68
|
+
export class FeishuBook {
|
|
69
|
+
constructor(dir) {
|
|
70
|
+
this.file = join(dir, FEISHU_FILE);
|
|
71
|
+
this.data = { ...DEFAULT_APP, bindings: [], pending: [], seen: [] };
|
|
72
|
+
/** Set by load() when bindings from before 0.3.4 were dropped, for the log. */
|
|
73
|
+
this.dropped = 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Reads the records as they are on disk now, replacing what this book holds.
|
|
78
|
+
*
|
|
79
|
+
* More than one process has a book on the same file: ZCode's extension and DeepSeek Harness
|
|
80
|
+
* can both run NetChat on a machine, and either may own the service, and with it the Feishu
|
|
81
|
+
* bridge, at any time. So what a book holds in memory is only what was true when it last read,
|
|
82
|
+
* and a change is applied to a fresh copy (see `update`), never written over the file from
|
|
83
|
+
* memory alone — a host whose bridge had started before the other noted a waiting person
|
|
84
|
+
* wrote its copy back, and that person's pairing code was gone (0.3.12 and before).
|
|
85
|
+
*/
|
|
86
|
+
load() {
|
|
87
|
+
const read = this.readFromDisk();
|
|
88
|
+
this.data = read.data;
|
|
89
|
+
this.dropped = read.dropped;
|
|
90
|
+
return this;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Refreshes what the book holds from the file, as `load()` does, keeping the log count. */
|
|
94
|
+
refresh() {
|
|
95
|
+
const dropped = this.dropped;
|
|
96
|
+
this.load();
|
|
97
|
+
this.dropped = dropped;
|
|
98
|
+
return this;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The records as the file has them, without touching this book. */
|
|
102
|
+
readFromDisk() {
|
|
103
|
+
const stored = readJson(this.file, null);
|
|
104
|
+
const empty = { ...DEFAULT_APP, bindings: [], pending: [], seen: [] };
|
|
105
|
+
if (!stored || typeof stored !== "object") return { data: empty, dropped: 0 };
|
|
106
|
+
const bindings = Array.isArray(stored.bindings) ? stored.bindings.filter((entry) => OPEN_ID.test(entry?.openId ?? "")) : [];
|
|
107
|
+
// Before 0.3.4 a binding was a Feishu user whose messages became tasks on this machine; that
|
|
108
|
+
// model is gone and such a binding names nobody, so it is dropped rather than half-kept.
|
|
109
|
+
// 0.3.4 bound users to a LAN agent; 0.3.5 binds them to this machine, and the agent they
|
|
110
|
+
// were bound to is simply forgotten.
|
|
111
|
+
const kept = [];
|
|
112
|
+
for (const entry of bindings) {
|
|
113
|
+
if (!entry.boundAt) continue;
|
|
114
|
+
const { agentId: _dropped, ...rest } = entry;
|
|
115
|
+
kept.push(rest);
|
|
116
|
+
}
|
|
117
|
+
// Credentials never saved at all (an older file without them) fall back to the shipped app;
|
|
118
|
+
// ones saved as empty strings are the owner's choice to have none, and stay empty.
|
|
119
|
+
const data = {
|
|
120
|
+
appId: typeof stored.appId === "string" ? stored.appId : DEFAULT_APP.appId,
|
|
121
|
+
appSecret: typeof stored.appSecret === "string" ? stored.appSecret : DEFAULT_APP.appSecret,
|
|
122
|
+
bindings: kept,
|
|
123
|
+
pending: Array.isArray(stored.pending) ? stored.pending.filter((entry) => OPEN_ID.test(entry?.openId ?? "")).map((entry) => ({ ...entry, code: typeof entry.code === "string" ? entry.code : pairingCode() })) : [],
|
|
124
|
+
seen: Array.isArray(stored.seen) ? stored.seen.filter((id) => typeof id === "string") : [],
|
|
125
|
+
};
|
|
126
|
+
return { data, dropped: bindings.length - kept.length };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
save() {
|
|
130
|
+
return writeJsonAtomic(this.file, this.data).catch((error) => console.error(`save feishu: ${describeError(error)}`));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Applies one change to the records as they are on disk now, and writes that back.
|
|
135
|
+
*
|
|
136
|
+
* `mutate(data)` alters the records it is given; whatever it returns is `update`'s result.
|
|
137
|
+
* The change is made to a fresh copy of the file, so a change another process wrote in the
|
|
138
|
+
* meantime survives it; this book then holds what was written. Writes are queued per file
|
|
139
|
+
* (`writeJsonAtomic`), and a change waits for the one before it, here and in any other book
|
|
140
|
+
* of this process, so two of them cannot interleave.
|
|
141
|
+
*/
|
|
142
|
+
async update(mutate) {
|
|
143
|
+
await writeFeishuChains.get(this.file)?.catch(() => {});
|
|
144
|
+
const read = this.readFromDisk();
|
|
145
|
+
const result = await mutate(read.data);
|
|
146
|
+
const written = writeJsonAtomic(this.file, read.data);
|
|
147
|
+
writeFeishuChains.set(this.file, written);
|
|
148
|
+
written.finally(() => {
|
|
149
|
+
if (writeFeishuChains.get(this.file) === written) writeFeishuChains.delete(this.file);
|
|
150
|
+
}, () => {});
|
|
151
|
+
await written.catch((error) => console.error(`save feishu: ${describeError(error)}`));
|
|
152
|
+
this.data = read.data;
|
|
153
|
+
this.dropped = read.dropped;
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
get configured() {
|
|
158
|
+
return APP_ID.test(this.data.appId) && this.data.appSecret.length > 0;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Sets (or clears, with empty strings) the app credentials. Returns whether they are complete. */
|
|
162
|
+
async configure({ appId, appSecret }) {
|
|
163
|
+
// Validated before anything is written: a rejected change must leave the book as it was.
|
|
164
|
+
const nextId = appId !== undefined ? String(appId ?? "").trim() : this.data.appId;
|
|
165
|
+
const nextSecret = appSecret !== undefined ? String(appSecret ?? "").trim() : this.data.appSecret;
|
|
166
|
+
if (nextId && !APP_ID.test(nextId)) {
|
|
167
|
+
throw new NetChatError("invalid_input", "App ID 应形如 cli_ 开头的 16 位十六进制");
|
|
168
|
+
}
|
|
169
|
+
return this.update((data) => {
|
|
170
|
+
data.appId = nextId;
|
|
171
|
+
data.appSecret = nextSecret;
|
|
172
|
+
return APP_ID.test(data.appId) && data.appSecret.length > 0;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
bound(openId) {
|
|
177
|
+
return this.data.bindings.find((entry) => entry.openId === openId) ?? null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Everyone bound on this machine: the owner's accounts, told when something waits on them. */
|
|
181
|
+
users() {
|
|
182
|
+
return this.data.bindings;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
waiting(openId) {
|
|
186
|
+
return this.data.pending.find((entry) => entry.openId === openId) ?? null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The pending entries a pairing code names. What the owner pastes is not necessarily the six
|
|
191
|
+
* characters and nothing else: the code comes in a message, and copying it off a phone selects
|
|
192
|
+
* the colon or the label before it, the first character of the next line, or the whole message;
|
|
193
|
+
* text copied out of Feishu can carry no-break, zero-width or ideographic spaces. So everything
|
|
194
|
+
* that is not a letter or a digit is dropped first (full-width folded to half-width, lower case
|
|
195
|
+
* raised), and a waiting code is named when it occurs in what is left — as the six characters,
|
|
196
|
+
* with gaps, or inside the message it came in.
|
|
197
|
+
*
|
|
198
|
+
* A pasted code is also read with look-alike characters treated as each other (B/8, S/5, Z/2,
|
|
199
|
+
* G/6, U/V — see LOOK_ALIKE) when the person typed it rather than pasted it. What comes back
|
|
200
|
+
* are the candidates: one means bind it, more than one means the code cannot say who is meant,
|
|
201
|
+
* and none means it names nobody.
|
|
202
|
+
*
|
|
203
|
+
* An exact match is not preferred over a look-alike one. With two people waiting whose codes
|
|
204
|
+
* differ by a look-alike pair — possible only for codes issued before 0.3.11 — a code typed
|
|
205
|
+
* exactly as one of them may be the other's, misread; preferring the exact match would bind
|
|
206
|
+
* that other person without a word. So every entry the code could name is returned, and the
|
|
207
|
+
* caller refuses the ambiguous ones.
|
|
208
|
+
*/
|
|
209
|
+
byCode(code) {
|
|
210
|
+
const pasted = lettersAndDigits(code);
|
|
211
|
+
if (!pasted) return [];
|
|
212
|
+
const folded = foldLookAlike(pasted);
|
|
213
|
+
return this.data.pending.filter((entry) => {
|
|
214
|
+
const issued = lettersAndDigits(entry.code);
|
|
215
|
+
return pasted.includes(issued) || folded.includes(foldLookAlike(issued));
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Puts a user on the pending list with a fresh pairing code, or refreshes their name if they
|
|
221
|
+
* are already there. The code is what the owner pastes into the panel to bind them: it proves
|
|
222
|
+
* the person at the panel is the one the chat is with, which the open_id alone would not.
|
|
223
|
+
* Applied to the records as they are on disk, so a person another host noted is kept.
|
|
224
|
+
*/
|
|
225
|
+
async notePending(openId, name) {
|
|
226
|
+
const firstSeenAt = nowIso();
|
|
227
|
+
return this.update((data) => {
|
|
228
|
+
const existing = data.pending.find((entry) => entry.openId === openId);
|
|
229
|
+
if (existing) {
|
|
230
|
+
if (name && existing.name !== name) existing.name = name;
|
|
231
|
+
existing.lastSeenAt = nowIso();
|
|
232
|
+
return { entry: existing, added: false };
|
|
233
|
+
}
|
|
234
|
+
// A code no one else is waiting with. Two people are never given the same one: a paste that
|
|
235
|
+
// named both could then bind neither.
|
|
236
|
+
let code = pairingCode();
|
|
237
|
+
while (data.pending.some((entry) => entry.code === code)) code = pairingCode();
|
|
238
|
+
const entry = { openId, code, name: clip(name, C.MAX_NAME_CHARS) || openId, firstSeenAt, lastSeenAt: firstSeenAt };
|
|
239
|
+
data.pending.unshift(entry);
|
|
240
|
+
return { entry, added: true };
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Binds a user to this machine: from the pairing code the bot gave them (pasted into the panel
|
|
246
|
+
* as it was copied — the code alone or with the message around it), or — for the panel's own
|
|
247
|
+
* list — from the open_id of a pending entry. Returns the binding, or null when the code names
|
|
248
|
+
* nobody waiting. Throws `ambiguous_code` when what was pasted names more than one person
|
|
249
|
+
* waiting: binding is an authorisation, and it must not go to whichever came first.
|
|
250
|
+
*
|
|
251
|
+
* The waiting list the code is looked for in is the one on disk now, so a code the other host's
|
|
252
|
+
* bridge gave a moment ago is found here.
|
|
253
|
+
*/
|
|
254
|
+
async bind({ code = "", openId = "", name = "" } = {}) {
|
|
255
|
+
const pasted = lettersAndDigits(code);
|
|
256
|
+
const folded = pasted ? foldLookAlike(pasted) : "";
|
|
257
|
+
const namedBy = (pending) => pending.filter((entry) => {
|
|
258
|
+
const issued = lettersAndDigits(entry.code);
|
|
259
|
+
return (pasted && pasted.includes(issued)) || (folded && folded.includes(foldLookAlike(issued)));
|
|
260
|
+
});
|
|
261
|
+
const outcome = await this.update((data) => {
|
|
262
|
+
const byCode = namedBy(data.pending);
|
|
263
|
+
if (byCode.length > 1) {
|
|
264
|
+
throw new NetChatError("ambiguous_code", `贴过来的内容里能对上 ${byCode.length} 个等待绑定的人的绑定码(${byCode.map((entry) => entry.name).join("、")}),分不出是哪位`, {
|
|
265
|
+
candidates: byCode.map((entry) => ({ openId: entry.openId, name: entry.name })),
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
const pending = byCode[0] ?? (openId ? data.pending.find((entry) => entry.openId === openId) ?? null : null);
|
|
269
|
+
if (!pending) return null;
|
|
270
|
+
const previous = data.bindings.find((entry) => entry.openId === pending.openId);
|
|
271
|
+
const clean = clip(String(name ?? "").trim(), C.MAX_NAME_CHARS);
|
|
272
|
+
const entry = {
|
|
273
|
+
openId: pending.openId,
|
|
274
|
+
name: clean || previous?.name || pending.name || pending.openId,
|
|
275
|
+
boundAt: previous?.boundAt ?? nowIso(),
|
|
276
|
+
lastMessageAt: previous?.lastMessageAt ?? null,
|
|
277
|
+
};
|
|
278
|
+
data.bindings = [entry, ...data.bindings.filter((item) => item.openId !== entry.openId)];
|
|
279
|
+
data.pending = data.pending.filter((item) => item.openId !== entry.openId);
|
|
280
|
+
return entry;
|
|
281
|
+
});
|
|
282
|
+
// Nothing was bound: the file was still rewritten with what it held, which is harmless, but
|
|
283
|
+
// the book's memory should say what it said.
|
|
284
|
+
if (outcome === null) this.load();
|
|
285
|
+
return outcome;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async unbind(openId) {
|
|
289
|
+
return this.update((data) => {
|
|
290
|
+
const before = data.bindings.length;
|
|
291
|
+
data.bindings = data.bindings.filter((item) => item.openId !== openId);
|
|
292
|
+
data.pending = data.pending.filter((item) => item.openId !== openId);
|
|
293
|
+
return data.bindings.length < before;
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async forgetPending(openId) {
|
|
298
|
+
return this.update((data) => {
|
|
299
|
+
const before = data.pending.length;
|
|
300
|
+
data.pending = data.pending.filter((item) => item.openId !== openId);
|
|
301
|
+
return data.pending.length < before;
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
seen(id) {
|
|
306
|
+
return this.data.seen.includes(id);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Notes a message as handled, and writes that down: another host's bridge holds the records
|
|
311
|
+
* next, and must not handle the same message again. Returns whether it was new.
|
|
312
|
+
*/
|
|
313
|
+
async remember(id) {
|
|
314
|
+
return this.update((data) => {
|
|
315
|
+
if (data.seen.includes(id)) return false;
|
|
316
|
+
data.seen.push(id);
|
|
317
|
+
if (data.seen.length > SEEN_LIMIT) data.seen.splice(0, data.seen.length - SEEN_LIMIT);
|
|
318
|
+
return true;
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Resolves an open_id, or a bound name that matches exactly one binding. */
|
|
323
|
+
resolve(query) {
|
|
324
|
+
const needle = String(query ?? "").trim();
|
|
325
|
+
if (!needle) throw new NetChatError("invalid_input", "需要飞书用户的 open_id 或已绑定的名字");
|
|
326
|
+
const byId = this.data.bindings.find((entry) => entry.openId === needle);
|
|
327
|
+
if (byId) return byId;
|
|
328
|
+
const matches = this.data.bindings.filter((entry) => entry.name === needle || entry.name.toLowerCase() === needle.toLowerCase());
|
|
329
|
+
if (matches.length === 1) return matches[0];
|
|
330
|
+
if (matches.length > 1) {
|
|
331
|
+
throw new NetChatError("ambiguous_agent", `"${needle}" 匹配到 ${matches.length} 个飞书用户`, {
|
|
332
|
+
candidates: matches.map((entry) => ({ openId: entry.openId, name: entry.name })),
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
throw new NetChatError("not_found", `"${needle}" 不是已绑定的飞书用户`, {
|
|
336
|
+
bindings: this.data.bindings.map((entry) => ({ openId: entry.openId, name: entry.name })),
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
publicView() {
|
|
341
|
+
const hide = (openId) => (openId.length > 10 ? `${openId.slice(0, 6)}…${openId.slice(-4)}` : openId);
|
|
342
|
+
return {
|
|
343
|
+
configured: this.configured,
|
|
344
|
+
appId: this.data.appId,
|
|
345
|
+
hasSecret: this.data.appSecret.length > 0,
|
|
346
|
+
bindings: this.data.bindings.map((entry) => ({ openId: entry.openId, maskedOpenId: hide(entry.openId), name: entry.name, boundAt: entry.boundAt, lastMessageAt: entry.lastMessageAt })),
|
|
347
|
+
pending: this.data.pending.map((entry) => ({ openId: entry.openId, maskedOpenId: hide(entry.openId), name: entry.name, code: entry.code, firstSeenAt: entry.firstSeenAt })),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Characters that read as each other off a screen, as pairs: the first is what a code is made
|
|
354
|
+
* of, the second is what it gets typed as. Codes used to be drawn from an alphabet with both
|
|
355
|
+
* of each pair in it, and a code with at least one of these characters came up 89% of the time;
|
|
356
|
+
* the match was exact, so one misread character was "this code is wrong or has expired", and
|
|
357
|
+
* binding took several tries (reported: the fourth).
|
|
358
|
+
*/
|
|
359
|
+
const LOOK_ALIKE = Object.freeze([["B", "8"], ["S", "5"], ["Z", "2"], ["G", "6"], ["U", "V"]]);
|
|
360
|
+
/** Letters and digits left out altogether, each for reading as another one. */
|
|
361
|
+
const UNREADABLE = "IO01";
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* The characters a pairing code is made of: capital letters and digits, without the unreadable
|
|
365
|
+
* ones and with only the first of each look-alike pair, so that no two characters of a code can
|
|
366
|
+
* be mistaken for each other. Derived from the two tables above rather than written out, so it
|
|
367
|
+
* cannot drift from them.
|
|
368
|
+
*/
|
|
369
|
+
const CODE_ALPHABET = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"].filter((character) => !UNREADABLE.includes(character) && !LOOK_ALIKE.some(([, misread]) => misread === character)).join("");
|
|
370
|
+
|
|
371
|
+
/** A code with every look-alike character replaced by the first of its pair: what it reads as. */
|
|
372
|
+
export function foldLookAlike(code) {
|
|
373
|
+
const fold = new Map(LOOK_ALIKE.flatMap(([kept, misread]) => [
|
|
374
|
+
[kept, kept],
|
|
375
|
+
[misread, kept],
|
|
376
|
+
]));
|
|
377
|
+
return [...String(code ?? "")].map((character) => fold.get(character) ?? character).join("");
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* What is left of a text once everything that is not a letter or a digit is gone: the code
|
|
382
|
+
* without the spaces, punctuation and line breaks that came along with it. Full-width letters
|
|
383
|
+
* and digits (as a CJK input method or a rich-text copy produces) fold to their half-width
|
|
384
|
+
* forms first, and lower case is raised.
|
|
385
|
+
*/
|
|
386
|
+
export function lettersAndDigits(text) {
|
|
387
|
+
return String(text ?? "").normalize("NFKC").toUpperCase().replace(/[^A-Z0-9]/g, "");
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** A short code the owner can read off Feishu and type into the panel: no confusing characters. */
|
|
391
|
+
function pairingCode() {
|
|
392
|
+
let code = "";
|
|
393
|
+
for (let i = 0; i < 6; i += 1) code += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
|
|
394
|
+
return code;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// ---- event content ------------------------------------------------------------------------------
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Parses the `content` of a message event. In the raw event `content` is a JSON string for
|
|
401
|
+
* every type: `{"text": …}` for text, `{"title","content":[…]}` for post, `{"file_key","file_name"}`
|
|
402
|
+
* for a file, `{"image_key"}` for an image. Returns readable text plus any resource to fetch.
|
|
403
|
+
*/
|
|
404
|
+
export function parseContent(messageType, content) {
|
|
405
|
+
if (typeof content !== "string" || !content.trim()) return { text: "", resources: [] };
|
|
406
|
+
let parsed = null;
|
|
407
|
+
try {
|
|
408
|
+
parsed = JSON.parse(content);
|
|
409
|
+
} catch {
|
|
410
|
+
return { text: content.trim(), resources: [] };
|
|
411
|
+
}
|
|
412
|
+
if (!parsed || typeof parsed !== "object") return { text: content.trim(), resources: [] };
|
|
413
|
+
|
|
414
|
+
const key = parsed.file_key ?? parsed.image_key;
|
|
415
|
+
const name = parsed.file_name ?? "";
|
|
416
|
+
// A file names `file_key`; an image (and a sticker, which is an image) names `image_key`.
|
|
417
|
+
const type = parsed.image_key ? "image" : parsed.file_key ? (/^img_/.test(parsed.file_key) || messageType === "image" || messageType === "sticker" ? "image" : "file") : null;
|
|
418
|
+
const resources = key && RESOURCE_KEY.test(key) && type ? [{ key, type, name: typeof name === "string" ? name : "" }] : [];
|
|
419
|
+
|
|
420
|
+
// Rich text (post) is a title plus paragraphs of segments; flatten what is readable.
|
|
421
|
+
const postText = () => {
|
|
422
|
+
const lines = [];
|
|
423
|
+
if (typeof parsed.title === "string" && parsed.title.trim()) lines.push(parsed.title.trim());
|
|
424
|
+
const paragraphs = Array.isArray(parsed.content) ? parsed.content : Object.values(parsed.content ?? {}).flat();
|
|
425
|
+
for (const paragraph of Array.isArray(paragraphs) ? paragraphs : []) {
|
|
426
|
+
const line = (Array.isArray(paragraph) ? paragraph : [])
|
|
427
|
+
.map((segment) => (typeof segment?.text === "string" ? segment.text : typeof segment?.user_id === "string" ? `@${segment.user_id}` : ""))
|
|
428
|
+
.join("");
|
|
429
|
+
if (line.trim()) lines.push(line);
|
|
430
|
+
}
|
|
431
|
+
return lines.join("\n").trim();
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
const text =
|
|
435
|
+
typeof parsed.text === "string"
|
|
436
|
+
? parsed.text.trim()
|
|
437
|
+
: messageType === "post"
|
|
438
|
+
? postText()
|
|
439
|
+
: [parsed.title, parsed.caption].filter((part) => typeof part === "string" && part.trim()).join("\n").trim();
|
|
440
|
+
return { text, resources };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** Text of a question as the user reads it in Feishu, with the choices numbered. */
|
|
444
|
+
export function questionText(task, question) {
|
|
445
|
+
const lines = [question.text];
|
|
446
|
+
if (question.options?.length) {
|
|
447
|
+
lines.push("", "回复编号或原文:");
|
|
448
|
+
question.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
449
|
+
}
|
|
450
|
+
return lines.join("\n");
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Matches a user's reply to a numbered choice; a plain number picks that option. */
|
|
454
|
+
export function optionByText(text, options) {
|
|
455
|
+
const needle = String(text ?? "").trim();
|
|
456
|
+
if (!needle || !options?.length) return null;
|
|
457
|
+
const exact = options.find((option) => option.trim().toLowerCase() === needle.toLowerCase());
|
|
458
|
+
if (exact) return exact;
|
|
459
|
+
if (/^\d{1,2}$/.test(needle)) {
|
|
460
|
+
const index = Number(needle) - 1;
|
|
461
|
+
if (index >= 0 && index < options.length) return options[index];
|
|
462
|
+
}
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** The message types whose content can be turned into a file message's upload type. */
|
|
467
|
+
const FILE_TYPES = new Map([
|
|
468
|
+
["pdf", "pdf"], ["doc", "doc"], ["docx", "doc"], ["xls", "xls"], ["xlsx", "xls"], ["ppt", "ppt"], ["pptx", "ppt"],
|
|
469
|
+
["mp4", "mp4"], ["mp3", "opus"], ["opus", "opus"], ["ogg", "opus"], ["txt", "stream"], ["csv", "stream"], ["json", "stream"], ["md", "stream"],
|
|
470
|
+
]);
|
|
471
|
+
const IMAGE_TYPES = new Set(["png", "jpg", "jpeg", "gif", "bmp", "webp", "heic", "tif", "tiff"]);
|
|
472
|
+
|
|
473
|
+
// ---- HTTPS to the open platform -------------------------------------------------------------------
|
|
474
|
+
|
|
475
|
+
/** JSON over HTTPS with a timeout; Feishu's envelope `{code, msg, data}` is checked here. */
|
|
476
|
+
export async function feishuRequest(path, { method = "POST", token, body, query, timeoutMs = 20_000, fetchImpl = fetch } = {}) {
|
|
477
|
+
const url = new URL(`${FEISHU_DOMAIN}${path}`);
|
|
478
|
+
for (const [key, value] of Object.entries(query ?? {})) url.searchParams.set(key, value);
|
|
479
|
+
const controller = new AbortController();
|
|
480
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
481
|
+
try {
|
|
482
|
+
const response = await fetchImpl(url, {
|
|
483
|
+
method,
|
|
484
|
+
signal: controller.signal,
|
|
485
|
+
headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body === undefined ? {} : { "content-type": "application/json" }) },
|
|
486
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
487
|
+
});
|
|
488
|
+
const data = await response.json().catch(() => null);
|
|
489
|
+
if (!response.ok || !data || (data.code !== undefined && data.code !== 0)) {
|
|
490
|
+
const code = data?.code ?? response.status;
|
|
491
|
+
// The two errors a user can act on get their own words; the rest carry Feishu's message.
|
|
492
|
+
const known = { 99991663: "飞书应用的 App ID 或 App Secret 不对", 99991672: "飞书应用没有开通所需权限", 230001: "飞书应用的事件订阅没有生效", 230013: "飞书应用没有开启机器人能力", 230006: "Bot ability is not activated" };
|
|
493
|
+
// The Feishu code goes under `feishuCode`: NetChatError spreads its extras onto itself, and
|
|
494
|
+
// a `code` there would replace this error's own code.
|
|
495
|
+
throw new NetChatError("feishu_api", known[code] ?? data?.msg ?? `飞书接口返回 ${code}`, { feishuCode: code, path });
|
|
496
|
+
}
|
|
497
|
+
return data.data ?? data;
|
|
498
|
+
} catch (error) {
|
|
499
|
+
if (error instanceof NetChatError) throw error;
|
|
500
|
+
if (controller.signal.aborted) throw new NetChatError("feishu_timeout", `飞书接口没有在 ${timeoutMs / 1000}s 内响应`);
|
|
501
|
+
throw new NetChatError("feishu_network", `连不上飞书:${describeError(error)}`);
|
|
502
|
+
} finally {
|
|
503
|
+
clearTimeout(timer);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Multipart upload of one file or image; returns the resource key. */
|
|
508
|
+
async function feishuUpload(path, { token, fileType, fileName, filePath, fetchImpl = fetch }) {
|
|
509
|
+
// Read into memory rather than hand over a stream: Feishu caps a message file well below this,
|
|
510
|
+
// and a stream left to the request body would keep a handle open past the send.
|
|
511
|
+
const bytes = await readFile(filePath);
|
|
512
|
+
if (bytes.length > MAX_UPLOAD_BYTES) throw new NetChatError("too_large", `文件超过 ${MAX_UPLOAD_BYTES / 1024 / 1024} MB,飞书不支持发送`);
|
|
513
|
+
const form = new FormData();
|
|
514
|
+
form.append("file_type", fileType);
|
|
515
|
+
form.append("file_name", fileName);
|
|
516
|
+
form.append("file", new Blob([bytes]), fileName);
|
|
517
|
+
const response = await fetchImpl(`${FEISHU_DOMAIN}${path}`, { method: "POST", headers: { authorization: `Bearer ${token}` }, body: form }).catch((error) => {
|
|
518
|
+
throw new NetChatError("feishu_network", `上传失败:${describeError(error)}`);
|
|
519
|
+
});
|
|
520
|
+
const data = await response.json().catch(() => null);
|
|
521
|
+
if (!response.ok || !data || data.code !== 0) throw new NetChatError("feishu_api", data?.msg ?? `上传返回 ${response.status}`, { feishuCode: data?.code, path });
|
|
522
|
+
return data.data?.file_key ?? data.data?.image_key;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* The bridge: one long connection to Feishu that hands out pairing codes to the unbound and
|
|
527
|
+
* hands the bound's messages to `onMessage`, plus the HTTPS calls to send reminders. It is owned by whoever
|
|
528
|
+
* owns the LAN service, so there is exactly one per machine. `fetchImpl` and `connect` are
|
|
529
|
+
* injectable so the suite never touches Feishu.
|
|
530
|
+
*/
|
|
531
|
+
export class FeishuBridge {
|
|
532
|
+
constructor({ dir, logger, onMessage, onEvent, machineName = "", hostName = "NetChat", fetchImpl = fetch, connect = (url) => new WsConnection(url), now = () => Date.now() }) {
|
|
533
|
+
this.dir = dir;
|
|
534
|
+
this.logger = logger;
|
|
535
|
+
this.onMessage = onMessage;
|
|
536
|
+
this.onEvent = onEvent;
|
|
537
|
+
// Said in the pairing message: a code has to be pasted into the host that gave it, and with
|
|
538
|
+
// ZCode and DeepSeek Harness both running NetChat that is not always the one at hand.
|
|
539
|
+
this.machineName = clip(String(machineName ?? "").trim(), 40) || "这台机器";
|
|
540
|
+
this.hostName = clip(String(hostName ?? "").trim(), 40) || "NetChat";
|
|
541
|
+
this.fetchImpl = fetchImpl;
|
|
542
|
+
this.connect = connect;
|
|
543
|
+
this.now = now;
|
|
544
|
+
this.book = new FeishuBook(dir).load();
|
|
545
|
+
this.ws = null;
|
|
546
|
+
this.state = "stopped";
|
|
547
|
+
this.lastError = null;
|
|
548
|
+
this.startedAt = null;
|
|
549
|
+
this.reconnectTimer = null;
|
|
550
|
+
this.pingTimer = null;
|
|
551
|
+
this.stopping = false;
|
|
552
|
+
this.generation = 0;
|
|
553
|
+
this.fragments = new FragmentCache();
|
|
554
|
+
this.token = null;
|
|
555
|
+
this.tokenExpiresAt = 0;
|
|
556
|
+
this.tokenPromise = null;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
get attachmentsDir() {
|
|
560
|
+
const dir = join(this.dir, "attachments");
|
|
561
|
+
mkdirSync(dir, { recursive: true });
|
|
562
|
+
return dir;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** A tenant token, fetched once and reused until two minutes before it expires. */
|
|
566
|
+
async tenantToken() {
|
|
567
|
+
if (this.token && this.now() < this.tokenExpiresAt - 120_000) return this.token;
|
|
568
|
+
this.tokenPromise ??= (async () => {
|
|
569
|
+
const data = await feishuRequest("/open-apis/auth/v3/tenant_access_token/internal", {
|
|
570
|
+
body: { app_id: this.book.data.appId, app_secret: this.book.data.appSecret },
|
|
571
|
+
fetchImpl: this.fetchImpl,
|
|
572
|
+
});
|
|
573
|
+
// The token endpoint answers at the top level: {code, msg, tenant_access_token, expire}.
|
|
574
|
+
if (!data?.tenant_access_token) throw new NetChatError("feishu_api", "飞书没有返回 tenant_access_token", { feishuCode: data?.code });
|
|
575
|
+
this.token = data.tenant_access_token;
|
|
576
|
+
this.tokenExpiresAt = this.now() + Math.max(60, Number(data.expire) || 7200) * 1000;
|
|
577
|
+
return this.token;
|
|
578
|
+
})().finally(() => {
|
|
579
|
+
this.tokenPromise = null;
|
|
580
|
+
});
|
|
581
|
+
return this.tokenPromise;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** The credentials are checked by asking Feishu for a token with them. */
|
|
585
|
+
async verifyCredentials() {
|
|
586
|
+
this.token = null;
|
|
587
|
+
this.tokenExpiresAt = 0;
|
|
588
|
+
await this.tenantToken();
|
|
589
|
+
return true;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** Sends a text / markdown / file message to a user's p2p chat as the bot. Returns the message id. */
|
|
593
|
+
async send(openId, { text = "", markdown = "", file = null } = {}) {
|
|
594
|
+
if (!OPEN_ID.test(openId ?? "")) throw new NetChatError("invalid_input", "open_id 必须是 ou_ 开头的 id");
|
|
595
|
+
const token = await this.tenantToken();
|
|
596
|
+
let msgType = "text";
|
|
597
|
+
let content;
|
|
598
|
+
if (file) {
|
|
599
|
+
const extension = String(file).split(".").pop().toLowerCase();
|
|
600
|
+
if (IMAGE_TYPES.has(extension)) {
|
|
601
|
+
msgType = "image";
|
|
602
|
+
const key = await feishuUpload("/open-apis/im/v1/images", { token, fileType: "image", fileName: String(file).split(/[\\/]/).pop(), filePath: file, fetchImpl: this.fetchImpl });
|
|
603
|
+
content = { image_key: key };
|
|
604
|
+
} else {
|
|
605
|
+
msgType = "file";
|
|
606
|
+
const key = await feishuUpload("/open-apis/im/v1/files", { token, fileType: FILE_TYPES.get(extension) ?? "stream", fileName: String(file).split(/[\\/]/).pop(), filePath: file, fetchImpl: this.fetchImpl });
|
|
607
|
+
content = { file_key: key };
|
|
608
|
+
}
|
|
609
|
+
} else if (markdown) {
|
|
610
|
+
// Feishu "post" is rich text; markdown is rendered into paragraphs. Line breaks survive as
|
|
611
|
+
// paragraphs so code blocks and lists stay readable, if plainly.
|
|
612
|
+
msgType = "post";
|
|
613
|
+
content = { zh_cn: { title: "", content: [[{ tag: "md", text: markdown }]] } };
|
|
614
|
+
} else {
|
|
615
|
+
content = { text };
|
|
616
|
+
}
|
|
617
|
+
const data = await feishuRequest("/open-apis/im/v1/messages", {
|
|
618
|
+
token,
|
|
619
|
+
query: { receive_id_type: "open_id" },
|
|
620
|
+
body: { receive_id: openId, msg_type: msgType, content: JSON.stringify(content) },
|
|
621
|
+
fetchImpl: this.fetchImpl,
|
|
622
|
+
});
|
|
623
|
+
return { messageId: data?.message_id ?? null, raw: data };
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** Downloads a file or image from a message into the attachments directory. Returns the absolute path. */
|
|
627
|
+
async download({ messageId, key, type, name }) {
|
|
628
|
+
if (!MESSAGE_ID.test(messageId ?? "") || !RESOURCE_KEY.test(key ?? "")) return null;
|
|
629
|
+
const token = await this.tenantToken();
|
|
630
|
+
const safe = String(name ?? "").replace(/[\\/:*?"<>|\r\n]+/g, "_").slice(0, 80) || key;
|
|
631
|
+
const output = join(this.attachmentsDir, `${messageId}_${safe}`);
|
|
632
|
+
const response = await this.fetchImpl(`${FEISHU_DOMAIN}/open-apis/im/v1/messages/${messageId}/resources/${key}?type=${type}`, {
|
|
633
|
+
headers: { authorization: `Bearer ${token}` },
|
|
634
|
+
}).catch((error) => {
|
|
635
|
+
throw new NetChatError("feishu_network", `下载失败:${describeError(error)}`);
|
|
636
|
+
});
|
|
637
|
+
if (!response.ok) {
|
|
638
|
+
// A binary endpoint reports errors as JSON; read it so the reason is not lost.
|
|
639
|
+
const data = await response.json().catch(() => null);
|
|
640
|
+
throw new NetChatError("feishu_api", data?.msg ?? `下载返回 ${response.status}`, { feishuCode: data?.code });
|
|
641
|
+
}
|
|
642
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
643
|
+
// Written beside the target and renamed, so a half-written attachment is never mistaken for a whole one.
|
|
644
|
+
writeFileSync(`${output}.part`, bytes);
|
|
645
|
+
renameSync(`${output}.part`, output);
|
|
646
|
+
return output;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
async start() {
|
|
650
|
+
if (this.ws || this.stopping) return;
|
|
651
|
+
if (!this.book.configured) {
|
|
652
|
+
this.state = "unconfigured";
|
|
653
|
+
this.lastError = "还没有填写飞书应用的 App ID 和 App Secret";
|
|
654
|
+
this.onEvent?.("feishu");
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
this.stopping = false;
|
|
658
|
+
await this.openConnection();
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** Handshake for a ws url, then the connection itself. Failures set the state and schedule a retry. */
|
|
662
|
+
async openConnection() {
|
|
663
|
+
const generation = ++this.generation;
|
|
664
|
+
this.state = "connecting";
|
|
665
|
+
try {
|
|
666
|
+
const token = await this.tenantToken();
|
|
667
|
+
const config = await feishuRequest("/callback/ws/endpoint", {
|
|
668
|
+
body: { AppID: this.book.data.appId, AppSecret: this.book.data.appSecret },
|
|
669
|
+
fetchImpl: this.fetchImpl,
|
|
670
|
+
timeoutMs: 15_000,
|
|
671
|
+
});
|
|
672
|
+
// The endpoint answers {URL, ClientConfig} without the usual envelope; feishuRequest returns it as is.
|
|
673
|
+
const url = config?.URL;
|
|
674
|
+
if (!url) throw new NetChatError("feishu_api", "飞书没有返回长连接地址", { config });
|
|
675
|
+
const service = Number(new URL(url).searchParams.get("service_id")) || 0;
|
|
676
|
+
const clientConfig = config?.ClientConfig ?? {};
|
|
677
|
+
const pingIntervalMs = Math.max(10, Number(clientConfig.PingInterval) || 120) * 1000;
|
|
678
|
+
if (generation !== this.generation) return;
|
|
679
|
+
const ws = this.connect(url);
|
|
680
|
+
this.ws = ws;
|
|
681
|
+
ws.on("binary", (buffer) => this.onFrame(buffer, service));
|
|
682
|
+
ws.on("text", (text) => this.onFrame(Buffer.from(text, "utf8"), service));
|
|
683
|
+
ws.on("error", (error) => this.logger?.warn?.(`feishu ws: ${describeError(error)}`));
|
|
684
|
+
ws.on("close", (code, reason) => {
|
|
685
|
+
if (this.ws !== ws) return;
|
|
686
|
+
this.ws = null;
|
|
687
|
+
clearInterval(this.pingTimer);
|
|
688
|
+
this.pingTimer = null;
|
|
689
|
+
if (this.stopping) {
|
|
690
|
+
this.state = "stopped";
|
|
691
|
+
this.onEvent?.("feishu");
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
this.state = "reconnecting";
|
|
695
|
+
this.lastError = `连接断开(${code}${reason ? ` ${reason}` : ""}),${Math.round(((Number(clientConfig.ReconnectInterval) || 90)))} 秒后重连`;
|
|
696
|
+
this.logger?.warn?.(`feishu: ${this.lastError}`);
|
|
697
|
+
this.onEvent?.("feishu");
|
|
698
|
+
this.scheduleReconnect(Math.max(5, Number(clientConfig.ReconnectInterval) || 90) * 1000);
|
|
699
|
+
});
|
|
700
|
+
await ws.connect();
|
|
701
|
+
if (generation !== this.generation) {
|
|
702
|
+
ws.close();
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
this.state = "listening";
|
|
706
|
+
this.lastError = null;
|
|
707
|
+
this.startedAt = nowIso();
|
|
708
|
+
this.onEvent?.("feishu");
|
|
709
|
+
this.logger?.info?.("feishu: connected");
|
|
710
|
+
// The server expects a ping every PingInterval seconds; the pong carries new intervals.
|
|
711
|
+
const ping = () => {
|
|
712
|
+
if (this.ws !== ws) return;
|
|
713
|
+
ws.send(pingFrame(service));
|
|
714
|
+
this.pingTimer = setTimeout(ping, pingIntervalMs);
|
|
715
|
+
};
|
|
716
|
+
ping();
|
|
717
|
+
} catch (error) {
|
|
718
|
+
if (generation !== this.generation) return;
|
|
719
|
+
this.ws = null;
|
|
720
|
+
// Bad credentials or missing scopes do not fix themselves: stop retrying and say so.
|
|
721
|
+
const fatal = error.code === "feishu_api" && [99991663, 99991672].includes(error.feishuCode);
|
|
722
|
+
this.lastError = describeError(error);
|
|
723
|
+
this.state = fatal ? "unconfigured" : "reconnecting";
|
|
724
|
+
this.logger?.warn?.(`feishu: ${this.lastError}`);
|
|
725
|
+
this.onEvent?.("feishu");
|
|
726
|
+
if (!fatal && !this.stopping) this.scheduleReconnect(15_000);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
scheduleReconnect(delayMs) {
|
|
731
|
+
if (this.reconnectTimer || this.stopping) return;
|
|
732
|
+
this.reconnectTimer = setTimeout(() => {
|
|
733
|
+
this.reconnectTimer = null;
|
|
734
|
+
if (!this.stopping) void this.openConnection();
|
|
735
|
+
}, delayMs);
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/** One protobuf frame from the connection. */
|
|
739
|
+
onFrame(buffer, service) {
|
|
740
|
+
let frame;
|
|
741
|
+
try {
|
|
742
|
+
frame = decodeFrame(buffer);
|
|
743
|
+
} catch (error) {
|
|
744
|
+
this.logger?.warn?.(`feishu frame: ${describeError(error)}`);
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
const headers = frame.headerMap;
|
|
748
|
+
if (headers[headerKeys.handshakeStatus] && headers[headerKeys.handshakeStatus] !== "0") {
|
|
749
|
+
this.lastError = `飞书拒绝了长连接握手:${headers["handshake-msg"] ?? headers[headerKeys.handshakeStatus]}`;
|
|
750
|
+
this.logger?.warn?.(`feishu: ${this.lastError}`);
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
if (frame.method === METHOD_DATA && headers[headerKeys.type] === MESSAGE_EVENT) {
|
|
754
|
+
const messageId = headers[headerKeys.messageId];
|
|
755
|
+
let whole;
|
|
756
|
+
try {
|
|
757
|
+
whole = this.fragments.merge({
|
|
758
|
+
messageId,
|
|
759
|
+
sum: Number(headers[headerKeys.sum] ?? 1),
|
|
760
|
+
seq: Number(headers[headerKeys.seq] ?? 0),
|
|
761
|
+
data: frame.payload ?? Buffer.alloc(0),
|
|
762
|
+
});
|
|
763
|
+
} catch (error) {
|
|
764
|
+
this.logger?.warn?.(`feishu fragments: ${describeError(error)}`);
|
|
765
|
+
// Still acknowledge, or Feishu keeps redelivering a fragment set we cannot use.
|
|
766
|
+
this.ws?.send(ackFor(frame, 200));
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
if (!whole) return;
|
|
770
|
+
// Acknowledge before handling: the handler may take as long as it likes, and the
|
|
771
|
+
// server only needs to know the frame was received within three seconds.
|
|
772
|
+
this.ws?.send(ackFor(frame, 200));
|
|
773
|
+
let event;
|
|
774
|
+
try {
|
|
775
|
+
event = JSON.parse(whole.toString("utf8"));
|
|
776
|
+
} catch {
|
|
777
|
+
this.logger?.warn?.("feishu event: not JSON");
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
void this.handleEvent(event).catch((error) => this.logger?.warn?.(`feishu event: ${describeError(error)}`));
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
if (frame.method === METHOD_DATA && headers[headerKeys.type] === MESSAGE_PING) {
|
|
784
|
+
// A server-initiated ping on the data channel: answer with the same frame, type pong.
|
|
785
|
+
this.ws?.send(encodeFrame({ SeqID: frame.SeqID, LogID: frame.LogID, service: frame.service, method: METHOD_DATA, headers: frame.headers.map((h) => (h.key === headerKeys.type ? { key: h.key, value: MESSAGE_PONG } : h)), payload: Buffer.from("{}") }));
|
|
786
|
+
}
|
|
787
|
+
// Control frames (our pong, their pong) need nothing: liveness is the ping loop's.
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
async handleEvent(event) {
|
|
791
|
+
// The v2 envelope puts the message under `event`; older shapes may arrive flat.
|
|
792
|
+
const body = event?.event ?? event;
|
|
793
|
+
const message = body?.message;
|
|
794
|
+
if (!message) return;
|
|
795
|
+
if (event?.event_type && event.event_type !== FEISHU_EVENT) return;
|
|
796
|
+
if (body.sender?.sender_type && body.sender.sender_type !== "user") return;
|
|
797
|
+
// Group chats are out of scope by design (see the top of this file).
|
|
798
|
+
if (message.chat_type && message.chat_type !== "p2p") return;
|
|
799
|
+
const openId = String(body.sender?.sender_id?.open_id ?? "");
|
|
800
|
+
const messageId = String(message.message_id ?? "");
|
|
801
|
+
if (!OPEN_ID.test(openId) || !MESSAGE_ID.test(messageId)) return;
|
|
802
|
+
// The records as they are now, not as they were when this bridge started: the other host on
|
|
803
|
+
// this machine may have bound this person, or handled this very message, a moment ago.
|
|
804
|
+
this.book.refresh();
|
|
805
|
+
if (this.book.seen(messageId)) return;
|
|
806
|
+
const { text, resources } = parseContent(message.message_type, message.content);
|
|
807
|
+
// A sticker, audio or a merge-forward summary with no text and nothing to download is not a task.
|
|
808
|
+
if (!text && !resources.length) return;
|
|
809
|
+
// Written down before anything else, so the other host's bridge does not handle it as well;
|
|
810
|
+
// false means it already has.
|
|
811
|
+
if (!(await this.book.remember(messageId))) return;
|
|
812
|
+
const bound = this.book.bound(openId);
|
|
813
|
+
|
|
814
|
+
if (!bound) {
|
|
815
|
+
// The pairing code is what the owner puts into the panel; it is said on every message,
|
|
816
|
+
// because the person may be reading it off another screen and will not remember the first.
|
|
817
|
+
const { entry, added } = await this.book.notePending(openId, "");
|
|
818
|
+
if (added) this.onEvent?.("feishu");
|
|
819
|
+
const code = entry.code;
|
|
820
|
+
// The code on a line of its own, as the six characters and nothing else: it is copied far
|
|
821
|
+
// more often than it is typed, and on a phone the selection runs past it — a copy takes
|
|
822
|
+
// this line, the one before, or the whole message, and the service finds the code in any of
|
|
823
|
+
// them. (0.3.11 wrote it with a space between characters, which a copy then carried along
|
|
824
|
+
// and the match refused.) And it says the code stays the same, so a refused one is not a
|
|
825
|
+
// reason to ask for another. It names the machine and its host too: with ZCode and DeepSeek
|
|
826
|
+
// Harness both running NetChat, a code has to be pasted into the one that gave it.
|
|
827
|
+
await this.send(openId, { text: `「${this.machineName}」的 ${this.hostName} 还没有绑定你的飞书。\n把下面这行绑定码贴到这台机器的 ${this.hostName} 里的 NetChat 面板 → 设置 → 飞书 → 绑定码里即可(整条消息贴过去也行)。\n\n${code}\n\n这个码在你绑定成功前不会变。` }).catch((error) => this.logger?.warn?.(`feishu: ${describeError(error)}`));
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
await this.book.update((data) => {
|
|
831
|
+
const entry = data.bindings.find((item) => item.openId === openId);
|
|
832
|
+
if (entry) entry.lastMessageAt = nowIso();
|
|
833
|
+
});
|
|
834
|
+
// What they wrote is an answer to a question waiting on a choice, when it can be told which
|
|
835
|
+
// one (a reply to the reminder names it; a bare message does when only one is open). The
|
|
836
|
+
// service decides and says what it did; here it is only passed on.
|
|
837
|
+
const outcome = await this.onMessage?.({ text, openId, parentId: message.parent_id ?? message.root_id ?? null }).catch((error) => {
|
|
838
|
+
this.logger?.warn?.(`feishu answer: ${describeError(error)}`);
|
|
839
|
+
return null;
|
|
840
|
+
});
|
|
841
|
+
if (!outcome) return;
|
|
842
|
+
const said = {
|
|
843
|
+
ignored: null,
|
|
844
|
+
"none-open": "你的 Agent 这边没有等你选择的提问。",
|
|
845
|
+
"already-answered": "这个提问已经答过了。",
|
|
846
|
+
off: "这台机器没有开“通知飞书”,飞书这边不作答。到 NetChat 面板 → 设置 → 飞书 里打开后再回。",
|
|
847
|
+
// ambiguous: the service has already listed what is open and how to answer.
|
|
848
|
+
ambiguous: null,
|
|
849
|
+
answered: null,
|
|
850
|
+
}[outcome.kind];
|
|
851
|
+
if (said) await this.send(openId, { text: said }).catch((error) => this.logger?.warn?.(`feishu: ${describeError(error)}`));
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
async stop() {
|
|
855
|
+
this.stopping = true;
|
|
856
|
+
this.generation += 1;
|
|
857
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
858
|
+
this.reconnectTimer = null;
|
|
859
|
+
clearInterval(this.pingTimer);
|
|
860
|
+
this.pingTimer = null;
|
|
861
|
+
const ws = this.ws;
|
|
862
|
+
this.ws = null;
|
|
863
|
+
if (ws) ws.close(1000, "bye");
|
|
864
|
+
this.state = "stopped";
|
|
865
|
+
this.onEvent?.("feishu");
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
status() {
|
|
869
|
+
return {
|
|
870
|
+
state: this.state,
|
|
871
|
+
lastError: this.lastError,
|
|
872
|
+
startedAt: this.startedAt,
|
|
873
|
+
bindings: this.book.data.bindings.length,
|
|
874
|
+
pending: this.book.data.pending.length,
|
|
875
|
+
appId: this.book.data.appId,
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
}
|