chattercatcher 0.1.5 → 0.1.6
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/dist/cli.js +3229 -130
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +6 -12
- package/dist/index.js +3206 -90
- package/dist/index.js.map +1 -1
- package/package.json +1 -2
- package/dist/chunk-LYT5TS7P.js +0 -3190
- package/dist/chunk-LYT5TS7P.js.map +0 -1
- package/dist/chunk-OEROFIU2.js +0 -107
- package/dist/chunk-OEROFIU2.js.map +0 -1
- package/dist/chunk-WOBPNFFZ.js +0 -29
- package/dist/chunk-WOBPNFFZ.js.map +0 -1
- package/dist/lancedb-store-QHG4PAI4.js +0 -10
- package/dist/lancedb-store-QHG4PAI4.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,127 +1,3229 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
FeishuMessageSender,
|
|
4
|
-
FeishuQuestionHandler,
|
|
5
|
-
FeishuResourceDownloader,
|
|
6
|
-
FileJobRepository,
|
|
7
|
-
GatewayIngestor,
|
|
8
|
-
MessageRepository,
|
|
9
|
-
applySecretInput,
|
|
10
|
-
askWithRag,
|
|
11
|
-
createChatModel,
|
|
12
|
-
createEmbeddingModel,
|
|
13
|
-
createFeishuGateway,
|
|
14
|
-
createHybridRetriever,
|
|
15
|
-
deleteLocalData,
|
|
16
|
-
ensureConfigFiles,
|
|
17
|
-
exportLocalData,
|
|
18
|
-
followLogFile,
|
|
19
|
-
formatCitation,
|
|
20
|
-
formatDoctorChecks,
|
|
21
|
-
getDatabasePath,
|
|
22
|
-
getGatewayStatus,
|
|
23
|
-
getLogsDirectory,
|
|
24
|
-
hasEmbeddingConfig,
|
|
25
|
-
indexMessageChunks,
|
|
26
|
-
ingestLocalFile,
|
|
27
|
-
loadConfig,
|
|
28
|
-
loadSecrets,
|
|
29
|
-
maskSecret,
|
|
30
|
-
normalizeLineCount,
|
|
31
|
-
openDatabase,
|
|
32
|
-
processMessagesNow,
|
|
33
|
-
readLatestLogTail,
|
|
34
|
-
removeGatewayPidRecord,
|
|
35
|
-
resetConfigFiles,
|
|
36
|
-
resolveEmbeddingApiKey,
|
|
37
|
-
restoreLocalData,
|
|
38
|
-
runDoctor,
|
|
39
|
-
saveConfig,
|
|
40
|
-
saveSecrets,
|
|
41
|
-
startWebServer,
|
|
42
|
-
stopGatewayProcess,
|
|
43
|
-
writeGatewayPidRecord
|
|
44
|
-
} from "./chunk-LYT5TS7P.js";
|
|
45
|
-
import {
|
|
46
|
-
getChatterCatcherHome,
|
|
47
|
-
getConfigPath,
|
|
48
|
-
getSecretsPath
|
|
49
|
-
} from "./chunk-WOBPNFFZ.js";
|
|
50
2
|
|
|
51
3
|
// src/cli.ts
|
|
52
4
|
import { input, password, select, confirm, number } from "@inquirer/prompts";
|
|
53
5
|
import { Command } from "commander";
|
|
6
|
+
import fs12 from "fs/promises";
|
|
7
|
+
|
|
8
|
+
// src/config/store.ts
|
|
54
9
|
import fs from "fs/promises";
|
|
10
|
+
import path3 from "path";
|
|
11
|
+
|
|
12
|
+
// src/config/schema.ts
|
|
13
|
+
import os from "os";
|
|
14
|
+
import path from "path";
|
|
15
|
+
import { z } from "zod";
|
|
16
|
+
function defaultDataDir() {
|
|
17
|
+
return path.join(process.env.CHATTERCATCHER_HOME || path.join(os.homedir(), ".chattercatcher"), "data");
|
|
18
|
+
}
|
|
19
|
+
var appConfigSchema = z.object({
|
|
20
|
+
feishu: z.object({
|
|
21
|
+
domain: z.enum(["feishu", "lark"]).default("feishu"),
|
|
22
|
+
appId: z.string().default(""),
|
|
23
|
+
groupPolicy: z.enum(["open", "allowlist", "disabled"]).default("open"),
|
|
24
|
+
requireMention: z.boolean().default(true)
|
|
25
|
+
}),
|
|
26
|
+
llm: z.object({
|
|
27
|
+
baseUrl: z.string().url().or(z.literal("")).default(""),
|
|
28
|
+
model: z.string().default("")
|
|
29
|
+
}),
|
|
30
|
+
embedding: z.object({
|
|
31
|
+
baseUrl: z.string().url().or(z.literal("")).default(""),
|
|
32
|
+
model: z.string().default(""),
|
|
33
|
+
dimension: z.number().int().positive().nullable().default(null)
|
|
34
|
+
}),
|
|
35
|
+
storage: z.object({
|
|
36
|
+
dataDir: z.string().default(defaultDataDir)
|
|
37
|
+
}),
|
|
38
|
+
web: z.object({
|
|
39
|
+
host: z.string().default("127.0.0.1"),
|
|
40
|
+
port: z.number().int().min(1).max(65535).default(3878)
|
|
41
|
+
}),
|
|
42
|
+
schedules: z.object({
|
|
43
|
+
indexing: z.string().default("*/10 * * * *")
|
|
44
|
+
})
|
|
45
|
+
});
|
|
46
|
+
var appSecretsSchema = z.object({
|
|
47
|
+
feishu: z.object({
|
|
48
|
+
appSecret: z.string().default("")
|
|
49
|
+
}),
|
|
50
|
+
llm: z.object({
|
|
51
|
+
apiKey: z.string().default("")
|
|
52
|
+
}),
|
|
53
|
+
embedding: z.object({
|
|
54
|
+
apiKey: z.string().default("")
|
|
55
|
+
})
|
|
56
|
+
});
|
|
57
|
+
function createDefaultConfig() {
|
|
58
|
+
return appConfigSchema.parse({
|
|
59
|
+
feishu: {},
|
|
60
|
+
llm: {},
|
|
61
|
+
embedding: {},
|
|
62
|
+
storage: {},
|
|
63
|
+
web: {},
|
|
64
|
+
schedules: {}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function createDefaultSecrets() {
|
|
68
|
+
return appSecretsSchema.parse({
|
|
69
|
+
feishu: {},
|
|
70
|
+
llm: {},
|
|
71
|
+
embedding: {}
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/config/paths.ts
|
|
76
|
+
import os2 from "os";
|
|
77
|
+
import path2 from "path";
|
|
78
|
+
function getChatterCatcherHome() {
|
|
79
|
+
return process.env.CHATTERCATCHER_HOME || path2.join(os2.homedir(), ".chattercatcher");
|
|
80
|
+
}
|
|
81
|
+
function resolveHomePath(value) {
|
|
82
|
+
if (value === "~") {
|
|
83
|
+
return os2.homedir();
|
|
84
|
+
}
|
|
85
|
+
if (value.startsWith("~/") || value.startsWith("~\\")) {
|
|
86
|
+
return path2.join(os2.homedir(), value.slice(2));
|
|
87
|
+
}
|
|
88
|
+
return path2.resolve(value);
|
|
89
|
+
}
|
|
90
|
+
function getConfigPath() {
|
|
91
|
+
return path2.join(getChatterCatcherHome(), "config.json");
|
|
92
|
+
}
|
|
93
|
+
function getSecretsPath() {
|
|
94
|
+
return path2.join(getChatterCatcherHome(), "secrets.json");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/config/store.ts
|
|
98
|
+
async function readJsonFile(filePath, fallback) {
|
|
99
|
+
try {
|
|
100
|
+
const raw = await fs.readFile(filePath, "utf8");
|
|
101
|
+
return JSON.parse(raw);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (error.code === "ENOENT") {
|
|
104
|
+
return fallback;
|
|
105
|
+
}
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
async function writeJsonFile(filePath, value) {
|
|
110
|
+
await fs.mkdir(path3.dirname(filePath), { recursive: true });
|
|
111
|
+
await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}
|
|
112
|
+
`, "utf8");
|
|
113
|
+
}
|
|
114
|
+
async function loadConfig() {
|
|
115
|
+
const raw = await readJsonFile(getConfigPath(), createDefaultConfig());
|
|
116
|
+
return appConfigSchema.parse(raw);
|
|
117
|
+
}
|
|
118
|
+
async function saveConfig(config) {
|
|
119
|
+
await writeJsonFile(getConfigPath(), appConfigSchema.parse(config));
|
|
120
|
+
}
|
|
121
|
+
async function loadSecrets() {
|
|
122
|
+
const raw = await readJsonFile(getSecretsPath(), createDefaultSecrets());
|
|
123
|
+
return appSecretsSchema.parse(raw);
|
|
124
|
+
}
|
|
125
|
+
async function saveSecrets(secrets) {
|
|
126
|
+
await writeJsonFile(getSecretsPath(), appSecretsSchema.parse(secrets));
|
|
127
|
+
}
|
|
128
|
+
async function ensureConfigFiles() {
|
|
129
|
+
await fs.mkdir(getChatterCatcherHome(), { recursive: true });
|
|
130
|
+
const config = await loadConfig();
|
|
131
|
+
const secrets = await loadSecrets();
|
|
132
|
+
await saveConfig(config);
|
|
133
|
+
await saveSecrets(secrets);
|
|
134
|
+
return { config, secrets };
|
|
135
|
+
}
|
|
136
|
+
async function resetConfigFiles() {
|
|
137
|
+
await saveConfig(createDefaultConfig());
|
|
138
|
+
await saveSecrets(createDefaultSecrets());
|
|
139
|
+
}
|
|
140
|
+
function maskSecret(value) {
|
|
141
|
+
if (!value) {
|
|
142
|
+
return "";
|
|
143
|
+
}
|
|
144
|
+
if (value.length <= 8) {
|
|
145
|
+
return "********";
|
|
146
|
+
}
|
|
147
|
+
return `${value.slice(0, 4)}...${value.slice(-4)}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// src/config/update.ts
|
|
151
|
+
function applySecretInput(currentValue, nextValue) {
|
|
152
|
+
const trimmed = nextValue?.trim() ?? "";
|
|
153
|
+
return trimmed ? trimmed : currentValue;
|
|
154
|
+
}
|
|
155
|
+
function resolveEmbeddingApiKey(input2) {
|
|
156
|
+
const explicit = applySecretInput(input2.currentEmbeddingKey, input2.nextEmbeddingKey);
|
|
157
|
+
return explicit || input2.llmApiKey;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// src/data/deletion.ts
|
|
161
|
+
import fs2 from "fs/promises";
|
|
162
|
+
import path4 from "path";
|
|
163
|
+
function emptyResult(targetType, targetId) {
|
|
164
|
+
return {
|
|
165
|
+
targetType,
|
|
166
|
+
targetId,
|
|
167
|
+
deletedMessages: 0,
|
|
168
|
+
deletedChunks: 0,
|
|
169
|
+
deletedFileJobs: 0,
|
|
170
|
+
deletedChats: 0,
|
|
171
|
+
deletedStoredFiles: [],
|
|
172
|
+
skippedStoredFiles: []
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function parseStoredPathFromRawPayload(rawPayloadJson) {
|
|
176
|
+
try {
|
|
177
|
+
const parsed = JSON.parse(rawPayloadJson);
|
|
178
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
const storedPath = parsed.storedPath;
|
|
182
|
+
return typeof storedPath === "string" ? storedPath : null;
|
|
183
|
+
} catch {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function isInsideDirectory(filePath, directory) {
|
|
188
|
+
const relative = path4.relative(path4.resolve(directory), path4.resolve(filePath));
|
|
189
|
+
return relative === "" || !relative.startsWith("..") && !path4.isAbsolute(relative);
|
|
190
|
+
}
|
|
191
|
+
async function removeStoredFiles(config, paths) {
|
|
192
|
+
const dataDir = resolveHomePath(config.storage.dataDir);
|
|
193
|
+
const deleted = [];
|
|
194
|
+
const skipped = [];
|
|
195
|
+
const uniquePaths = [...new Set(paths.filter(Boolean).map((item) => path4.resolve(item)))];
|
|
196
|
+
for (const storedPath of uniquePaths) {
|
|
197
|
+
if (!isInsideDirectory(storedPath, dataDir)) {
|
|
198
|
+
skipped.push(storedPath);
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
try {
|
|
202
|
+
await fs2.rm(storedPath, { force: true });
|
|
203
|
+
deleted.push(storedPath);
|
|
204
|
+
} catch {
|
|
205
|
+
skipped.push(storedPath);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return { deleted, skipped };
|
|
209
|
+
}
|
|
210
|
+
function getStoredPathsForMessages(database, messageIds) {
|
|
211
|
+
if (messageIds.length === 0) {
|
|
212
|
+
return [];
|
|
213
|
+
}
|
|
214
|
+
const rows = database.prepare(
|
|
215
|
+
`
|
|
216
|
+
SELECT raw_payload_json AS rawPayloadJson
|
|
217
|
+
FROM messages
|
|
218
|
+
WHERE id IN (${messageIds.map(() => "?").join(", ")})
|
|
219
|
+
`
|
|
220
|
+
).all(...messageIds);
|
|
221
|
+
const fileJobRows = database.prepare(
|
|
222
|
+
`
|
|
223
|
+
SELECT stored_path AS storedPath
|
|
224
|
+
FROM file_jobs
|
|
225
|
+
WHERE message_id IN (${messageIds.map(() => "?").join(", ")})
|
|
226
|
+
`
|
|
227
|
+
).all(...messageIds);
|
|
228
|
+
return [
|
|
229
|
+
...rows.map((row) => parseStoredPathFromRawPayload(row.rawPayloadJson)).filter((item) => Boolean(item)),
|
|
230
|
+
...fileJobRows.map((row) => row.storedPath).filter((item) => Boolean(item))
|
|
231
|
+
];
|
|
232
|
+
}
|
|
233
|
+
function deleteMessagesByIds(database, messageIds) {
|
|
234
|
+
if (messageIds.length === 0) {
|
|
235
|
+
return {
|
|
236
|
+
deletedMessages: 0,
|
|
237
|
+
deletedChunks: 0,
|
|
238
|
+
deletedFileJobs: 0
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
const placeholders = messageIds.map(() => "?").join(", ");
|
|
242
|
+
const deletedChunks = database.prepare(`SELECT COUNT(*) AS count FROM message_chunks WHERE message_id IN (${placeholders})`).get(...messageIds).count;
|
|
243
|
+
const deletedFileJobs = database.prepare(`DELETE FROM file_jobs WHERE message_id IN (${placeholders})`).run(...messageIds).changes;
|
|
244
|
+
database.prepare(`DELETE FROM message_chunks_fts WHERE message_id IN (${placeholders})`).run(...messageIds);
|
|
245
|
+
const deletedMessages = database.prepare(`DELETE FROM messages WHERE id IN (${placeholders})`).run(...messageIds).changes;
|
|
246
|
+
return {
|
|
247
|
+
deletedMessages,
|
|
248
|
+
deletedChunks,
|
|
249
|
+
deletedFileJobs
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
async function deleteLocalData(input2) {
|
|
253
|
+
const result = emptyResult(input2.targetType, input2.targetId);
|
|
254
|
+
let storedPaths = [];
|
|
255
|
+
const transaction = input2.database.transaction(() => {
|
|
256
|
+
if (input2.targetType === "chat") {
|
|
257
|
+
const messageIds = input2.database.prepare("SELECT id FROM messages WHERE chat_id = ?").all(input2.targetId).map((row) => row.id);
|
|
258
|
+
storedPaths = getStoredPathsForMessages(input2.database, messageIds);
|
|
259
|
+
const deleted2 = deleteMessagesByIds(input2.database, messageIds);
|
|
260
|
+
result.deletedMessages = deleted2.deletedMessages;
|
|
261
|
+
result.deletedChunks = deleted2.deletedChunks;
|
|
262
|
+
result.deletedFileJobs = deleted2.deletedFileJobs;
|
|
263
|
+
result.deletedChats = input2.database.prepare("DELETE FROM chats WHERE id = ?").run(input2.targetId).changes;
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (input2.targetType === "file") {
|
|
267
|
+
const file = input2.database.prepare("SELECT id FROM messages WHERE id = ? AND message_type = 'file'").get(input2.targetId);
|
|
268
|
+
if (!file) {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
storedPaths = getStoredPathsForMessages(input2.database, [input2.targetId]);
|
|
273
|
+
const deleted = deleteMessagesByIds(input2.database, [input2.targetId]);
|
|
274
|
+
result.deletedMessages = deleted.deletedMessages;
|
|
275
|
+
result.deletedChunks = deleted.deletedChunks;
|
|
276
|
+
result.deletedFileJobs = deleted.deletedFileJobs;
|
|
277
|
+
});
|
|
278
|
+
transaction();
|
|
279
|
+
const removed = await removeStoredFiles(input2.config, storedPaths);
|
|
280
|
+
result.deletedStoredFiles = removed.deleted;
|
|
281
|
+
result.skippedStoredFiles = removed.skipped;
|
|
282
|
+
return result;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// src/db/database.ts
|
|
286
|
+
import Database from "better-sqlite3";
|
|
287
|
+
import fs3 from "fs";
|
|
288
|
+
import path5 from "path";
|
|
289
|
+
function getDatabasePath(config) {
|
|
290
|
+
return path5.join(resolveHomePath(config.storage.dataDir), "chattercatcher.db");
|
|
291
|
+
}
|
|
292
|
+
function openDatabase(config) {
|
|
293
|
+
const databasePath = getDatabasePath(config);
|
|
294
|
+
fs3.mkdirSync(path5.dirname(databasePath), { recursive: true });
|
|
295
|
+
const database = new Database(databasePath);
|
|
296
|
+
database.pragma("journal_mode = WAL");
|
|
297
|
+
database.pragma("foreign_keys = ON");
|
|
298
|
+
migrateDatabase(database);
|
|
299
|
+
return database;
|
|
300
|
+
}
|
|
301
|
+
function migrateDatabase(database) {
|
|
302
|
+
database.exec(`
|
|
303
|
+
CREATE TABLE IF NOT EXISTS chats (
|
|
304
|
+
id TEXT PRIMARY KEY,
|
|
305
|
+
platform TEXT NOT NULL,
|
|
306
|
+
platform_chat_id TEXT NOT NULL,
|
|
307
|
+
name TEXT NOT NULL,
|
|
308
|
+
created_at TEXT NOT NULL,
|
|
309
|
+
updated_at TEXT NOT NULL,
|
|
310
|
+
UNIQUE(platform, platform_chat_id)
|
|
311
|
+
);
|
|
312
|
+
|
|
313
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
314
|
+
id TEXT PRIMARY KEY,
|
|
315
|
+
platform TEXT NOT NULL,
|
|
316
|
+
platform_message_id TEXT NOT NULL,
|
|
317
|
+
chat_id TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
|
318
|
+
sender_id TEXT NOT NULL,
|
|
319
|
+
sender_name TEXT NOT NULL,
|
|
320
|
+
message_type TEXT NOT NULL,
|
|
321
|
+
text TEXT NOT NULL,
|
|
322
|
+
raw_payload_json TEXT NOT NULL,
|
|
323
|
+
sent_at TEXT NOT NULL,
|
|
324
|
+
received_at TEXT NOT NULL,
|
|
325
|
+
created_at TEXT NOT NULL,
|
|
326
|
+
UNIQUE(platform, platform_message_id)
|
|
327
|
+
);
|
|
328
|
+
|
|
329
|
+
CREATE TABLE IF NOT EXISTS message_chunks (
|
|
330
|
+
id TEXT PRIMARY KEY,
|
|
331
|
+
message_id TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
|
332
|
+
chunk_index INTEGER NOT NULL,
|
|
333
|
+
text TEXT NOT NULL,
|
|
334
|
+
metadata_json TEXT NOT NULL,
|
|
335
|
+
created_at TEXT NOT NULL,
|
|
336
|
+
UNIQUE(message_id, chunk_index)
|
|
337
|
+
);
|
|
338
|
+
|
|
339
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS message_chunks_fts USING fts5(
|
|
340
|
+
text,
|
|
341
|
+
chunk_id UNINDEXED,
|
|
342
|
+
message_id UNINDEXED,
|
|
343
|
+
tokenize = 'unicode61'
|
|
344
|
+
);
|
|
345
|
+
|
|
346
|
+
CREATE TABLE IF NOT EXISTS message_chunk_vectors (
|
|
347
|
+
chunk_id TEXT PRIMARY KEY REFERENCES message_chunks(id) ON DELETE CASCADE,
|
|
348
|
+
vector_json TEXT NOT NULL,
|
|
349
|
+
evidence_json TEXT NOT NULL,
|
|
350
|
+
updated_at TEXT NOT NULL
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
CREATE TABLE IF NOT EXISTS file_jobs (
|
|
354
|
+
id TEXT PRIMARY KEY,
|
|
355
|
+
source_path TEXT NOT NULL,
|
|
356
|
+
stored_path TEXT,
|
|
357
|
+
file_name TEXT NOT NULL,
|
|
358
|
+
status TEXT NOT NULL,
|
|
359
|
+
parser TEXT,
|
|
360
|
+
message_id TEXT,
|
|
361
|
+
bytes INTEGER,
|
|
362
|
+
characters INTEGER,
|
|
363
|
+
warnings_json TEXT NOT NULL DEFAULT '[]',
|
|
364
|
+
error TEXT,
|
|
365
|
+
created_at TEXT NOT NULL,
|
|
366
|
+
updated_at TEXT NOT NULL
|
|
367
|
+
);
|
|
368
|
+
`);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// src/doctor/checks.ts
|
|
372
|
+
import fs5 from "fs/promises";
|
|
373
|
+
|
|
374
|
+
// src/files/jobs.ts
|
|
375
|
+
import crypto from "crypto";
|
|
376
|
+
import path6 from "path";
|
|
377
|
+
function nowIso() {
|
|
378
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
379
|
+
}
|
|
380
|
+
function stableJobId(sourcePath) {
|
|
381
|
+
return crypto.createHash("sha256").update(path6.resolve(sourcePath)).digest("hex").slice(0, 32);
|
|
382
|
+
}
|
|
383
|
+
function parseWarnings(value) {
|
|
384
|
+
try {
|
|
385
|
+
const parsed = JSON.parse(value);
|
|
386
|
+
return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
|
|
387
|
+
} catch {
|
|
388
|
+
return [];
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
var FileJobRepository = class {
|
|
392
|
+
constructor(database) {
|
|
393
|
+
this.database = database;
|
|
394
|
+
}
|
|
395
|
+
database;
|
|
396
|
+
start(input2) {
|
|
397
|
+
const id = stableJobId(input2.sourcePath);
|
|
398
|
+
const now = nowIso();
|
|
399
|
+
this.database.prepare(
|
|
400
|
+
`
|
|
401
|
+
INSERT INTO file_jobs (
|
|
402
|
+
id, source_path, file_name, status, warnings_json, created_at, updated_at
|
|
403
|
+
)
|
|
404
|
+
VALUES (@id, @sourcePath, @fileName, 'processing', '[]', @createdAt, @updatedAt)
|
|
405
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
406
|
+
source_path = excluded.source_path,
|
|
407
|
+
file_name = excluded.file_name,
|
|
408
|
+
status = 'processing',
|
|
409
|
+
parser = NULL,
|
|
410
|
+
message_id = NULL,
|
|
411
|
+
bytes = NULL,
|
|
412
|
+
characters = NULL,
|
|
413
|
+
warnings_json = '[]',
|
|
414
|
+
error = NULL,
|
|
415
|
+
updated_at = excluded.updated_at
|
|
416
|
+
`
|
|
417
|
+
).run({
|
|
418
|
+
id,
|
|
419
|
+
sourcePath: path6.resolve(input2.sourcePath),
|
|
420
|
+
fileName: input2.fileName ?? path6.basename(input2.sourcePath),
|
|
421
|
+
createdAt: now,
|
|
422
|
+
updatedAt: now
|
|
423
|
+
});
|
|
424
|
+
return id;
|
|
425
|
+
}
|
|
426
|
+
complete(input2) {
|
|
427
|
+
this.database.prepare(
|
|
428
|
+
`
|
|
429
|
+
UPDATE file_jobs
|
|
430
|
+
SET
|
|
431
|
+
stored_path = @storedPath,
|
|
432
|
+
status = 'indexed',
|
|
433
|
+
parser = @parser,
|
|
434
|
+
message_id = @messageId,
|
|
435
|
+
bytes = @bytes,
|
|
436
|
+
characters = @characters,
|
|
437
|
+
warnings_json = @warningsJson,
|
|
438
|
+
error = NULL,
|
|
439
|
+
updated_at = @updatedAt
|
|
440
|
+
WHERE id = @id
|
|
441
|
+
`
|
|
442
|
+
).run({
|
|
443
|
+
id: input2.id,
|
|
444
|
+
storedPath: input2.storedPath,
|
|
445
|
+
parser: input2.parser,
|
|
446
|
+
messageId: input2.messageId,
|
|
447
|
+
bytes: input2.bytes,
|
|
448
|
+
characters: input2.characters,
|
|
449
|
+
warningsJson: JSON.stringify(input2.warnings),
|
|
450
|
+
updatedAt: nowIso()
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
fail(input2) {
|
|
454
|
+
this.database.prepare(
|
|
455
|
+
`
|
|
456
|
+
UPDATE file_jobs
|
|
457
|
+
SET status = 'failed', error = @error, updated_at = @updatedAt
|
|
458
|
+
WHERE id = @id
|
|
459
|
+
`
|
|
460
|
+
).run({
|
|
461
|
+
id: input2.id,
|
|
462
|
+
error: input2.error,
|
|
463
|
+
updatedAt: nowIso()
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
get(id) {
|
|
467
|
+
return this.listByWhere("WHERE id = ?", [id], 1)[0] ?? null;
|
|
468
|
+
}
|
|
469
|
+
list(limit = 50, options = {}) {
|
|
470
|
+
return options.status ? this.listByWhere("WHERE status = ?", [options.status], limit) : this.listByWhere("", [], limit);
|
|
471
|
+
}
|
|
472
|
+
listByWhere(whereSql, params, limit) {
|
|
473
|
+
const rows = this.database.prepare(
|
|
474
|
+
`
|
|
475
|
+
SELECT
|
|
476
|
+
id,
|
|
477
|
+
source_path AS sourcePath,
|
|
478
|
+
stored_path AS storedPath,
|
|
479
|
+
file_name AS fileName,
|
|
480
|
+
status,
|
|
481
|
+
parser,
|
|
482
|
+
message_id AS messageId,
|
|
483
|
+
bytes,
|
|
484
|
+
characters,
|
|
485
|
+
warnings_json AS warningsJson,
|
|
486
|
+
error,
|
|
487
|
+
created_at AS createdAt,
|
|
488
|
+
updated_at AS updatedAt
|
|
489
|
+
FROM file_jobs
|
|
490
|
+
${whereSql}
|
|
491
|
+
ORDER BY updated_at DESC
|
|
492
|
+
LIMIT ?
|
|
493
|
+
`
|
|
494
|
+
).all(...params, limit);
|
|
495
|
+
return rows.map((row) => ({
|
|
496
|
+
id: row.id,
|
|
497
|
+
sourcePath: row.sourcePath,
|
|
498
|
+
storedPath: row.storedPath ?? void 0,
|
|
499
|
+
fileName: row.fileName,
|
|
500
|
+
status: row.status,
|
|
501
|
+
parser: row.parser ?? void 0,
|
|
502
|
+
messageId: row.messageId ?? void 0,
|
|
503
|
+
bytes: row.bytes ?? void 0,
|
|
504
|
+
characters: row.characters ?? void 0,
|
|
505
|
+
warnings: parseWarnings(row.warningsJson),
|
|
506
|
+
error: row.error ?? void 0,
|
|
507
|
+
createdAt: row.createdAt,
|
|
508
|
+
updatedAt: row.updatedAt
|
|
509
|
+
}));
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
// src/gateway/runtime.ts
|
|
514
|
+
import fs4 from "fs";
|
|
515
|
+
import path7 from "path";
|
|
516
|
+
function getGatewayPidPath() {
|
|
517
|
+
return path7.join(getChatterCatcherHome(), "gateway.pid");
|
|
518
|
+
}
|
|
519
|
+
function isProcessRunning(pid) {
|
|
520
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
521
|
+
return false;
|
|
522
|
+
}
|
|
523
|
+
try {
|
|
524
|
+
process.kill(pid, 0);
|
|
525
|
+
return true;
|
|
526
|
+
} catch {
|
|
527
|
+
return false;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function readGatewayPidRecord(pidFile = getGatewayPidPath()) {
|
|
531
|
+
try {
|
|
532
|
+
const raw = fs4.readFileSync(pidFile, "utf8");
|
|
533
|
+
const parsed = JSON.parse(raw);
|
|
534
|
+
if (!Number.isInteger(parsed.pid) || typeof parsed.startedAt !== "string" || typeof parsed.command !== "string") {
|
|
535
|
+
return null;
|
|
536
|
+
}
|
|
537
|
+
const pid = parsed.pid;
|
|
538
|
+
if (pid === void 0) {
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
return {
|
|
542
|
+
pid,
|
|
543
|
+
startedAt: parsed.startedAt,
|
|
544
|
+
command: parsed.command
|
|
545
|
+
};
|
|
546
|
+
} catch (error) {
|
|
547
|
+
if (error.code === "ENOENT") {
|
|
548
|
+
return null;
|
|
549
|
+
}
|
|
550
|
+
return null;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function writeGatewayPidRecord(pidFile = getGatewayPidPath(), record = {
|
|
554
|
+
pid: process.pid,
|
|
555
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
556
|
+
command: process.argv.join(" ")
|
|
557
|
+
}) {
|
|
558
|
+
fs4.mkdirSync(path7.dirname(pidFile), { recursive: true });
|
|
559
|
+
fs4.writeFileSync(pidFile, `${JSON.stringify(record, null, 2)}
|
|
560
|
+
`, "utf8");
|
|
561
|
+
}
|
|
562
|
+
function removeGatewayPidRecord(pidFile = getGatewayPidPath()) {
|
|
563
|
+
try {
|
|
564
|
+
fs4.rmSync(pidFile, { force: true });
|
|
565
|
+
} catch {
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
function getGatewayRuntimeState(pidFile = getGatewayPidPath()) {
|
|
569
|
+
const record = readGatewayPidRecord(pidFile);
|
|
570
|
+
const running = record ? isProcessRunning(record.pid) : false;
|
|
571
|
+
return {
|
|
572
|
+
pidFile,
|
|
573
|
+
record,
|
|
574
|
+
running,
|
|
575
|
+
stale: Boolean(record && !running)
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
function stopGatewayProcess(pidFile = getGatewayPidPath()) {
|
|
579
|
+
const state = getGatewayRuntimeState(pidFile);
|
|
580
|
+
if (!state.record) {
|
|
581
|
+
return {
|
|
582
|
+
stopped: false,
|
|
583
|
+
message: "Gateway \u6CA1\u6709\u8FD0\u884C\u8BB0\u5F55\u3002"
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
if (state.stale) {
|
|
587
|
+
removeGatewayPidRecord(pidFile);
|
|
588
|
+
return {
|
|
589
|
+
stopped: false,
|
|
590
|
+
message: `Gateway PID \u6587\u4EF6\u5DF2\u8FC7\u671F\uFF0C\u5DF2\u6E05\u7406\uFF1A${state.record.pid}`
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
if (state.record.pid === process.pid) {
|
|
594
|
+
return {
|
|
595
|
+
stopped: false,
|
|
596
|
+
message: "\u62D2\u7EDD\u505C\u6B62\u5F53\u524D CLI \u8FDB\u7A0B\uFF1B\u8BF7\u5728\u53E6\u4E00\u4E2A\u7EC8\u7AEF\u8FD0\u884C stop\uFF0C\u6216\u6309 Ctrl+C\u3002"
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
try {
|
|
600
|
+
process.kill(state.record.pid, "SIGTERM");
|
|
601
|
+
removeGatewayPidRecord(pidFile);
|
|
602
|
+
return {
|
|
603
|
+
stopped: true,
|
|
604
|
+
message: `\u5DF2\u5411 Gateway \u8FDB\u7A0B\u53D1\u9001\u505C\u6B62\u4FE1\u53F7\uFF1Apid=${state.record.pid}`
|
|
605
|
+
};
|
|
606
|
+
} catch (error) {
|
|
607
|
+
return {
|
|
608
|
+
stopped: false,
|
|
609
|
+
message: `\u505C\u6B62 Gateway \u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// src/gateway/index.ts
|
|
615
|
+
function getGatewayStatus(config, secrets) {
|
|
616
|
+
if (!config.feishu.appId) {
|
|
617
|
+
return {
|
|
618
|
+
configured: false,
|
|
619
|
+
connection: "not_configured",
|
|
620
|
+
message: "\u5C1A\u672A\u914D\u7F6E\u98DE\u4E66 App ID\u3002\u8BF7\u8FD0\u884C chattercatcher setup \u6216 chattercatcher settings\u3002"
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
if (secrets && !secrets.feishu.appSecret) {
|
|
624
|
+
return {
|
|
625
|
+
configured: false,
|
|
626
|
+
connection: "not_configured",
|
|
627
|
+
message: "\u5C1A\u672A\u914D\u7F6E\u98DE\u4E66 App Secret\u3002\u8BF7\u8FD0\u884C chattercatcher setup \u6216 chattercatcher settings\u3002"
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
const runtime = getGatewayRuntimeState();
|
|
631
|
+
if (runtime.running && runtime.record) {
|
|
632
|
+
return {
|
|
633
|
+
configured: true,
|
|
634
|
+
connection: "running",
|
|
635
|
+
message: `\u98DE\u4E66 Gateway \u6B63\u5728\u8FD0\u884C\uFF1Apid=${runtime.record.pid}\uFF0CstartedAt=${runtime.record.startedAt}`,
|
|
636
|
+
pid: runtime.record.pid,
|
|
637
|
+
pidFile: runtime.pidFile
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
if (runtime.stale && runtime.record) {
|
|
641
|
+
return {
|
|
642
|
+
configured: true,
|
|
643
|
+
connection: "ready_for_start",
|
|
644
|
+
message: `\u98DE\u4E66\u957F\u8FDE\u63A5\u914D\u7F6E\u5DF2\u5C31\u7EEA\uFF1B\u53D1\u73B0\u8FC7\u671F PID \u6587\u4EF6\uFF1Apid=${runtime.record.pid}\u3002\u8FD0\u884C chattercatcher gateway start \u4F1A\u8986\u76D6\u8FD0\u884C\u8BB0\u5F55\u3002`,
|
|
645
|
+
pid: runtime.record.pid,
|
|
646
|
+
pidFile: runtime.pidFile
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
return {
|
|
650
|
+
configured: true,
|
|
651
|
+
connection: "ready_for_start",
|
|
652
|
+
message: "\u98DE\u4E66\u957F\u8FDE\u63A5\u914D\u7F6E\u5DF2\u5C31\u7EEA\u3002\u8FD0\u884C chattercatcher gateway start \u540E\u4F1A\u63A5\u6536 im.message.receive_v1 \u4E8B\u4EF6\u3002",
|
|
653
|
+
pidFile: runtime.pidFile
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// src/llm/openai-compatible.ts
|
|
658
|
+
function normalizeBaseUrl(baseUrl) {
|
|
659
|
+
return baseUrl.replace(/\/+$/, "");
|
|
660
|
+
}
|
|
661
|
+
var OpenAICompatibleChatModel = class {
|
|
662
|
+
constructor(options) {
|
|
663
|
+
this.options = options;
|
|
664
|
+
}
|
|
665
|
+
options;
|
|
666
|
+
async complete(messages) {
|
|
667
|
+
if (!this.options.baseUrl || !this.options.apiKey || !this.options.model) {
|
|
668
|
+
throw new Error("LLM \u914D\u7F6E\u4E0D\u5B8C\u6574\u3002\u8BF7\u8FD0\u884C chattercatcher setup \u6216 chattercatcher settings\u3002");
|
|
669
|
+
}
|
|
670
|
+
const response = await fetch(`${normalizeBaseUrl(this.options.baseUrl)}/chat/completions`, {
|
|
671
|
+
method: "POST",
|
|
672
|
+
headers: {
|
|
673
|
+
authorization: `Bearer ${this.options.apiKey}`,
|
|
674
|
+
"content-type": "application/json"
|
|
675
|
+
},
|
|
676
|
+
body: JSON.stringify({
|
|
677
|
+
model: this.options.model,
|
|
678
|
+
messages,
|
|
679
|
+
temperature: this.options.temperature ?? 0.2
|
|
680
|
+
})
|
|
681
|
+
});
|
|
682
|
+
if (!response.ok) {
|
|
683
|
+
const body = await response.text();
|
|
684
|
+
throw new Error(`LLM \u8BF7\u6C42\u5931\u8D25\uFF1A${response.status} ${body}`);
|
|
685
|
+
}
|
|
686
|
+
const data2 = await response.json();
|
|
687
|
+
const content = data2.choices?.[0]?.message?.content?.trim();
|
|
688
|
+
if (!content) {
|
|
689
|
+
throw new Error("LLM \u8FD4\u56DE\u4E3A\u7A7A\u3002");
|
|
690
|
+
}
|
|
691
|
+
return content;
|
|
692
|
+
}
|
|
693
|
+
};
|
|
694
|
+
var OpenAICompatibleEmbeddingModel = class {
|
|
695
|
+
constructor(options) {
|
|
696
|
+
this.options = options;
|
|
697
|
+
}
|
|
698
|
+
options;
|
|
699
|
+
async embed(text) {
|
|
700
|
+
const [vector] = await this.embedBatch([text]);
|
|
701
|
+
return vector ?? [];
|
|
702
|
+
}
|
|
703
|
+
async embedBatch(texts) {
|
|
704
|
+
if (!this.options.baseUrl || !this.options.apiKey || !this.options.model) {
|
|
705
|
+
throw new Error("Embedding \u914D\u7F6E\u4E0D\u5B8C\u6574\u3002\u8BF7\u8FD0\u884C chattercatcher setup \u6216 chattercatcher settings\u3002");
|
|
706
|
+
}
|
|
707
|
+
const response = await fetch(`${normalizeBaseUrl(this.options.baseUrl)}/embeddings`, {
|
|
708
|
+
method: "POST",
|
|
709
|
+
headers: {
|
|
710
|
+
authorization: `Bearer ${this.options.apiKey}`,
|
|
711
|
+
"content-type": "application/json"
|
|
712
|
+
},
|
|
713
|
+
body: JSON.stringify({
|
|
714
|
+
model: this.options.model,
|
|
715
|
+
input: texts
|
|
716
|
+
})
|
|
717
|
+
});
|
|
718
|
+
if (!response.ok) {
|
|
719
|
+
const body = await response.text();
|
|
720
|
+
throw new Error(`Embedding \u8BF7\u6C42\u5931\u8D25\uFF1A${response.status} ${body}`);
|
|
721
|
+
}
|
|
722
|
+
const data2 = await response.json();
|
|
723
|
+
return data2.data?.map((item) => item.embedding ?? []) ?? [];
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
function createChatModel(config, secrets) {
|
|
727
|
+
return new OpenAICompatibleChatModel({
|
|
728
|
+
baseUrl: config.llm.baseUrl,
|
|
729
|
+
apiKey: secrets.llm.apiKey,
|
|
730
|
+
model: config.llm.model
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
function createEmbeddingModel(config, secrets) {
|
|
734
|
+
return new OpenAICompatibleEmbeddingModel({
|
|
735
|
+
baseUrl: config.embedding.baseUrl || config.llm.baseUrl,
|
|
736
|
+
apiKey: secrets.embedding.apiKey || secrets.llm.apiKey,
|
|
737
|
+
model: config.embedding.model
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// src/messages/repository.ts
|
|
742
|
+
import crypto2 from "crypto";
|
|
743
|
+
|
|
744
|
+
// src/messages/chunker.ts
|
|
745
|
+
function chunkText(text, maxChars = 900, overlapChars = 120) {
|
|
746
|
+
const normalized = text.trim().replace(/\s+/g, " ");
|
|
747
|
+
if (!normalized) {
|
|
748
|
+
return [];
|
|
749
|
+
}
|
|
750
|
+
if (normalized.length <= maxChars) {
|
|
751
|
+
return [{ index: 0, text: normalized }];
|
|
752
|
+
}
|
|
753
|
+
const chunks = [];
|
|
754
|
+
let cursor = 0;
|
|
755
|
+
while (cursor < normalized.length) {
|
|
756
|
+
const end = Math.min(cursor + maxChars, normalized.length);
|
|
757
|
+
chunks.push({ index: chunks.length, text: normalized.slice(cursor, end) });
|
|
758
|
+
if (end === normalized.length) {
|
|
759
|
+
break;
|
|
760
|
+
}
|
|
761
|
+
cursor = Math.max(end - overlapChars, cursor + 1);
|
|
762
|
+
}
|
|
763
|
+
return chunks;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// src/messages/repository.ts
|
|
767
|
+
function nowIso2() {
|
|
768
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
769
|
+
}
|
|
770
|
+
function stableId(parts) {
|
|
771
|
+
return crypto2.createHash("sha256").update(parts.join("")).digest("hex").slice(0, 32);
|
|
772
|
+
}
|
|
773
|
+
function escapeFtsQuery(query) {
|
|
774
|
+
const terms = query.trim().split(/\s+/).map((term) => term.replace(/"/g, '""')).filter(Boolean);
|
|
775
|
+
if (terms.length === 0) {
|
|
776
|
+
return '""';
|
|
777
|
+
}
|
|
778
|
+
return terms.map((term) => `"${term}"`).join(" OR ");
|
|
779
|
+
}
|
|
780
|
+
function escapeLikeTerm(term) {
|
|
781
|
+
return term.replace(/[\\%_]/g, (match) => `\\${match}`);
|
|
782
|
+
}
|
|
783
|
+
function buildSearchTerms(query) {
|
|
784
|
+
const trimmed = query.trim();
|
|
785
|
+
if (!trimmed) {
|
|
786
|
+
return [];
|
|
787
|
+
}
|
|
788
|
+
const terms = trimmed.split(/\s+/).filter(Boolean);
|
|
789
|
+
if (terms.length > 1) {
|
|
790
|
+
return terms;
|
|
791
|
+
}
|
|
792
|
+
if (/[\u3400-\u9fff]/.test(trimmed) && trimmed.length > 2) {
|
|
793
|
+
const cjkTerms = /* @__PURE__ */ new Set([trimmed]);
|
|
794
|
+
for (let index2 = 0; index2 < trimmed.length - 1; index2 += 1) {
|
|
795
|
+
cjkTerms.add(trimmed.slice(index2, index2 + 2));
|
|
796
|
+
}
|
|
797
|
+
return [...cjkTerms];
|
|
798
|
+
}
|
|
799
|
+
return [trimmed];
|
|
800
|
+
}
|
|
801
|
+
function parseRawPayload(value) {
|
|
802
|
+
try {
|
|
803
|
+
const parsed = JSON.parse(value);
|
|
804
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
805
|
+
} catch {
|
|
806
|
+
return {};
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
var MessageRepository = class {
|
|
810
|
+
constructor(database) {
|
|
811
|
+
this.database = database;
|
|
812
|
+
}
|
|
813
|
+
database;
|
|
814
|
+
ingest(input2) {
|
|
815
|
+
const createdAt = nowIso2();
|
|
816
|
+
const chatId = stableId([input2.platform, input2.platformChatId]);
|
|
817
|
+
const messageId = stableId([input2.platform, input2.platformMessageId]);
|
|
818
|
+
const rawPayloadJson = JSON.stringify(input2.rawPayload ?? {});
|
|
819
|
+
const chunks = chunkText(input2.text);
|
|
820
|
+
const transaction = this.database.transaction(() => {
|
|
821
|
+
this.database.prepare(
|
|
822
|
+
`
|
|
823
|
+
INSERT INTO chats (id, platform, platform_chat_id, name, created_at, updated_at)
|
|
824
|
+
VALUES (@id, @platform, @platformChatId, @name, @createdAt, @updatedAt)
|
|
825
|
+
ON CONFLICT(platform, platform_chat_id)
|
|
826
|
+
DO UPDATE SET name = excluded.name, updated_at = excluded.updated_at
|
|
827
|
+
`
|
|
828
|
+
).run({
|
|
829
|
+
id: chatId,
|
|
830
|
+
platform: input2.platform,
|
|
831
|
+
platformChatId: input2.platformChatId,
|
|
832
|
+
name: input2.chatName,
|
|
833
|
+
createdAt,
|
|
834
|
+
updatedAt: createdAt
|
|
835
|
+
});
|
|
836
|
+
this.database.prepare(
|
|
837
|
+
`
|
|
838
|
+
INSERT INTO messages (
|
|
839
|
+
id, platform, platform_message_id, chat_id, sender_id, sender_name,
|
|
840
|
+
message_type, text, raw_payload_json, sent_at, received_at, created_at
|
|
841
|
+
)
|
|
842
|
+
VALUES (
|
|
843
|
+
@id, @platform, @platformMessageId, @chatId, @senderId, @senderName,
|
|
844
|
+
@messageType, @text, @rawPayloadJson, @sentAt, @receivedAt, @createdAt
|
|
845
|
+
)
|
|
846
|
+
ON CONFLICT(platform, platform_message_id)
|
|
847
|
+
DO UPDATE SET
|
|
848
|
+
text = excluded.text,
|
|
849
|
+
raw_payload_json = excluded.raw_payload_json,
|
|
850
|
+
received_at = excluded.received_at
|
|
851
|
+
`
|
|
852
|
+
).run({
|
|
853
|
+
id: messageId,
|
|
854
|
+
platform: input2.platform,
|
|
855
|
+
platformMessageId: input2.platformMessageId,
|
|
856
|
+
chatId,
|
|
857
|
+
senderId: input2.senderId,
|
|
858
|
+
senderName: input2.senderName,
|
|
859
|
+
messageType: input2.messageType,
|
|
860
|
+
text: input2.text,
|
|
861
|
+
rawPayloadJson,
|
|
862
|
+
sentAt: input2.sentAt,
|
|
863
|
+
receivedAt: createdAt,
|
|
864
|
+
createdAt
|
|
865
|
+
});
|
|
866
|
+
this.database.prepare("DELETE FROM message_chunks_fts WHERE message_id = ?").run(messageId);
|
|
867
|
+
this.database.prepare("DELETE FROM message_chunks WHERE message_id = ?").run(messageId);
|
|
868
|
+
const insertChunk = this.database.prepare(`
|
|
869
|
+
INSERT INTO message_chunks (id, message_id, chunk_index, text, metadata_json, created_at)
|
|
870
|
+
VALUES (@id, @messageId, @chunkIndex, @text, @metadataJson, @createdAt)
|
|
871
|
+
`);
|
|
872
|
+
const insertFts = this.database.prepare(`
|
|
873
|
+
INSERT INTO message_chunks_fts (text, chunk_id, message_id)
|
|
874
|
+
VALUES (@text, @chunkId, @messageId)
|
|
875
|
+
`);
|
|
876
|
+
for (const chunk of chunks) {
|
|
877
|
+
const chunkId = stableId([messageId, String(chunk.index)]);
|
|
878
|
+
insertChunk.run({
|
|
879
|
+
id: chunkId,
|
|
880
|
+
messageId,
|
|
881
|
+
chunkIndex: chunk.index,
|
|
882
|
+
text: chunk.text,
|
|
883
|
+
metadataJson: JSON.stringify({ sourceType: "message" }),
|
|
884
|
+
createdAt
|
|
885
|
+
});
|
|
886
|
+
insertFts.run({ text: chunk.text, chunkId, messageId });
|
|
887
|
+
}
|
|
888
|
+
});
|
|
889
|
+
transaction();
|
|
890
|
+
return messageId;
|
|
891
|
+
}
|
|
892
|
+
listRecentMessages(limit = 20) {
|
|
893
|
+
return this.database.prepare(
|
|
894
|
+
`
|
|
895
|
+
SELECT
|
|
896
|
+
mc.id AS chunkId,
|
|
897
|
+
m.id AS messageId,
|
|
898
|
+
m.platform AS platform,
|
|
899
|
+
mc.text AS text,
|
|
900
|
+
1.0 AS score,
|
|
901
|
+
m.message_type AS messageType,
|
|
902
|
+
c.name AS chatName,
|
|
903
|
+
m.sender_name AS senderName,
|
|
904
|
+
m.sent_at AS sentAt
|
|
905
|
+
FROM message_chunks mc
|
|
906
|
+
JOIN messages m ON m.id = mc.message_id
|
|
907
|
+
JOIN chats c ON c.id = m.chat_id
|
|
908
|
+
ORDER BY m.sent_at DESC
|
|
909
|
+
LIMIT ?
|
|
910
|
+
`
|
|
911
|
+
).all(limit);
|
|
912
|
+
}
|
|
913
|
+
listAllMessageChunks(limit = 1e4) {
|
|
914
|
+
return this.database.prepare(
|
|
915
|
+
`
|
|
916
|
+
SELECT
|
|
917
|
+
mc.id AS chunkId,
|
|
918
|
+
m.id AS messageId,
|
|
919
|
+
m.platform AS platform,
|
|
920
|
+
mc.text AS text,
|
|
921
|
+
1.0 AS score,
|
|
922
|
+
m.message_type AS messageType,
|
|
923
|
+
c.name AS chatName,
|
|
924
|
+
m.sender_name AS senderName,
|
|
925
|
+
m.sent_at AS sentAt
|
|
926
|
+
FROM message_chunks mc
|
|
927
|
+
JOIN messages m ON m.id = mc.message_id
|
|
928
|
+
JOIN chats c ON c.id = m.chat_id
|
|
929
|
+
ORDER BY m.sent_at DESC, mc.chunk_index ASC
|
|
930
|
+
LIMIT ?
|
|
931
|
+
`
|
|
932
|
+
).all(limit);
|
|
933
|
+
}
|
|
934
|
+
listMessageChunksByMessageIds(messageIds, limit = 1e4) {
|
|
935
|
+
if (messageIds.length === 0) {
|
|
936
|
+
return [];
|
|
937
|
+
}
|
|
938
|
+
return this.database.prepare(
|
|
939
|
+
`
|
|
940
|
+
SELECT
|
|
941
|
+
mc.id AS chunkId,
|
|
942
|
+
m.id AS messageId,
|
|
943
|
+
m.platform AS platform,
|
|
944
|
+
mc.text AS text,
|
|
945
|
+
1.0 AS score,
|
|
946
|
+
m.message_type AS messageType,
|
|
947
|
+
c.name AS chatName,
|
|
948
|
+
m.sender_name AS senderName,
|
|
949
|
+
m.sent_at AS sentAt
|
|
950
|
+
FROM message_chunks mc
|
|
951
|
+
JOIN messages m ON m.id = mc.message_id
|
|
952
|
+
JOIN chats c ON c.id = m.chat_id
|
|
953
|
+
WHERE m.id IN (${messageIds.map(() => "?").join(", ")})
|
|
954
|
+
ORDER BY m.sent_at DESC, mc.chunk_index ASC
|
|
955
|
+
LIMIT ?
|
|
956
|
+
`
|
|
957
|
+
).all(...messageIds, limit);
|
|
958
|
+
}
|
|
959
|
+
searchMessages(query, limit = 8, options = {}) {
|
|
960
|
+
const ftsQuery = escapeFtsQuery(query);
|
|
961
|
+
const excludedIds = options.excludeMessageIds ?? [];
|
|
962
|
+
const excludedWhere = excludedIds.length > 0 ? `AND fts.message_id NOT IN (${excludedIds.map(() => "?").join(", ")})` : "";
|
|
963
|
+
const ftsResults = this.database.prepare(
|
|
964
|
+
`
|
|
965
|
+
SELECT
|
|
966
|
+
fts.chunk_id AS chunkId,
|
|
967
|
+
fts.message_id AS messageId,
|
|
968
|
+
m.platform AS platform,
|
|
969
|
+
mc.text AS text,
|
|
970
|
+
bm25(message_chunks_fts) * -1 AS score,
|
|
971
|
+
m.message_type AS messageType,
|
|
972
|
+
c.name AS chatName,
|
|
973
|
+
m.sender_name AS senderName,
|
|
974
|
+
m.sent_at AS sentAt
|
|
975
|
+
FROM message_chunks_fts fts
|
|
976
|
+
JOIN message_chunks mc ON mc.id = fts.chunk_id
|
|
977
|
+
JOIN messages m ON m.id = fts.message_id
|
|
978
|
+
JOIN chats c ON c.id = m.chat_id
|
|
979
|
+
WHERE message_chunks_fts MATCH ?
|
|
980
|
+
${excludedWhere}
|
|
981
|
+
ORDER BY bm25(message_chunks_fts)
|
|
982
|
+
LIMIT ?
|
|
983
|
+
`
|
|
984
|
+
).all(ftsQuery, ...excludedIds, limit);
|
|
985
|
+
if (ftsResults.length > 0) {
|
|
986
|
+
return ftsResults;
|
|
987
|
+
}
|
|
988
|
+
const terms = buildSearchTerms(query);
|
|
989
|
+
if (terms.length === 0) {
|
|
990
|
+
return [];
|
|
991
|
+
}
|
|
992
|
+
const where = terms.map(() => "mc.text LIKE ? ESCAPE '\\'").join(" OR ");
|
|
993
|
+
const params = terms.map((term) => `%${escapeLikeTerm(term)}%`);
|
|
994
|
+
const likeExcludedWhere = excludedIds.length > 0 ? `AND m.id NOT IN (${excludedIds.map(() => "?").join(", ")})` : "";
|
|
995
|
+
return this.database.prepare(
|
|
996
|
+
`
|
|
997
|
+
SELECT
|
|
998
|
+
mc.id AS chunkId,
|
|
999
|
+
m.id AS messageId,
|
|
1000
|
+
m.platform AS platform,
|
|
1001
|
+
mc.text AS text,
|
|
1002
|
+
0.1 AS score,
|
|
1003
|
+
m.message_type AS messageType,
|
|
1004
|
+
c.name AS chatName,
|
|
1005
|
+
m.sender_name AS senderName,
|
|
1006
|
+
m.sent_at AS sentAt
|
|
1007
|
+
FROM message_chunks mc
|
|
1008
|
+
JOIN messages m ON m.id = mc.message_id
|
|
1009
|
+
JOIN chats c ON c.id = m.chat_id
|
|
1010
|
+
WHERE (${where})
|
|
1011
|
+
${likeExcludedWhere}
|
|
1012
|
+
ORDER BY m.sent_at DESC
|
|
1013
|
+
LIMIT ?
|
|
1014
|
+
`
|
|
1015
|
+
).all(...params, ...excludedIds, limit);
|
|
1016
|
+
}
|
|
1017
|
+
getChatCount() {
|
|
1018
|
+
return this.database.prepare("SELECT COUNT(*) AS count FROM chats").get().count;
|
|
1019
|
+
}
|
|
1020
|
+
getMessageCount() {
|
|
1021
|
+
return this.database.prepare("SELECT COUNT(*) AS count FROM messages").get().count;
|
|
1022
|
+
}
|
|
1023
|
+
hasPlatformMessage(platform, platformMessageId) {
|
|
1024
|
+
const row = this.database.prepare("SELECT 1 AS existsFlag FROM messages WHERE platform = ? AND platform_message_id = ? LIMIT 1").get(platform, platformMessageId);
|
|
1025
|
+
return Boolean(row);
|
|
1026
|
+
}
|
|
1027
|
+
listChats() {
|
|
1028
|
+
return this.database.prepare(
|
|
1029
|
+
`
|
|
1030
|
+
SELECT
|
|
1031
|
+
id,
|
|
1032
|
+
platform,
|
|
1033
|
+
platform_chat_id AS platformChatId,
|
|
1034
|
+
name,
|
|
1035
|
+
created_at AS createdAt,
|
|
1036
|
+
updated_at AS updatedAt
|
|
1037
|
+
FROM chats
|
|
1038
|
+
ORDER BY updated_at DESC
|
|
1039
|
+
`
|
|
1040
|
+
).all();
|
|
1041
|
+
}
|
|
1042
|
+
listFiles(limit = 50) {
|
|
1043
|
+
const rows = this.database.prepare(
|
|
1044
|
+
`
|
|
1045
|
+
SELECT
|
|
1046
|
+
id AS messageId,
|
|
1047
|
+
sender_name AS fileName,
|
|
1048
|
+
raw_payload_json AS rawPayloadJson,
|
|
1049
|
+
length(text) AS characters,
|
|
1050
|
+
created_at AS importedAt
|
|
1051
|
+
FROM messages
|
|
1052
|
+
WHERE message_type = 'file'
|
|
1053
|
+
ORDER BY created_at DESC
|
|
1054
|
+
LIMIT ?
|
|
1055
|
+
`
|
|
1056
|
+
).all(limit);
|
|
1057
|
+
return rows.map((row) => {
|
|
1058
|
+
const payload = parseRawPayload(row.rawPayloadJson);
|
|
1059
|
+
return {
|
|
1060
|
+
messageId: row.messageId,
|
|
1061
|
+
fileName: row.fileName,
|
|
1062
|
+
sourcePath: typeof payload.sourcePath === "string" ? payload.sourcePath : void 0,
|
|
1063
|
+
storedPath: typeof payload.storedPath === "string" ? payload.storedPath : void 0,
|
|
1064
|
+
bytes: typeof payload.bytes === "number" ? payload.bytes : void 0,
|
|
1065
|
+
characters: row.characters,
|
|
1066
|
+
parser: typeof payload.parser === "string" ? payload.parser : void 0,
|
|
1067
|
+
parserWarnings: Array.isArray(payload.parserWarnings) ? payload.parserWarnings.filter((item) => typeof item === "string") : void 0,
|
|
1068
|
+
importedAt: row.importedAt
|
|
1069
|
+
};
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
};
|
|
1073
|
+
|
|
1074
|
+
// src/rag/hybrid-retriever.ts
|
|
1075
|
+
function normalizeScore(score) {
|
|
1076
|
+
if (!Number.isFinite(score)) {
|
|
1077
|
+
return 0;
|
|
1078
|
+
}
|
|
1079
|
+
return Math.max(0, Math.min(1, score));
|
|
1080
|
+
}
|
|
1081
|
+
var HybridRetriever = class {
|
|
1082
|
+
constructor(retrievers, options = {}) {
|
|
1083
|
+
this.retrievers = retrievers;
|
|
1084
|
+
this.options = options;
|
|
1085
|
+
}
|
|
1086
|
+
retrievers;
|
|
1087
|
+
options;
|
|
1088
|
+
async retrieve(question) {
|
|
1089
|
+
const results = await Promise.all(this.retrievers.map((retriever) => retriever.retrieve(question)));
|
|
1090
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1091
|
+
for (const [retrieverIndex, evidenceList] of results.entries()) {
|
|
1092
|
+
for (const evidence of evidenceList) {
|
|
1093
|
+
const existing = merged.get(evidence.id);
|
|
1094
|
+
const weightedScore = normalizeScore(evidence.score) + (this.retrievers.length - retrieverIndex) * 0.01;
|
|
1095
|
+
if (!existing || weightedScore > existing.score) {
|
|
1096
|
+
merged.set(evidence.id, {
|
|
1097
|
+
...evidence,
|
|
1098
|
+
score: weightedScore
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
return [...merged.values()].sort((left, right) => right.score - left.score).slice(0, this.options.limit ?? 8);
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
|
|
1107
|
+
// src/rag/message-retriever.ts
|
|
1108
|
+
function toEvidenceSource(result) {
|
|
1109
|
+
if (result.messageType === "file") {
|
|
1110
|
+
return {
|
|
1111
|
+
type: "file",
|
|
1112
|
+
label: result.senderName,
|
|
1113
|
+
timestamp: result.sentAt
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
return {
|
|
1117
|
+
type: "message",
|
|
1118
|
+
label: result.chatName,
|
|
1119
|
+
sender: result.senderName,
|
|
1120
|
+
timestamp: result.sentAt
|
|
1121
|
+
};
|
|
1122
|
+
}
|
|
1123
|
+
var MessageFtsRetriever = class {
|
|
1124
|
+
constructor(messages, options = {}) {
|
|
1125
|
+
this.messages = messages;
|
|
1126
|
+
this.options = options;
|
|
1127
|
+
}
|
|
1128
|
+
messages;
|
|
1129
|
+
options;
|
|
1130
|
+
async retrieve(question) {
|
|
1131
|
+
const results = this.messages.searchMessages(question, 8, {
|
|
1132
|
+
excludeMessageIds: this.options.excludeMessageIds
|
|
1133
|
+
});
|
|
1134
|
+
return results.map((result) => ({
|
|
1135
|
+
id: result.chunkId,
|
|
1136
|
+
text: result.text,
|
|
1137
|
+
score: result.score,
|
|
1138
|
+
source: toEvidenceSource(result)
|
|
1139
|
+
}));
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1143
|
+
// src/rag/embedding.ts
|
|
1144
|
+
function cosineSimilarity(left, right) {
|
|
1145
|
+
if (left.length === 0 || right.length === 0 || left.length !== right.length) {
|
|
1146
|
+
return 0;
|
|
1147
|
+
}
|
|
1148
|
+
let dot = 0;
|
|
1149
|
+
let leftNorm = 0;
|
|
1150
|
+
let rightNorm = 0;
|
|
1151
|
+
for (let index2 = 0; index2 < left.length; index2 += 1) {
|
|
1152
|
+
const leftValue = left[index2] ?? 0;
|
|
1153
|
+
const rightValue = right[index2] ?? 0;
|
|
1154
|
+
dot += leftValue * rightValue;
|
|
1155
|
+
leftNorm += leftValue * leftValue;
|
|
1156
|
+
rightNorm += rightValue * rightValue;
|
|
1157
|
+
}
|
|
1158
|
+
if (leftNorm === 0 || rightNorm === 0) {
|
|
1159
|
+
return 0;
|
|
1160
|
+
}
|
|
1161
|
+
return dot / (Math.sqrt(leftNorm) * Math.sqrt(rightNorm));
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
// src/rag/sqlite-vector-store.ts
|
|
1165
|
+
var SQLiteVectorStore = class {
|
|
1166
|
+
constructor(database) {
|
|
1167
|
+
this.database = database;
|
|
1168
|
+
}
|
|
1169
|
+
database;
|
|
1170
|
+
async upsert(records) {
|
|
1171
|
+
if (records.length === 0) {
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
const statement = this.database.prepare(`
|
|
1175
|
+
INSERT INTO message_chunk_vectors (chunk_id, vector_json, evidence_json, updated_at)
|
|
1176
|
+
VALUES (@chunkId, @vectorJson, @evidenceJson, @updatedAt)
|
|
1177
|
+
ON CONFLICT(chunk_id) DO UPDATE SET
|
|
1178
|
+
vector_json = excluded.vector_json,
|
|
1179
|
+
evidence_json = excluded.evidence_json,
|
|
1180
|
+
updated_at = excluded.updated_at
|
|
1181
|
+
`);
|
|
1182
|
+
const upsertMany = this.database.transaction((items) => {
|
|
1183
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1184
|
+
for (const item of items) {
|
|
1185
|
+
statement.run({
|
|
1186
|
+
chunkId: item.id,
|
|
1187
|
+
vectorJson: JSON.stringify(item.vector),
|
|
1188
|
+
evidenceJson: JSON.stringify(item.evidence),
|
|
1189
|
+
updatedAt
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
});
|
|
1193
|
+
upsertMany(records);
|
|
1194
|
+
}
|
|
1195
|
+
async search(vector, limit) {
|
|
1196
|
+
if (limit <= 0) {
|
|
1197
|
+
return [];
|
|
1198
|
+
}
|
|
1199
|
+
const rows = this.database.prepare("SELECT chunk_id, vector_json, evidence_json FROM message_chunk_vectors").all();
|
|
1200
|
+
return rows.map((row) => {
|
|
1201
|
+
const storedVector = JSON.parse(row.vector_json);
|
|
1202
|
+
const evidence = JSON.parse(row.evidence_json);
|
|
1203
|
+
const vectorScore = cosineSimilarity(vector, storedVector);
|
|
1204
|
+
return {
|
|
1205
|
+
...evidence,
|
|
1206
|
+
score: vectorScore,
|
|
1207
|
+
vectorScore
|
|
1208
|
+
};
|
|
1209
|
+
}).sort((left, right) => right.vectorScore - left.vectorScore).slice(0, limit);
|
|
1210
|
+
}
|
|
1211
|
+
async count() {
|
|
1212
|
+
const row = this.database.prepare("SELECT COUNT(*) AS count FROM message_chunk_vectors").get();
|
|
1213
|
+
return row.count;
|
|
1214
|
+
}
|
|
1215
|
+
close() {
|
|
1216
|
+
}
|
|
1217
|
+
};
|
|
55
1218
|
|
|
56
|
-
//
|
|
57
|
-
var
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
bugs: {
|
|
70
|
-
url: "https://github.com/FlashingChen2024/chattercatcher/issues"
|
|
71
|
-
},
|
|
72
|
-
bin: {
|
|
73
|
-
chattercatcher: "dist/cli.js"
|
|
74
|
-
},
|
|
75
|
-
files: [
|
|
76
|
-
"assets",
|
|
77
|
-
"dist",
|
|
78
|
-
"docs",
|
|
79
|
-
"README.md",
|
|
80
|
-
"AGENTS.md"
|
|
81
|
-
],
|
|
82
|
-
directories: {
|
|
83
|
-
doc: "docs"
|
|
84
|
-
},
|
|
85
|
-
scripts: {
|
|
86
|
-
build: "tsup",
|
|
87
|
-
dev: "tsx src/cli.ts",
|
|
88
|
-
lint: "tsc --noEmit",
|
|
89
|
-
typecheck: "tsc --noEmit",
|
|
90
|
-
test: "vitest run"
|
|
91
|
-
},
|
|
92
|
-
keywords: [
|
|
93
|
-
"feishu",
|
|
94
|
-
"lark",
|
|
95
|
-
"rag",
|
|
96
|
-
"local-first",
|
|
97
|
-
"knowledge-base"
|
|
98
|
-
],
|
|
99
|
-
author: "FlashingChen2024",
|
|
100
|
-
license: "MIT",
|
|
101
|
-
dependencies: {
|
|
102
|
-
"@inquirer/prompts": "^8.4.2",
|
|
103
|
-
"@lancedb/lancedb": "0.23.0",
|
|
104
|
-
"@larksuiteoapi/node-sdk": "^1.62.0",
|
|
105
|
-
"better-sqlite3": "^12.9.0",
|
|
106
|
-
commander: "^14.0.3",
|
|
107
|
-
fastify: "^5.8.5",
|
|
108
|
-
mammoth: "^1.12.0",
|
|
109
|
-
"pdf-parse": "^2.4.5",
|
|
110
|
-
pino: "^10.3.1",
|
|
111
|
-
zod: "^4.3.6"
|
|
112
|
-
},
|
|
113
|
-
devDependencies: {
|
|
114
|
-
"@types/better-sqlite3": "^7.6.13",
|
|
115
|
-
"@types/node": "^25.6.0",
|
|
116
|
-
"@types/yazl": "^3.3.1",
|
|
117
|
-
tsup: "^8.5.1",
|
|
118
|
-
tsx: "^4.21.0",
|
|
119
|
-
typescript: "^6.0.3",
|
|
120
|
-
vitest: "^4.1.5",
|
|
121
|
-
yazl: "^3.3.1"
|
|
1219
|
+
// src/rag/vector-retriever.ts
|
|
1220
|
+
var VectorRetriever = class {
|
|
1221
|
+
constructor(embedding, store, limit = 8) {
|
|
1222
|
+
this.embedding = embedding;
|
|
1223
|
+
this.store = store;
|
|
1224
|
+
this.limit = limit;
|
|
1225
|
+
}
|
|
1226
|
+
embedding;
|
|
1227
|
+
store;
|
|
1228
|
+
limit;
|
|
1229
|
+
async retrieve(question) {
|
|
1230
|
+
const vector = await this.embedding.embed(question);
|
|
1231
|
+
return this.store.search(vector, this.limit);
|
|
122
1232
|
}
|
|
123
1233
|
};
|
|
124
1234
|
|
|
1235
|
+
// src/rag/factory.ts
|
|
1236
|
+
function hasEmbeddingConfig(config, secrets) {
|
|
1237
|
+
return Boolean((config.embedding.baseUrl || config.llm.baseUrl) && config.embedding.model && (secrets.embedding.apiKey || secrets.llm.apiKey));
|
|
1238
|
+
}
|
|
1239
|
+
async function createHybridRetriever(input2) {
|
|
1240
|
+
const retrievers = [new MessageFtsRetriever(input2.messages, { excludeMessageIds: input2.excludeMessageIds })];
|
|
1241
|
+
const closers = [];
|
|
1242
|
+
if (hasEmbeddingConfig(input2.config, input2.secrets)) {
|
|
1243
|
+
const vectorStore = new SQLiteVectorStore(input2.messages.database);
|
|
1244
|
+
retrievers.push(new VectorRetriever(createEmbeddingModel(input2.config, input2.secrets), vectorStore));
|
|
1245
|
+
closers.push(() => vectorStore.close());
|
|
1246
|
+
}
|
|
1247
|
+
return {
|
|
1248
|
+
retriever: new HybridRetriever(retrievers),
|
|
1249
|
+
close: () => {
|
|
1250
|
+
for (const closer of closers) {
|
|
1251
|
+
closer();
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
// src/doctor/checks.ts
|
|
1258
|
+
function pass(name, message) {
|
|
1259
|
+
return { name, status: "pass", message };
|
|
1260
|
+
}
|
|
1261
|
+
function warn(name, message) {
|
|
1262
|
+
return { name, status: "warn", message };
|
|
1263
|
+
}
|
|
1264
|
+
function fail(name, message) {
|
|
1265
|
+
return { name, status: "fail", message };
|
|
1266
|
+
}
|
|
1267
|
+
async function runDoctor(config, secrets, options = {}) {
|
|
1268
|
+
const checks = [];
|
|
1269
|
+
checks.push(await checkHomeDirectory());
|
|
1270
|
+
checks.push(checkFeishu(config, secrets));
|
|
1271
|
+
checks.push(checkLlmConfig(config, secrets));
|
|
1272
|
+
checks.push(checkEmbeddingConfig(config, secrets));
|
|
1273
|
+
checks.push(await checkSqlite(config));
|
|
1274
|
+
checks.push(await checkFilePipeline(config));
|
|
1275
|
+
checks.push(await checkSqliteVector(config));
|
|
1276
|
+
checks.push(checkRagPolicy());
|
|
1277
|
+
if (options.online) {
|
|
1278
|
+
checks.push(await checkChatModel(config, secrets));
|
|
1279
|
+
checks.push(await checkEmbeddingModel(config, secrets));
|
|
1280
|
+
}
|
|
1281
|
+
return checks;
|
|
1282
|
+
}
|
|
1283
|
+
async function checkHomeDirectory() {
|
|
1284
|
+
const home = getChatterCatcherHome();
|
|
1285
|
+
try {
|
|
1286
|
+
await fs5.mkdir(home, { recursive: true });
|
|
1287
|
+
await fs5.access(home);
|
|
1288
|
+
return pass("\u914D\u7F6E\u76EE\u5F55", home);
|
|
1289
|
+
} catch (error) {
|
|
1290
|
+
return fail("\u914D\u7F6E\u76EE\u5F55", error instanceof Error ? error.message : String(error));
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
function checkFeishu(config, secrets) {
|
|
1294
|
+
const status = getGatewayStatus(config, secrets);
|
|
1295
|
+
if (status.configured) {
|
|
1296
|
+
return pass("\u98DE\u4E66 Gateway", status.message);
|
|
1297
|
+
}
|
|
1298
|
+
return warn("\u98DE\u4E66 Gateway", status.message);
|
|
1299
|
+
}
|
|
1300
|
+
function checkLlmConfig(config, secrets) {
|
|
1301
|
+
if (!config.llm.baseUrl || !config.llm.model || !secrets.llm.apiKey) {
|
|
1302
|
+
return warn("LLM \u914D\u7F6E", "\u672A\u914D\u7F6E\u5B8C\u6574\uFF1B@ \u63D0\u95EE\u65F6\u65E0\u6CD5\u751F\u6210\u6A21\u578B\u56DE\u7B54\u3002");
|
|
1303
|
+
}
|
|
1304
|
+
return pass("LLM \u914D\u7F6E", `${config.llm.model} @ ${config.llm.baseUrl}`);
|
|
1305
|
+
}
|
|
1306
|
+
function checkEmbeddingConfig(config, secrets) {
|
|
1307
|
+
if (!hasEmbeddingConfig(config, secrets)) {
|
|
1308
|
+
return warn("Embedding \u914D\u7F6E", "\u672A\u914D\u7F6E\u5B8C\u6574\uFF1BRAG \u4F1A\u4F7F\u7528 SQLite FTS\uFF0C\u65E0\u6CD5\u4F7F\u7528 SQLite Vector \u8BED\u4E49\u68C0\u7D22\u3002");
|
|
1309
|
+
}
|
|
1310
|
+
return pass("Embedding \u914D\u7F6E", `${config.embedding.model} @ ${config.embedding.baseUrl || config.llm.baseUrl}`);
|
|
1311
|
+
}
|
|
1312
|
+
async function checkSqlite(config) {
|
|
1313
|
+
let database = null;
|
|
1314
|
+
try {
|
|
1315
|
+
database = openDatabase(config);
|
|
1316
|
+
const messages = new MessageRepository(database);
|
|
1317
|
+
return pass("SQLite", `${getDatabasePath(config)}\uFF1Bmessages=${messages.getMessageCount()}`);
|
|
1318
|
+
} catch (error) {
|
|
1319
|
+
return fail("SQLite", error instanceof Error ? error.message : String(error));
|
|
1320
|
+
} finally {
|
|
1321
|
+
database?.close();
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async function checkFilePipeline(config) {
|
|
1325
|
+
let database = null;
|
|
1326
|
+
try {
|
|
1327
|
+
database = openDatabase(config);
|
|
1328
|
+
const messages = new MessageRepository(database);
|
|
1329
|
+
const jobs = new FileJobRepository(database);
|
|
1330
|
+
const fileCount = messages.listFiles(1e6).length;
|
|
1331
|
+
const failedJobs = jobs.list(1e6, { status: "failed" });
|
|
1332
|
+
if (failedJobs.length > 0) {
|
|
1333
|
+
return warn("\u6587\u4EF6\u89E3\u6790", `files=${fileCount}\uFF1Bfailed_jobs=${failedJobs.length}\uFF1B\u53EF\u8FD0\u884C chattercatcher files jobs --status failed \u67E5\u770B\u3002`);
|
|
1334
|
+
}
|
|
1335
|
+
return pass("\u6587\u4EF6\u89E3\u6790", `files=${fileCount}\uFF1Bfailed_jobs=0`);
|
|
1336
|
+
} catch (error) {
|
|
1337
|
+
return fail("\u6587\u4EF6\u89E3\u6790", error instanceof Error ? error.message : String(error));
|
|
1338
|
+
} finally {
|
|
1339
|
+
database?.close();
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
async function checkSqliteVector(config) {
|
|
1343
|
+
let database = null;
|
|
1344
|
+
try {
|
|
1345
|
+
database = openDatabase(config);
|
|
1346
|
+
const store = new SQLiteVectorStore(database);
|
|
1347
|
+
const count = await store.count();
|
|
1348
|
+
return pass("SQLite Vector", `${getDatabasePath(config)}\uFF1Bvectors=${count}`);
|
|
1349
|
+
} catch (error) {
|
|
1350
|
+
return fail("SQLite Vector", error instanceof Error ? error.message : String(error));
|
|
1351
|
+
} finally {
|
|
1352
|
+
database?.close();
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
function checkRagPolicy() {
|
|
1356
|
+
return pass("RAG \u7B56\u7565", "\u5F3A\u5236\u5148\u68C0\u7D22\u8BC1\u636E\u518D\u56DE\u7B54\uFF1B\u7981\u6B62\u5168\u91CF\u4E0A\u4E0B\u6587\u5806\u53E0\u3002");
|
|
1357
|
+
}
|
|
1358
|
+
async function checkChatModel(config, secrets) {
|
|
1359
|
+
if (!config.llm.baseUrl || !config.llm.model || !secrets.llm.apiKey) {
|
|
1360
|
+
return warn("LLM \u8FDE\u901A\u6027", "\u8DF3\u8FC7\uFF1ALLM \u914D\u7F6E\u4E0D\u5B8C\u6574\u3002");
|
|
1361
|
+
}
|
|
1362
|
+
try {
|
|
1363
|
+
const answer = await createChatModel(config, secrets).complete([{ role: "user", content: "Reply with OK only." }]);
|
|
1364
|
+
return pass("LLM \u8FDE\u901A\u6027", answer.slice(0, 80));
|
|
1365
|
+
} catch (error) {
|
|
1366
|
+
return fail("LLM \u8FDE\u901A\u6027", error instanceof Error ? error.message : String(error));
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
async function checkEmbeddingModel(config, secrets) {
|
|
1370
|
+
if (!hasEmbeddingConfig(config, secrets)) {
|
|
1371
|
+
return warn("Embedding \u8FDE\u901A\u6027", "\u8DF3\u8FC7\uFF1AEmbedding \u914D\u7F6E\u4E0D\u5B8C\u6574\u3002");
|
|
1372
|
+
}
|
|
1373
|
+
try {
|
|
1374
|
+
const vector = await createEmbeddingModel(config, secrets).embed("chattercatcher doctor");
|
|
1375
|
+
if (vector.length === 0) {
|
|
1376
|
+
return fail("Embedding \u8FDE\u901A\u6027", "\u8FD4\u56DE\u5411\u91CF\u4E3A\u7A7A\u3002");
|
|
1377
|
+
}
|
|
1378
|
+
return pass("Embedding \u8FDE\u901A\u6027", `dimension=${vector.length}`);
|
|
1379
|
+
} catch (error) {
|
|
1380
|
+
return fail("Embedding \u8FDE\u901A\u6027", error instanceof Error ? error.message : String(error));
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
function formatDoctorChecks(checks) {
|
|
1384
|
+
const icon = {
|
|
1385
|
+
pass: "PASS",
|
|
1386
|
+
warn: "WARN",
|
|
1387
|
+
fail: "FAIL"
|
|
1388
|
+
};
|
|
1389
|
+
return checks.map((check) => `[${icon[check.status]}] ${check.name}: ${check.message}`).join("\n");
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
// src/export/data-export.ts
|
|
1393
|
+
import fs6 from "fs/promises";
|
|
1394
|
+
import path8 from "path";
|
|
1395
|
+
function parseJsonObject(value) {
|
|
1396
|
+
try {
|
|
1397
|
+
const parsed = JSON.parse(value);
|
|
1398
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
1399
|
+
} catch {
|
|
1400
|
+
return {};
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
function parseJsonArray(value) {
|
|
1404
|
+
try {
|
|
1405
|
+
const parsed = JSON.parse(value);
|
|
1406
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
1407
|
+
} catch {
|
|
1408
|
+
return [];
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
function defaultExportPath(config, exportedAt) {
|
|
1412
|
+
const fileName = `chattercatcher-export-${exportedAt.replace(/[:.]/g, "-")}.json`;
|
|
1413
|
+
return path8.join(resolveHomePath(config.storage.dataDir), "exports", fileName);
|
|
1414
|
+
}
|
|
1415
|
+
async function exportLocalData(input2) {
|
|
1416
|
+
const exportedAt = input2.exportedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1417
|
+
const outputPath = path8.resolve(input2.outputPath ?? defaultExportPath(input2.config, exportedAt));
|
|
1418
|
+
const chats = input2.database.prepare(
|
|
1419
|
+
`
|
|
1420
|
+
SELECT
|
|
1421
|
+
id,
|
|
1422
|
+
platform,
|
|
1423
|
+
platform_chat_id AS platformChatId,
|
|
1424
|
+
name,
|
|
1425
|
+
created_at AS createdAt,
|
|
1426
|
+
updated_at AS updatedAt
|
|
1427
|
+
FROM chats
|
|
1428
|
+
ORDER BY updated_at ASC
|
|
1429
|
+
`
|
|
1430
|
+
).all();
|
|
1431
|
+
const messages = input2.database.prepare(
|
|
1432
|
+
`
|
|
1433
|
+
SELECT
|
|
1434
|
+
id,
|
|
1435
|
+
platform,
|
|
1436
|
+
platform_message_id AS platformMessageId,
|
|
1437
|
+
chat_id AS chatId,
|
|
1438
|
+
sender_id AS senderId,
|
|
1439
|
+
sender_name AS senderName,
|
|
1440
|
+
message_type AS messageType,
|
|
1441
|
+
text,
|
|
1442
|
+
raw_payload_json AS rawPayloadJson,
|
|
1443
|
+
sent_at AS sentAt,
|
|
1444
|
+
received_at AS receivedAt,
|
|
1445
|
+
created_at AS createdAt
|
|
1446
|
+
FROM messages
|
|
1447
|
+
ORDER BY sent_at ASC, created_at ASC
|
|
1448
|
+
`
|
|
1449
|
+
).all().map(({ rawPayloadJson, ...message }) => ({
|
|
1450
|
+
...message,
|
|
1451
|
+
rawPayload: parseJsonObject(rawPayloadJson)
|
|
1452
|
+
}));
|
|
1453
|
+
const chunks = input2.database.prepare(
|
|
1454
|
+
`
|
|
1455
|
+
SELECT
|
|
1456
|
+
id,
|
|
1457
|
+
message_id AS messageId,
|
|
1458
|
+
chunk_index AS chunkIndex,
|
|
1459
|
+
text,
|
|
1460
|
+
metadata_json AS metadataJson,
|
|
1461
|
+
created_at AS createdAt
|
|
1462
|
+
FROM message_chunks
|
|
1463
|
+
ORDER BY message_id ASC, chunk_index ASC
|
|
1464
|
+
`
|
|
1465
|
+
).all().map(({ metadataJson, ...chunk }) => ({
|
|
1466
|
+
...chunk,
|
|
1467
|
+
metadata: parseJsonObject(metadataJson)
|
|
1468
|
+
}));
|
|
1469
|
+
const fileJobs = input2.database.prepare(
|
|
1470
|
+
`
|
|
1471
|
+
SELECT
|
|
1472
|
+
id,
|
|
1473
|
+
source_path AS sourcePath,
|
|
1474
|
+
stored_path AS storedPath,
|
|
1475
|
+
file_name AS fileName,
|
|
1476
|
+
status,
|
|
1477
|
+
parser,
|
|
1478
|
+
message_id AS messageId,
|
|
1479
|
+
bytes,
|
|
1480
|
+
characters,
|
|
1481
|
+
warnings_json AS warningsJson,
|
|
1482
|
+
error,
|
|
1483
|
+
created_at AS createdAt,
|
|
1484
|
+
updated_at AS updatedAt
|
|
1485
|
+
FROM file_jobs
|
|
1486
|
+
ORDER BY updated_at ASC
|
|
1487
|
+
`
|
|
1488
|
+
).all().map(({ warningsJson, ...job }) => ({
|
|
1489
|
+
...job,
|
|
1490
|
+
warnings: parseJsonArray(warningsJson).filter((item) => typeof item === "string")
|
|
1491
|
+
}));
|
|
1492
|
+
const payload = {
|
|
1493
|
+
app: "ChatterCatcher",
|
|
1494
|
+
schemaVersion: 1,
|
|
1495
|
+
exportedAt,
|
|
1496
|
+
note: "\u672C\u6587\u4EF6\u53EA\u5305\u542B\u672C\u5730\u77E5\u8BC6\u5E93\u6570\u636E\uFF0C\u4E0D\u5305\u542B API Key\u3001App Secret \u6216 token\u3002",
|
|
1497
|
+
data: {
|
|
1498
|
+
chats,
|
|
1499
|
+
messages,
|
|
1500
|
+
chunks,
|
|
1501
|
+
fileJobs
|
|
1502
|
+
}
|
|
1503
|
+
};
|
|
1504
|
+
await fs6.mkdir(path8.dirname(outputPath), { recursive: true });
|
|
1505
|
+
await fs6.writeFile(outputPath, `${JSON.stringify(payload, null, 2)}
|
|
1506
|
+
`, "utf8");
|
|
1507
|
+
return {
|
|
1508
|
+
outputPath,
|
|
1509
|
+
chats: chats.length,
|
|
1510
|
+
messages: messages.length,
|
|
1511
|
+
chunks: chunks.length,
|
|
1512
|
+
fileJobs: fileJobs.length
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
// src/export/data-restore.ts
|
|
1517
|
+
import fs7 from "fs/promises";
|
|
1518
|
+
import path9 from "path";
|
|
1519
|
+
function asObject(value) {
|
|
1520
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1521
|
+
}
|
|
1522
|
+
function asArray(value) {
|
|
1523
|
+
return Array.isArray(value) ? value.map(asObject) : [];
|
|
1524
|
+
}
|
|
1525
|
+
function asString(value, field) {
|
|
1526
|
+
if (typeof value !== "string") {
|
|
1527
|
+
throw new Error(`\u6062\u590D\u6587\u4EF6\u5B57\u6BB5\u65E0\u6548\uFF1A${field}`);
|
|
1528
|
+
}
|
|
1529
|
+
return value;
|
|
1530
|
+
}
|
|
1531
|
+
function asOptionalString(value) {
|
|
1532
|
+
return typeof value === "string" ? value : null;
|
|
1533
|
+
}
|
|
1534
|
+
function asOptionalNumber(value) {
|
|
1535
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
1536
|
+
}
|
|
1537
|
+
function asJson(value, fallback) {
|
|
1538
|
+
return JSON.stringify(value === void 0 ? fallback : value);
|
|
1539
|
+
}
|
|
1540
|
+
function parsePayload(raw) {
|
|
1541
|
+
const parsed = asObject(JSON.parse(raw));
|
|
1542
|
+
const data2 = asObject(parsed.data);
|
|
1543
|
+
const payload = {
|
|
1544
|
+
app: asString(parsed.app, "app"),
|
|
1545
|
+
schemaVersion: typeof parsed.schemaVersion === "number" ? parsed.schemaVersion : NaN,
|
|
1546
|
+
data: {
|
|
1547
|
+
chats: asArray(data2.chats),
|
|
1548
|
+
messages: asArray(data2.messages),
|
|
1549
|
+
chunks: asArray(data2.chunks),
|
|
1550
|
+
fileJobs: asArray(data2.fileJobs)
|
|
1551
|
+
}
|
|
1552
|
+
};
|
|
1553
|
+
if (payload.app !== "ChatterCatcher" || payload.schemaVersion !== 1) {
|
|
1554
|
+
throw new Error("\u6062\u590D\u6587\u4EF6\u4E0D\u662F ChatterCatcher schemaVersion=1 \u5BFC\u51FA\u3002");
|
|
1555
|
+
}
|
|
1556
|
+
return payload;
|
|
1557
|
+
}
|
|
1558
|
+
function clearDatabase(database) {
|
|
1559
|
+
database.prepare("DELETE FROM message_chunks_fts").run();
|
|
1560
|
+
database.prepare("DELETE FROM message_chunks").run();
|
|
1561
|
+
database.prepare("DELETE FROM file_jobs").run();
|
|
1562
|
+
database.prepare("DELETE FROM messages").run();
|
|
1563
|
+
database.prepare("DELETE FROM chats").run();
|
|
1564
|
+
}
|
|
1565
|
+
async function restoreLocalData(input2) {
|
|
1566
|
+
const inputPath = path9.resolve(input2.inputPath);
|
|
1567
|
+
const payload = parsePayload(await fs7.readFile(inputPath, "utf8"));
|
|
1568
|
+
const mode = input2.replace ? "replace" : "merge";
|
|
1569
|
+
const restore = input2.database.transaction(() => {
|
|
1570
|
+
if (input2.replace) {
|
|
1571
|
+
clearDatabase(input2.database);
|
|
1572
|
+
}
|
|
1573
|
+
const upsertChat = input2.database.prepare(`
|
|
1574
|
+
INSERT INTO chats (id, platform, platform_chat_id, name, created_at, updated_at)
|
|
1575
|
+
VALUES (@id, @platform, @platformChatId, @name, @createdAt, @updatedAt)
|
|
1576
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1577
|
+
platform = excluded.platform,
|
|
1578
|
+
platform_chat_id = excluded.platform_chat_id,
|
|
1579
|
+
name = excluded.name,
|
|
1580
|
+
updated_at = excluded.updated_at
|
|
1581
|
+
`);
|
|
1582
|
+
const upsertMessage = input2.database.prepare(`
|
|
1583
|
+
INSERT INTO messages (
|
|
1584
|
+
id, platform, platform_message_id, chat_id, sender_id, sender_name,
|
|
1585
|
+
message_type, text, raw_payload_json, sent_at, received_at, created_at
|
|
1586
|
+
)
|
|
1587
|
+
VALUES (
|
|
1588
|
+
@id, @platform, @platformMessageId, @chatId, @senderId, @senderName,
|
|
1589
|
+
@messageType, @text, @rawPayloadJson, @sentAt, @receivedAt, @createdAt
|
|
1590
|
+
)
|
|
1591
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1592
|
+
platform = excluded.platform,
|
|
1593
|
+
platform_message_id = excluded.platform_message_id,
|
|
1594
|
+
chat_id = excluded.chat_id,
|
|
1595
|
+
sender_id = excluded.sender_id,
|
|
1596
|
+
sender_name = excluded.sender_name,
|
|
1597
|
+
message_type = excluded.message_type,
|
|
1598
|
+
text = excluded.text,
|
|
1599
|
+
raw_payload_json = excluded.raw_payload_json,
|
|
1600
|
+
sent_at = excluded.sent_at,
|
|
1601
|
+
received_at = excluded.received_at
|
|
1602
|
+
`);
|
|
1603
|
+
const upsertChunk = input2.database.prepare(`
|
|
1604
|
+
INSERT INTO message_chunks (id, message_id, chunk_index, text, metadata_json, created_at)
|
|
1605
|
+
VALUES (@id, @messageId, @chunkIndex, @text, @metadataJson, @createdAt)
|
|
1606
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1607
|
+
message_id = excluded.message_id,
|
|
1608
|
+
chunk_index = excluded.chunk_index,
|
|
1609
|
+
text = excluded.text,
|
|
1610
|
+
metadata_json = excluded.metadata_json
|
|
1611
|
+
`);
|
|
1612
|
+
const insertFts = input2.database.prepare(`
|
|
1613
|
+
INSERT INTO message_chunks_fts (text, chunk_id, message_id)
|
|
1614
|
+
VALUES (@text, @chunkId, @messageId)
|
|
1615
|
+
`);
|
|
1616
|
+
const upsertFileJob = input2.database.prepare(`
|
|
1617
|
+
INSERT INTO file_jobs (
|
|
1618
|
+
id, source_path, stored_path, file_name, status, parser, message_id,
|
|
1619
|
+
bytes, characters, warnings_json, error, created_at, updated_at
|
|
1620
|
+
)
|
|
1621
|
+
VALUES (
|
|
1622
|
+
@id, @sourcePath, @storedPath, @fileName, @status, @parser, @messageId,
|
|
1623
|
+
@bytes, @characters, @warningsJson, @error, @createdAt, @updatedAt
|
|
1624
|
+
)
|
|
1625
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1626
|
+
source_path = excluded.source_path,
|
|
1627
|
+
stored_path = excluded.stored_path,
|
|
1628
|
+
file_name = excluded.file_name,
|
|
1629
|
+
status = excluded.status,
|
|
1630
|
+
parser = excluded.parser,
|
|
1631
|
+
message_id = excluded.message_id,
|
|
1632
|
+
bytes = excluded.bytes,
|
|
1633
|
+
characters = excluded.characters,
|
|
1634
|
+
warnings_json = excluded.warnings_json,
|
|
1635
|
+
error = excluded.error,
|
|
1636
|
+
updated_at = excluded.updated_at
|
|
1637
|
+
`);
|
|
1638
|
+
for (const chat of payload.data.chats) {
|
|
1639
|
+
upsertChat.run({
|
|
1640
|
+
id: asString(chat.id, "chat.id"),
|
|
1641
|
+
platform: asString(chat.platform, "chat.platform"),
|
|
1642
|
+
platformChatId: asString(chat.platformChatId, "chat.platformChatId"),
|
|
1643
|
+
name: asString(chat.name, "chat.name"),
|
|
1644
|
+
createdAt: asString(chat.createdAt, "chat.createdAt"),
|
|
1645
|
+
updatedAt: asString(chat.updatedAt, "chat.updatedAt")
|
|
1646
|
+
});
|
|
1647
|
+
}
|
|
1648
|
+
for (const message of payload.data.messages) {
|
|
1649
|
+
upsertMessage.run({
|
|
1650
|
+
id: asString(message.id, "message.id"),
|
|
1651
|
+
platform: asString(message.platform, "message.platform"),
|
|
1652
|
+
platformMessageId: asString(message.platformMessageId, "message.platformMessageId"),
|
|
1653
|
+
chatId: asString(message.chatId, "message.chatId"),
|
|
1654
|
+
senderId: asString(message.senderId, "message.senderId"),
|
|
1655
|
+
senderName: asString(message.senderName, "message.senderName"),
|
|
1656
|
+
messageType: asString(message.messageType, "message.messageType"),
|
|
1657
|
+
text: asString(message.text, "message.text"),
|
|
1658
|
+
rawPayloadJson: asJson(message.rawPayload, {}),
|
|
1659
|
+
sentAt: asString(message.sentAt, "message.sentAt"),
|
|
1660
|
+
receivedAt: asString(message.receivedAt, "message.receivedAt"),
|
|
1661
|
+
createdAt: asString(message.createdAt, "message.createdAt")
|
|
1662
|
+
});
|
|
1663
|
+
input2.database.prepare("DELETE FROM message_chunks_fts WHERE message_id = ?").run(asString(message.id, "message.id"));
|
|
1664
|
+
}
|
|
1665
|
+
for (const chunk of payload.data.chunks) {
|
|
1666
|
+
const messageId = asString(chunk.messageId, "chunk.messageId");
|
|
1667
|
+
const chunkId = asString(chunk.id, "chunk.id");
|
|
1668
|
+
const text = asString(chunk.text, "chunk.text");
|
|
1669
|
+
upsertChunk.run({
|
|
1670
|
+
id: chunkId,
|
|
1671
|
+
messageId,
|
|
1672
|
+
chunkIndex: asOptionalNumber(chunk.chunkIndex) ?? 0,
|
|
1673
|
+
text,
|
|
1674
|
+
metadataJson: asJson(chunk.metadata, {}),
|
|
1675
|
+
createdAt: asString(chunk.createdAt, "chunk.createdAt")
|
|
1676
|
+
});
|
|
1677
|
+
insertFts.run({ text, chunkId, messageId });
|
|
1678
|
+
}
|
|
1679
|
+
for (const job of payload.data.fileJobs) {
|
|
1680
|
+
upsertFileJob.run({
|
|
1681
|
+
id: asString(job.id, "fileJob.id"),
|
|
1682
|
+
sourcePath: asString(job.sourcePath, "fileJob.sourcePath"),
|
|
1683
|
+
storedPath: asOptionalString(job.storedPath),
|
|
1684
|
+
fileName: asString(job.fileName, "fileJob.fileName"),
|
|
1685
|
+
status: asString(job.status, "fileJob.status"),
|
|
1686
|
+
parser: asOptionalString(job.parser),
|
|
1687
|
+
messageId: asOptionalString(job.messageId),
|
|
1688
|
+
bytes: asOptionalNumber(job.bytes),
|
|
1689
|
+
characters: asOptionalNumber(job.characters),
|
|
1690
|
+
warningsJson: asJson(Array.isArray(job.warnings) ? job.warnings : [], []),
|
|
1691
|
+
error: asOptionalString(job.error),
|
|
1692
|
+
createdAt: asString(job.createdAt, "fileJob.createdAt"),
|
|
1693
|
+
updatedAt: asString(job.updatedAt, "fileJob.updatedAt")
|
|
1694
|
+
});
|
|
1695
|
+
}
|
|
1696
|
+
});
|
|
1697
|
+
restore();
|
|
1698
|
+
return {
|
|
1699
|
+
inputPath,
|
|
1700
|
+
mode,
|
|
1701
|
+
chats: payload.data.chats.length,
|
|
1702
|
+
messages: payload.data.messages.length,
|
|
1703
|
+
chunks: payload.data.chunks.length,
|
|
1704
|
+
fileJobs: payload.data.fileJobs.length
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
// src/feishu/gateway.ts
|
|
1709
|
+
import * as lark2 from "@larksuiteoapi/node-sdk";
|
|
1710
|
+
|
|
1711
|
+
// src/rag/citations.ts
|
|
1712
|
+
function isOpaqueId(value) {
|
|
1713
|
+
return Boolean(value && /^(ou|oc|om|cli|on|un|uid)_?[a-z0-9]+/i.test(value));
|
|
1714
|
+
}
|
|
1715
|
+
function formatTime(value) {
|
|
1716
|
+
if (!value) {
|
|
1717
|
+
return "\u672A\u77E5\u65F6\u95F4";
|
|
1718
|
+
}
|
|
1719
|
+
const date = new Date(value);
|
|
1720
|
+
if (Number.isNaN(date.getTime())) {
|
|
1721
|
+
return value;
|
|
1722
|
+
}
|
|
1723
|
+
const pad = (input2) => String(input2).padStart(2, "0");
|
|
1724
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
1725
|
+
}
|
|
1726
|
+
function formatSpeaker(source) {
|
|
1727
|
+
if (source.type === "file") {
|
|
1728
|
+
return isOpaqueId(source.label) ? "\u6587\u4EF6" : `\u6587\u4EF6 ${source.label}`;
|
|
1729
|
+
}
|
|
1730
|
+
if (source.sender && !isOpaqueId(source.sender)) {
|
|
1731
|
+
return source.sender;
|
|
1732
|
+
}
|
|
1733
|
+
return "\u7FA4\u6210\u5458";
|
|
1734
|
+
}
|
|
1735
|
+
function clipText(value, maxLength) {
|
|
1736
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
1737
|
+
return normalized.length > maxLength ? `${normalized.slice(0, maxLength)}...` : normalized;
|
|
1738
|
+
}
|
|
1739
|
+
function formatCitation(citation, options = {}) {
|
|
1740
|
+
const maxTextLength = options.maxTextLength ?? 120;
|
|
1741
|
+
const speaker = formatSpeaker(citation.source);
|
|
1742
|
+
const time = formatTime(citation.source.timestamp);
|
|
1743
|
+
const verb = citation.source.type === "file" ? "\u8BB0\u5F55" : "\u8BF4";
|
|
1744
|
+
return `[${citation.marker}] ${speaker}\u5728 ${time} ${verb}\uFF1A\u201C${clipText(citation.text, maxTextLength)}\u201D`;
|
|
1745
|
+
}
|
|
1746
|
+
function formatCitations(citations, options = {}) {
|
|
1747
|
+
return citations.map((citation) => formatCitation(citation, options)).join("\n");
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
// src/rag/answer.ts
|
|
1751
|
+
var DEFAULT_MAX_EVIDENCE_BLOCKS = 8;
|
|
1752
|
+
var DEFAULT_MAX_CHARS_PER_BLOCK = 1200;
|
|
1753
|
+
var SCORE_TIE_THRESHOLD = 0.15;
|
|
1754
|
+
function parseTimestamp(value) {
|
|
1755
|
+
if (!value) {
|
|
1756
|
+
return 0;
|
|
1757
|
+
}
|
|
1758
|
+
const time = Date.parse(value);
|
|
1759
|
+
return Number.isFinite(time) ? time : 0;
|
|
1760
|
+
}
|
|
1761
|
+
function rankEvidenceForPrompt(evidence) {
|
|
1762
|
+
return [...evidence].sort((left, right) => {
|
|
1763
|
+
const scoreDiff = right.score - left.score;
|
|
1764
|
+
if (Math.abs(scoreDiff) > SCORE_TIE_THRESHOLD) {
|
|
1765
|
+
return scoreDiff;
|
|
1766
|
+
}
|
|
1767
|
+
const timeDiff = parseTimestamp(right.source.timestamp) - parseTimestamp(left.source.timestamp);
|
|
1768
|
+
if (timeDiff !== 0) {
|
|
1769
|
+
return timeDiff;
|
|
1770
|
+
}
|
|
1771
|
+
return scoreDiff;
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
function buildEvidencePrompt(question, evidence, options = {}) {
|
|
1775
|
+
if (evidence.length === 0) {
|
|
1776
|
+
throw new Error("RAG evidence is required before answer generation.");
|
|
1777
|
+
}
|
|
1778
|
+
const maxEvidenceBlocks = options.maxEvidenceBlocks ?? DEFAULT_MAX_EVIDENCE_BLOCKS;
|
|
1779
|
+
const maxCharsPerBlock = options.maxCharsPerBlock ?? DEFAULT_MAX_CHARS_PER_BLOCK;
|
|
1780
|
+
const selected = rankEvidenceForPrompt(evidence).slice(0, maxEvidenceBlocks);
|
|
1781
|
+
const citations = selected.map((item, index2) => ({
|
|
1782
|
+
marker: `S${index2 + 1}`,
|
|
1783
|
+
evidenceId: item.id,
|
|
1784
|
+
source: item.source,
|
|
1785
|
+
text: item.text
|
|
1786
|
+
}));
|
|
1787
|
+
const evidenceText = selected.map((item, index2) => {
|
|
1788
|
+
const marker = citations[index2]?.marker;
|
|
1789
|
+
const clippedText = item.text.length > maxCharsPerBlock ? `${item.text.slice(0, maxCharsPerBlock)}...` : item.text;
|
|
1790
|
+
const sourceParts = [
|
|
1791
|
+
item.source.label,
|
|
1792
|
+
item.source.sender ? `\u53D1\u9001\u4EBA\uFF1A${item.source.sender}` : void 0,
|
|
1793
|
+
item.source.timestamp ? `\u65F6\u95F4\uFF1A${item.source.timestamp}` : void 0,
|
|
1794
|
+
item.source.location ? `\u4F4D\u7F6E\uFF1A${item.source.location}` : void 0
|
|
1795
|
+
].filter(Boolean);
|
|
1796
|
+
return `[${marker}]
|
|
1797
|
+
\u6765\u6E90\uFF1A${sourceParts.join("\uFF1B")}
|
|
1798
|
+
\u5185\u5BB9\uFF1A${clippedText}`;
|
|
1799
|
+
}).join("\n\n");
|
|
1800
|
+
return {
|
|
1801
|
+
citations,
|
|
1802
|
+
messages: [
|
|
1803
|
+
{
|
|
1804
|
+
role: "system",
|
|
1805
|
+
content: "\u4F60\u662F ChatterCatcher \u7684\u95EE\u7B54\u6A21\u5757\u3002\u53EA\u80FD\u6839\u636E\u63D0\u4F9B\u7684\u68C0\u7D22\u8BC1\u636E\u56DE\u7B54\uFF0C\u5FC5\u987B\u7B80\u77ED\u76F4\u63A5\u3002\u4E8B\u5B9E\u6027\u7ED3\u8BBA\u5FC5\u987B\u5F15\u7528 [S1] \u8FD9\u6837\u7684\u6765\u6E90\u6807\u8BB0\u3002\u8BC1\u636E\u4E0D\u8DB3\u65F6\u8BF4\u4E0D\u77E5\u9053\uFF0C\u4E0D\u8981\u731C\u3002\u82E5\u8BC1\u636E\u4E92\u76F8\u77DB\u76FE\uFF0C\u4F18\u5148\u91C7\u7528\u65F6\u95F4\u66F4\u65B0\u4E14\u8868\u8FF0\u660E\u786E\u7684\u8BC1\u636E\uFF1B\u5982\u679C\u8F83\u65B0\u7684\u8BC1\u636E\u53EA\u662F\u8BA8\u8BBA\u3001\u731C\u6D4B\u6216\u4E0D\u786E\u5B9A\u8868\u8FBE\uFF0C\u4E0D\u8981\u628A\u5B83\u5F53\u4F5C\u786E\u5B9A\u66F4\u65B0\u3002"
|
|
1806
|
+
},
|
|
1807
|
+
{
|
|
1808
|
+
role: "user",
|
|
1809
|
+
content: `\u95EE\u9898\uFF1A${question}
|
|
1810
|
+
|
|
1811
|
+
\u8BC1\u636E\u5904\u7406\u89C4\u5219\uFF1A
|
|
1812
|
+
1. \u5148\u5224\u65AD\u8BC1\u636E\u662F\u5426\u8DB3\u4EE5\u56DE\u7B54\u95EE\u9898\u3002
|
|
1813
|
+
2. \u540C\u4E00\u4E8B\u9879\u51FA\u73B0\u591A\u4E2A\u7248\u672C\u65F6\uFF0C\u9ED8\u8BA4\u8F83\u65B0\u7684\u660E\u786E\u6D88\u606F\u4F18\u5148\u3002
|
|
1814
|
+
3. \u56DE\u7B54\u53EA\u5F15\u7528\u5B9E\u9645\u652F\u6491\u7ED3\u8BBA\u7684\u8BC1\u636E\u3002
|
|
1815
|
+
|
|
1816
|
+
\u68C0\u7D22\u8BC1\u636E\uFF1A
|
|
1817
|
+
${evidenceText}`
|
|
1818
|
+
}
|
|
1819
|
+
]
|
|
1820
|
+
};
|
|
1821
|
+
}
|
|
1822
|
+
async function generateGroundedAnswer(input2) {
|
|
1823
|
+
const prompt = buildEvidencePrompt(input2.question, input2.evidence);
|
|
1824
|
+
const answer = await input2.model.complete(prompt.messages);
|
|
1825
|
+
return {
|
|
1826
|
+
answer,
|
|
1827
|
+
citations: prompt.citations
|
|
1828
|
+
};
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
// src/rag/qa-service.ts
|
|
1832
|
+
async function askWithRag(input2) {
|
|
1833
|
+
const evidence = await input2.retriever.retrieve(input2.question);
|
|
1834
|
+
if (evidence.length === 0) {
|
|
1835
|
+
return {
|
|
1836
|
+
answer: "\u4E0D\u77E5\u9053\u3002\u5F53\u524D\u672C\u5730\u77E5\u8BC6\u5E93\u6CA1\u6709\u68C0\u7D22\u5230\u8DB3\u591F\u8BC1\u636E\u3002",
|
|
1837
|
+
citations: []
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
return generateGroundedAnswer({
|
|
1841
|
+
question: input2.question,
|
|
1842
|
+
evidence,
|
|
1843
|
+
model: input2.model
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
// src/feishu/question.ts
|
|
1848
|
+
function parseTextContent(content) {
|
|
1849
|
+
if (!content) {
|
|
1850
|
+
return "";
|
|
1851
|
+
}
|
|
1852
|
+
try {
|
|
1853
|
+
const parsed = JSON.parse(content);
|
|
1854
|
+
return typeof parsed.text === "string" ? parsed.text : "";
|
|
1855
|
+
} catch {
|
|
1856
|
+
return content;
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
function stripMentions(text, mentions) {
|
|
1860
|
+
let result = text;
|
|
1861
|
+
for (const mention of mentions ?? []) {
|
|
1862
|
+
for (const token of [mention.key, mention.name, mention.name ? `@${mention.name}` : void 0]) {
|
|
1863
|
+
if (token) {
|
|
1864
|
+
result = result.replaceAll(token, " ");
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
return result.replace(/@\s*ChatterCatcher/gi, " ").replace(/@/g, " ").replace(/\s+/g, " ").trim();
|
|
1869
|
+
}
|
|
1870
|
+
function isFeishuMessageAddressedToBot(payload) {
|
|
1871
|
+
const message = payload.event?.message;
|
|
1872
|
+
if (!message || message.message_type !== "text") {
|
|
1873
|
+
return false;
|
|
1874
|
+
}
|
|
1875
|
+
const mentions = message.mentions ?? [];
|
|
1876
|
+
const text = parseTextContent(message.content);
|
|
1877
|
+
return mentions.length > 0 || /@?ChatterCatcher/i.test(text);
|
|
1878
|
+
}
|
|
1879
|
+
function getFeishuQuestionDecision(payload, config) {
|
|
1880
|
+
const message = payload.event?.message;
|
|
1881
|
+
if (!message?.chat_id || message.message_type !== "text") {
|
|
1882
|
+
return {
|
|
1883
|
+
shouldAnswer: false,
|
|
1884
|
+
reason: "\u4E0D\u662F\u53EF\u56DE\u7B54\u7684\u6587\u672C\u6D88\u606F\u3002"
|
|
1885
|
+
};
|
|
1886
|
+
}
|
|
1887
|
+
const mentions = message.mentions ?? [];
|
|
1888
|
+
const text = parseTextContent(message.content);
|
|
1889
|
+
const hasMention = isFeishuMessageAddressedToBot(payload);
|
|
1890
|
+
if (config.feishu.requireMention && !hasMention) {
|
|
1891
|
+
return {
|
|
1892
|
+
shouldAnswer: false,
|
|
1893
|
+
reason: "\u7FA4\u804A\u914D\u7F6E\u4E3A\u5FC5\u987B @ \u540E\u56DE\u7B54\u3002"
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
const question = stripMentions(text, mentions);
|
|
1897
|
+
if (!question) {
|
|
1898
|
+
return {
|
|
1899
|
+
shouldAnswer: false,
|
|
1900
|
+
reason: "\u6CA1\u6709\u53EF\u56DE\u7B54\u7684\u95EE\u9898\u6587\u672C\u3002"
|
|
1901
|
+
};
|
|
1902
|
+
}
|
|
1903
|
+
return {
|
|
1904
|
+
shouldAnswer: true,
|
|
1905
|
+
question,
|
|
1906
|
+
chatId: message.chat_id
|
|
1907
|
+
};
|
|
1908
|
+
}
|
|
1909
|
+
var FeishuQuestionHandler = class {
|
|
1910
|
+
constructor(options) {
|
|
1911
|
+
this.options = options;
|
|
1912
|
+
}
|
|
1913
|
+
options;
|
|
1914
|
+
async sendResponse(chatId, messageId, text) {
|
|
1915
|
+
if (messageId && this.options.sender.replyTextToMessage) {
|
|
1916
|
+
try {
|
|
1917
|
+
await this.options.sender.replyTextToMessage(messageId, text);
|
|
1918
|
+
return;
|
|
1919
|
+
} catch (error) {
|
|
1920
|
+
console.log(`\u98DE\u4E66\u56DE\u590D\u539F\u6D88\u606F\u5931\u8D25\uFF0C\u9000\u56DE\u7FA4\u6D88\u606F\uFF1A${error instanceof Error ? error.message : String(error)}`);
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
await this.options.sender.sendTextToChat(chatId, text);
|
|
1924
|
+
}
|
|
1925
|
+
async acknowledgeQuestion(chatId, messageId) {
|
|
1926
|
+
if (!messageId) {
|
|
1927
|
+
return;
|
|
1928
|
+
}
|
|
1929
|
+
if (this.options.sender.addReactionToMessage) {
|
|
1930
|
+
try {
|
|
1931
|
+
await this.options.sender.addReactionToMessage(messageId, this.options.thinkingEmojiType ?? "keyboard");
|
|
1932
|
+
return;
|
|
1933
|
+
} catch (error) {
|
|
1934
|
+
console.log(`\u98DE\u4E66\u63D0\u95EE\u8868\u60C5\u53CD\u9988\u5931\u8D25\uFF0C\u6539\u7528\u6587\u5B57\u53CD\u9988\uFF1A${error instanceof Error ? error.message : String(error)}`);
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
await this.sendResponse(chatId, messageId, "\u6536\u5230\uFF0C\u6B63\u5728\u67E5\u3002");
|
|
1938
|
+
}
|
|
1939
|
+
async handle(payload, options = {}) {
|
|
1940
|
+
const decision = getFeishuQuestionDecision(payload, this.options.config);
|
|
1941
|
+
if (!decision.shouldAnswer || !decision.question || !decision.chatId) {
|
|
1942
|
+
return decision;
|
|
1943
|
+
}
|
|
1944
|
+
const questionMessageId = payload.event?.message?.message_id;
|
|
1945
|
+
await this.acknowledgeQuestion(decision.chatId, questionMessageId);
|
|
1946
|
+
const { retriever, close } = await createHybridRetriever({
|
|
1947
|
+
config: this.options.config,
|
|
1948
|
+
secrets: this.options.secrets,
|
|
1949
|
+
messages: new MessageRepository(this.options.database),
|
|
1950
|
+
excludeMessageIds: options.excludeMessageIds
|
|
1951
|
+
});
|
|
1952
|
+
try {
|
|
1953
|
+
try {
|
|
1954
|
+
const result = await askWithRag({
|
|
1955
|
+
question: decision.question,
|
|
1956
|
+
retriever,
|
|
1957
|
+
model: this.options.model
|
|
1958
|
+
});
|
|
1959
|
+
const citations = formatCitations(result.citations);
|
|
1960
|
+
const text = citations ? `${result.answer}
|
|
1961
|
+
|
|
1962
|
+
\u5F15\u7528\uFF1A
|
|
1963
|
+
${citations}` : result.answer;
|
|
1964
|
+
await this.sendResponse(decision.chatId, questionMessageId, text);
|
|
1965
|
+
} catch (error) {
|
|
1966
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1967
|
+
await this.sendResponse(decision.chatId, questionMessageId, `\u6682\u65F6\u65E0\u6CD5\u56DE\u7B54\uFF1A${message}`);
|
|
1968
|
+
}
|
|
1969
|
+
return decision;
|
|
1970
|
+
} finally {
|
|
1971
|
+
close();
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
};
|
|
1975
|
+
|
|
1976
|
+
// src/feishu/sender.ts
|
|
1977
|
+
import * as lark from "@larksuiteoapi/node-sdk";
|
|
1978
|
+
function mapDomain(domain) {
|
|
1979
|
+
return domain === "lark" ? lark.Domain.Lark : lark.Domain.Feishu;
|
|
1980
|
+
}
|
|
1981
|
+
var FeishuMessageSender = class _FeishuMessageSender {
|
|
1982
|
+
constructor(client) {
|
|
1983
|
+
this.client = client;
|
|
1984
|
+
}
|
|
1985
|
+
client;
|
|
1986
|
+
static fromConfig(config, secrets) {
|
|
1987
|
+
const client = new lark.Client({
|
|
1988
|
+
appId: config.feishu.appId,
|
|
1989
|
+
appSecret: secrets.feishu.appSecret,
|
|
1990
|
+
domain: mapDomain(config.feishu.domain)
|
|
1991
|
+
});
|
|
1992
|
+
return new _FeishuMessageSender(client);
|
|
1993
|
+
}
|
|
1994
|
+
async sendTextToChat(chatId, text) {
|
|
1995
|
+
const payload = {
|
|
1996
|
+
data: {
|
|
1997
|
+
receive_id: chatId,
|
|
1998
|
+
msg_type: "text",
|
|
1999
|
+
content: JSON.stringify({ text })
|
|
2000
|
+
},
|
|
2001
|
+
params: {
|
|
2002
|
+
receive_id_type: "chat_id"
|
|
2003
|
+
}
|
|
2004
|
+
};
|
|
2005
|
+
if (this.client.im.v1?.message.create) {
|
|
2006
|
+
await this.client.im.v1.message.create(payload);
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
if (this.client.im.message?.create) {
|
|
2010
|
+
await this.client.im.message.create(payload);
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
{
|
|
2014
|
+
throw new Error("\u5F53\u524D\u98DE\u4E66 SDK \u4E0D\u652F\u6301\u6D88\u606F\u53D1\u9001\u63A5\u53E3\u3002");
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
async replyTextToMessage(messageId, text) {
|
|
2018
|
+
const payload = {
|
|
2019
|
+
path: {
|
|
2020
|
+
message_id: messageId
|
|
2021
|
+
},
|
|
2022
|
+
data: {
|
|
2023
|
+
msg_type: "text",
|
|
2024
|
+
content: JSON.stringify({ text })
|
|
2025
|
+
}
|
|
2026
|
+
};
|
|
2027
|
+
if (this.client.im.v1?.message.reply) {
|
|
2028
|
+
await this.client.im.v1.message.reply(payload);
|
|
2029
|
+
return;
|
|
2030
|
+
}
|
|
2031
|
+
if (this.client.im.message?.reply) {
|
|
2032
|
+
await this.client.im.message.reply(payload);
|
|
2033
|
+
return;
|
|
2034
|
+
}
|
|
2035
|
+
throw new Error("\u5F53\u524D\u98DE\u4E66 SDK \u4E0D\u652F\u6301\u6D88\u606F\u56DE\u590D\u63A5\u53E3\u3002");
|
|
2036
|
+
}
|
|
2037
|
+
async addReactionToMessage(messageId, emojiType) {
|
|
2038
|
+
if (!this.client.im.v1?.messageReaction?.create) {
|
|
2039
|
+
throw new Error("\u5F53\u524D\u98DE\u4E66 SDK \u4E0D\u652F\u6301\u6D88\u606F\u8868\u60C5\u56DE\u590D\u63A5\u53E3\u3002");
|
|
2040
|
+
}
|
|
2041
|
+
await this.client.im.v1.messageReaction.create({
|
|
2042
|
+
path: {
|
|
2043
|
+
message_id: messageId
|
|
2044
|
+
},
|
|
2045
|
+
data: {
|
|
2046
|
+
reaction_type: {
|
|
2047
|
+
emoji_type: emojiType
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
};
|
|
2053
|
+
|
|
2054
|
+
// src/feishu/gateway.ts
|
|
2055
|
+
function assertFeishuConfig(config, secrets) {
|
|
2056
|
+
if (!config.feishu.appId || !secrets.feishu.appSecret) {
|
|
2057
|
+
throw new Error("\u98DE\u4E66\u914D\u7F6E\u4E0D\u5B8C\u6574\u3002\u8BF7\u5148\u8FD0\u884C chattercatcher setup \u6216 chattercatcher settings\u3002");
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
function createFeishuEventDispatcher(options) {
|
|
2061
|
+
const answeredMessageIds = /* @__PURE__ */ new Set();
|
|
2062
|
+
return new lark2.EventDispatcher({}).register({
|
|
2063
|
+
"im.message.receive_v1": async (data2) => {
|
|
2064
|
+
const payload = { event: data2 };
|
|
2065
|
+
if (options.questionHandler && isFeishuMessageAddressedToBot(payload)) {
|
|
2066
|
+
const platformMessageId = data2?.message?.message_id;
|
|
2067
|
+
if (platformMessageId && answeredMessageIds.has(platformMessageId)) {
|
|
2068
|
+
console.log("\u98DE\u4E66\u63D0\u95EE\u91CD\u590D\u6295\u9012\uFF1A\u5DF2\u8DF3\u8FC7\u56DE\u7B54\u3002");
|
|
2069
|
+
return;
|
|
2070
|
+
}
|
|
2071
|
+
const decision = getFeishuQuestionDecision(payload, options.config);
|
|
2072
|
+
if (decision.shouldAnswer) {
|
|
2073
|
+
if (platformMessageId) {
|
|
2074
|
+
answeredMessageIds.add(platformMessageId);
|
|
2075
|
+
}
|
|
2076
|
+
await options.questionHandler.handle(payload);
|
|
2077
|
+
console.log("\u98DE\u4E66\u63D0\u95EE\u5DF2\u56DE\u7B54\uFF1A\u8DF3\u8FC7\u77E5\u8BC6\u5E93\u5165\u5E93\u3002");
|
|
2078
|
+
return;
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
const result = options.resourceDownloader ? await options.ingestor.ingestFeishuEventAndDownloadAttachments({
|
|
2082
|
+
payload,
|
|
2083
|
+
downloader: options.resourceDownloader,
|
|
2084
|
+
config: options.config,
|
|
2085
|
+
vectorIndexMessage: options.attachmentVectorIndexer
|
|
2086
|
+
}) : options.ingestor.ingestFeishuEvent(payload);
|
|
2087
|
+
if (!result.accepted) {
|
|
2088
|
+
console.log(`\u98DE\u4E66\u6D88\u606F\u672A\u5165\u5E93\uFF1A${result.reason}`);
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
console.log(`\u98DE\u4E66\u6D88\u606F\u5DF2\u5165\u5E93\uFF1A${result.messageId}`);
|
|
2092
|
+
if (result.duplicate) {
|
|
2093
|
+
console.log("\u98DE\u4E66\u6D88\u606F\u91CD\u590D\u6295\u9012\uFF1A\u5DF2\u8DF3\u8FC7\u9644\u4EF6\u5904\u7406\u548C\u56DE\u7B54\u3002");
|
|
2094
|
+
return;
|
|
2095
|
+
}
|
|
2096
|
+
if (result.attachment?.downloaded) {
|
|
2097
|
+
console.log(`\u98DE\u4E66\u9644\u4EF6\u5DF2\u4E0B\u8F7D\uFF1A${result.attachment.downloaded.storedPath}`);
|
|
2098
|
+
if (result.attachment.indexedMessageId) {
|
|
2099
|
+
console.log(`\u98DE\u4E66\u9644\u4EF6\u5DF2\u8FDB\u5165 RAG\uFF1A${result.attachment.indexedMessageId}`);
|
|
2100
|
+
if (result.attachment.vectorIndexed) {
|
|
2101
|
+
console.log(
|
|
2102
|
+
`\u98DE\u4E66\u9644\u4EF6\u5411\u91CF\u7D22\u5F15\u5B8C\u6210\uFF1Achunks=${result.attachment.vectorIndexed.chunks}, vectors=${result.attachment.vectorIndexed.vectors}`
|
|
2103
|
+
);
|
|
2104
|
+
}
|
|
2105
|
+
} else if (result.attachment.skippedReason) {
|
|
2106
|
+
console.log(`\u98DE\u4E66\u9644\u4EF6\u6682\u672A\u8FDB\u5165 RAG\uFF1A${result.attachment.skippedReason}`);
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
if (options.questionHandler) {
|
|
2110
|
+
const decision = await options.questionHandler.handle(payload, {
|
|
2111
|
+
excludeMessageIds: result.messageId ? [result.messageId] : []
|
|
2112
|
+
});
|
|
2113
|
+
if (!decision.shouldAnswer) {
|
|
2114
|
+
console.log(`\u98DE\u4E66\u6D88\u606F\u4E0D\u89E6\u53D1\u56DE\u7B54\uFF1A${decision.reason}`);
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
});
|
|
2119
|
+
}
|
|
2120
|
+
function createFeishuGateway(options) {
|
|
2121
|
+
assertFeishuConfig(options.config, options.secrets);
|
|
2122
|
+
const wsClient = options.wsClientFactory?.({
|
|
2123
|
+
appId: options.config.feishu.appId,
|
|
2124
|
+
appSecret: options.secrets.feishu.appSecret,
|
|
2125
|
+
domain: mapDomain(options.config.feishu.domain),
|
|
2126
|
+
onReady: () => console.log("\u98DE\u4E66\u957F\u8FDE\u63A5\u5DF2\u5EFA\u7ACB\u3002"),
|
|
2127
|
+
onError: (error) => console.error(`\u98DE\u4E66\u957F\u8FDE\u63A5\u9519\u8BEF\uFF1A${error.message}`),
|
|
2128
|
+
onReconnecting: () => console.log("\u98DE\u4E66\u957F\u8FDE\u63A5\u6B63\u5728\u91CD\u8FDE\u3002"),
|
|
2129
|
+
onReconnected: () => console.log("\u98DE\u4E66\u957F\u8FDE\u63A5\u5DF2\u91CD\u8FDE\u3002")
|
|
2130
|
+
}) ?? new lark2.WSClient({
|
|
2131
|
+
appId: options.config.feishu.appId,
|
|
2132
|
+
appSecret: options.secrets.feishu.appSecret,
|
|
2133
|
+
domain: mapDomain(options.config.feishu.domain),
|
|
2134
|
+
loggerLevel: lark2.LoggerLevel.info,
|
|
2135
|
+
source: "chattercatcher",
|
|
2136
|
+
onReady: () => console.log("\u98DE\u4E66\u957F\u8FDE\u63A5\u5DF2\u5EFA\u7ACB\u3002"),
|
|
2137
|
+
onError: (error) => console.error(`\u98DE\u4E66\u957F\u8FDE\u63A5\u9519\u8BEF\uFF1A${error.message}`),
|
|
2138
|
+
onReconnecting: () => console.log("\u98DE\u4E66\u957F\u8FDE\u63A5\u6B63\u5728\u91CD\u8FDE\u3002"),
|
|
2139
|
+
onReconnected: () => console.log("\u98DE\u4E66\u957F\u8FDE\u63A5\u5DF2\u91CD\u8FDE\u3002")
|
|
2140
|
+
});
|
|
2141
|
+
const eventDispatcher = createFeishuEventDispatcher({
|
|
2142
|
+
config: options.config,
|
|
2143
|
+
ingestor: options.ingestor,
|
|
2144
|
+
questionHandler: options.questionHandler,
|
|
2145
|
+
resourceDownloader: options.resourceDownloader,
|
|
2146
|
+
attachmentVectorIndexer: options.attachmentVectorIndexer
|
|
2147
|
+
});
|
|
2148
|
+
return {
|
|
2149
|
+
async start() {
|
|
2150
|
+
await wsClient.start({ eventDispatcher });
|
|
2151
|
+
},
|
|
2152
|
+
stop() {
|
|
2153
|
+
wsClient.close({ force: true });
|
|
2154
|
+
}
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
// src/feishu/resource-downloader.ts
|
|
2159
|
+
import * as lark3 from "@larksuiteoapi/node-sdk";
|
|
2160
|
+
import fs8 from "fs/promises";
|
|
2161
|
+
import path10 from "path";
|
|
2162
|
+
var RESOURCE_TYPE_BY_KIND = {
|
|
2163
|
+
file: "file",
|
|
2164
|
+
image: "image",
|
|
2165
|
+
audio: "audio",
|
|
2166
|
+
media: "media"
|
|
2167
|
+
};
|
|
2168
|
+
var DEFAULT_EXTENSION_BY_KIND = {
|
|
2169
|
+
file: ".bin",
|
|
2170
|
+
image: ".jpg",
|
|
2171
|
+
audio: ".mp3",
|
|
2172
|
+
media: ".mp4"
|
|
2173
|
+
};
|
|
2174
|
+
function sanitizeFileName(value) {
|
|
2175
|
+
const sanitized = value.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_").trim();
|
|
2176
|
+
return sanitized || "feishu-resource";
|
|
2177
|
+
}
|
|
2178
|
+
function buildStoredFileName(input2) {
|
|
2179
|
+
const rawName = input2.attachment.fileName || `${input2.attachment.fileKey}${DEFAULT_EXTENSION_BY_KIND[input2.attachment.kind]}`;
|
|
2180
|
+
return `${input2.messageId}-${sanitizeFileName(rawName)}`;
|
|
2181
|
+
}
|
|
2182
|
+
var FeishuResourceDownloader = class _FeishuResourceDownloader {
|
|
2183
|
+
constructor(client, dataDir) {
|
|
2184
|
+
this.client = client;
|
|
2185
|
+
this.dataDir = dataDir;
|
|
2186
|
+
}
|
|
2187
|
+
client;
|
|
2188
|
+
dataDir;
|
|
2189
|
+
static fromConfig(config, secrets) {
|
|
2190
|
+
const client = new lark3.Client({
|
|
2191
|
+
appId: config.feishu.appId,
|
|
2192
|
+
appSecret: secrets.feishu.appSecret,
|
|
2193
|
+
domain: mapDomain(config.feishu.domain)
|
|
2194
|
+
});
|
|
2195
|
+
return new _FeishuResourceDownloader(client, resolveHomePath(config.storage.dataDir));
|
|
2196
|
+
}
|
|
2197
|
+
async download(input2) {
|
|
2198
|
+
const resourceType = RESOURCE_TYPE_BY_KIND[input2.attachment.kind];
|
|
2199
|
+
const targetDir = path10.join(this.dataDir, "files", "feishu");
|
|
2200
|
+
await fs8.mkdir(targetDir, { recursive: true });
|
|
2201
|
+
const fileName = buildStoredFileName(input2);
|
|
2202
|
+
const storedPath = path10.join(targetDir, fileName);
|
|
2203
|
+
const payload = {
|
|
2204
|
+
params: { type: resourceType },
|
|
2205
|
+
path: { message_id: input2.messageId, file_key: input2.attachment.fileKey }
|
|
2206
|
+
};
|
|
2207
|
+
const api = this.client.im.v1?.messageResource?.get ?? this.client.im.messageResource?.get;
|
|
2208
|
+
if (!api) {
|
|
2209
|
+
throw new Error("\u5F53\u524D\u98DE\u4E66 SDK \u4E0D\u652F\u6301 messageResource.get\uFF0C\u65E0\u6CD5\u4E0B\u8F7D\u6D88\u606F\u8D44\u6E90\u3002");
|
|
2210
|
+
}
|
|
2211
|
+
const response = await api(payload);
|
|
2212
|
+
await response.writeFile(storedPath);
|
|
2213
|
+
return {
|
|
2214
|
+
messageId: input2.messageId,
|
|
2215
|
+
fileKey: input2.attachment.fileKey,
|
|
2216
|
+
fileName,
|
|
2217
|
+
resourceType,
|
|
2218
|
+
storedPath
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
};
|
|
2222
|
+
|
|
2223
|
+
// src/files/ingest.ts
|
|
2224
|
+
import crypto3 from "crypto";
|
|
2225
|
+
import fs10 from "fs/promises";
|
|
2226
|
+
import path12 from "path";
|
|
2227
|
+
|
|
2228
|
+
// src/files/parser.ts
|
|
2229
|
+
import fs9 from "fs/promises";
|
|
2230
|
+
import path11 from "path";
|
|
2231
|
+
import mammoth from "mammoth";
|
|
2232
|
+
import { PDFParse } from "pdf-parse";
|
|
2233
|
+
var TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".txt", ".md", ".markdown", ".json", ".csv", ".tsv", ".log"]);
|
|
2234
|
+
var DOCX_EXTENSIONS = /* @__PURE__ */ new Set([".docx"]);
|
|
2235
|
+
var PDF_EXTENSIONS = /* @__PURE__ */ new Set([".pdf"]);
|
|
2236
|
+
function isSupportedParseFile(filePath) {
|
|
2237
|
+
const extension = path11.extname(filePath).toLowerCase();
|
|
2238
|
+
return TEXT_EXTENSIONS.has(extension) || DOCX_EXTENSIONS.has(extension) || PDF_EXTENSIONS.has(extension);
|
|
2239
|
+
}
|
|
2240
|
+
function describeSupportedParseTypes() {
|
|
2241
|
+
return "txt\u3001md\u3001json\u3001csv\u3001tsv\u3001log\u3001docx\u3001pdf";
|
|
2242
|
+
}
|
|
2243
|
+
async function parseFileToText(filePath) {
|
|
2244
|
+
const extension = path11.extname(filePath).toLowerCase();
|
|
2245
|
+
if (TEXT_EXTENSIONS.has(extension)) {
|
|
2246
|
+
return {
|
|
2247
|
+
text: await fs9.readFile(filePath, "utf8"),
|
|
2248
|
+
parser: "text",
|
|
2249
|
+
warnings: []
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
if (DOCX_EXTENSIONS.has(extension)) {
|
|
2253
|
+
const result = await mammoth.extractRawText({ path: filePath });
|
|
2254
|
+
return {
|
|
2255
|
+
text: result.value,
|
|
2256
|
+
parser: "docx",
|
|
2257
|
+
warnings: result.messages.map((message) => message.message)
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
if (PDF_EXTENSIONS.has(extension)) {
|
|
2261
|
+
const buffer = await fs9.readFile(filePath);
|
|
2262
|
+
const parser = new PDFParse({ data: buffer });
|
|
2263
|
+
try {
|
|
2264
|
+
const result = await parser.getText();
|
|
2265
|
+
return {
|
|
2266
|
+
text: result.text,
|
|
2267
|
+
parser: "pdf",
|
|
2268
|
+
warnings: []
|
|
2269
|
+
};
|
|
2270
|
+
} finally {
|
|
2271
|
+
await parser.destroy();
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
throw new Error(`\u6682\u4E0D\u652F\u6301\u8BE5\u6587\u4EF6\u7C7B\u578B\uFF1A${extension || "\u65E0\u6269\u5C55\u540D"}\u3002\u5F53\u524D\u652F\u6301 ${describeSupportedParseTypes()}\u3002`);
|
|
2275
|
+
}
|
|
2276
|
+
|
|
2277
|
+
// src/files/ingest.ts
|
|
2278
|
+
function isSupportedTextFile(filePath) {
|
|
2279
|
+
return isSupportedParseFile(filePath);
|
|
2280
|
+
}
|
|
2281
|
+
function ensureSupportedTextFile(filePath) {
|
|
2282
|
+
if (!isSupportedTextFile(filePath)) {
|
|
2283
|
+
const extension = path12.extname(filePath).toLowerCase();
|
|
2284
|
+
throw new Error(`\u6682\u4E0D\u652F\u6301\u8BE5\u6587\u4EF6\u7C7B\u578B\uFF1A${extension || "\u65E0\u6269\u5C55\u540D"}\u3002\u5F53\u524D\u652F\u6301 ${describeSupportedParseTypes()}\u3002`);
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
function stableStoredName(sourcePath, fileName) {
|
|
2288
|
+
const digest = crypto3.createHash("sha256").update(sourcePath).digest("hex").slice(0, 16);
|
|
2289
|
+
return `${digest}-${fileName}`;
|
|
2290
|
+
}
|
|
2291
|
+
async function ingestLocalFile(input2) {
|
|
2292
|
+
const sourcePath = path12.resolve(input2.filePath);
|
|
2293
|
+
const fileName = path12.basename(sourcePath);
|
|
2294
|
+
const jobId = input2.jobs?.start({ sourcePath, fileName });
|
|
2295
|
+
try {
|
|
2296
|
+
ensureSupportedTextFile(sourcePath);
|
|
2297
|
+
const stat = await fs10.stat(sourcePath);
|
|
2298
|
+
if (!stat.isFile()) {
|
|
2299
|
+
throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${sourcePath}`);
|
|
2300
|
+
}
|
|
2301
|
+
const parsed = await parseFileToText(sourcePath);
|
|
2302
|
+
const text = parsed.text.trim();
|
|
2303
|
+
if (!text) {
|
|
2304
|
+
throw new Error(`\u6587\u4EF6\u6CA1\u6709\u53EF\u7D22\u5F15\u6587\u672C\uFF1A${sourcePath}`);
|
|
2305
|
+
}
|
|
2306
|
+
const fileDir = path12.join(resolveHomePath(input2.config.storage.dataDir), "files");
|
|
2307
|
+
await fs10.mkdir(fileDir, { recursive: true });
|
|
2308
|
+
const storedPath = path12.join(fileDir, stableStoredName(sourcePath, fileName));
|
|
2309
|
+
await fs10.copyFile(sourcePath, storedPath);
|
|
2310
|
+
const messageId = input2.messages.ingest({
|
|
2311
|
+
platform: "local-file",
|
|
2312
|
+
platformChatId: "local-files",
|
|
2313
|
+
chatName: "\u6587\u4EF6\u5E93",
|
|
2314
|
+
platformMessageId: sourcePath,
|
|
2315
|
+
senderId: "local-file",
|
|
2316
|
+
senderName: fileName,
|
|
2317
|
+
messageType: "file",
|
|
2318
|
+
text,
|
|
2319
|
+
sentAt: stat.mtime.toISOString(),
|
|
2320
|
+
rawPayload: {
|
|
2321
|
+
sourcePath,
|
|
2322
|
+
storedPath,
|
|
2323
|
+
bytes: stat.size,
|
|
2324
|
+
fileName,
|
|
2325
|
+
parser: parsed.parser,
|
|
2326
|
+
parserWarnings: parsed.warnings
|
|
2327
|
+
}
|
|
2328
|
+
});
|
|
2329
|
+
input2.jobs?.complete({
|
|
2330
|
+
id: jobId ?? "",
|
|
2331
|
+
storedPath,
|
|
2332
|
+
parser: parsed.parser,
|
|
2333
|
+
messageId,
|
|
2334
|
+
bytes: stat.size,
|
|
2335
|
+
characters: text.length,
|
|
2336
|
+
warnings: parsed.warnings
|
|
2337
|
+
});
|
|
2338
|
+
return {
|
|
2339
|
+
messageId,
|
|
2340
|
+
sourcePath,
|
|
2341
|
+
storedPath,
|
|
2342
|
+
fileName,
|
|
2343
|
+
bytes: stat.size,
|
|
2344
|
+
characters: text.length,
|
|
2345
|
+
parser: parsed.parser,
|
|
2346
|
+
warnings: parsed.warnings,
|
|
2347
|
+
jobId
|
|
2348
|
+
};
|
|
2349
|
+
} catch (error) {
|
|
2350
|
+
if (jobId) {
|
|
2351
|
+
input2.jobs?.fail({
|
|
2352
|
+
id: jobId,
|
|
2353
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
2356
|
+
throw error;
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
2359
|
+
|
|
2360
|
+
// src/feishu/normalize.ts
|
|
2361
|
+
function asObject2(value) {
|
|
2362
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
2363
|
+
}
|
|
2364
|
+
function parseContent(content) {
|
|
2365
|
+
if (!content) {
|
|
2366
|
+
return {};
|
|
2367
|
+
}
|
|
2368
|
+
try {
|
|
2369
|
+
return asObject2(JSON.parse(content));
|
|
2370
|
+
} catch {
|
|
2371
|
+
return { text: content };
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
function stringifyUnknown(value) {
|
|
2375
|
+
if (typeof value === "string") {
|
|
2376
|
+
return value;
|
|
2377
|
+
}
|
|
2378
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
2379
|
+
return String(value);
|
|
2380
|
+
}
|
|
2381
|
+
return "";
|
|
2382
|
+
}
|
|
2383
|
+
function numberUnknown(value) {
|
|
2384
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
2385
|
+
return value;
|
|
2386
|
+
}
|
|
2387
|
+
if (typeof value === "string") {
|
|
2388
|
+
const parsed = Number(value);
|
|
2389
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
2390
|
+
}
|
|
2391
|
+
return void 0;
|
|
2392
|
+
}
|
|
2393
|
+
function extractPostText(content) {
|
|
2394
|
+
const post = asObject2(content.post);
|
|
2395
|
+
const zhCn = asObject2(post.zh_cn ?? post["zh-CN"] ?? post.en_us ?? post["en-US"]);
|
|
2396
|
+
const title = stringifyUnknown(zhCn.title);
|
|
2397
|
+
const blocks = Array.isArray(zhCn.content) ? zhCn.content : [];
|
|
2398
|
+
const parts = [];
|
|
2399
|
+
if (title) {
|
|
2400
|
+
parts.push(title);
|
|
2401
|
+
}
|
|
2402
|
+
for (const block of blocks) {
|
|
2403
|
+
if (!Array.isArray(block)) {
|
|
2404
|
+
continue;
|
|
2405
|
+
}
|
|
2406
|
+
for (const item of block) {
|
|
2407
|
+
const object = asObject2(item);
|
|
2408
|
+
const text = stringifyUnknown(object.text);
|
|
2409
|
+
if (text) {
|
|
2410
|
+
parts.push(text);
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
return parts.join(" ").trim();
|
|
2415
|
+
}
|
|
2416
|
+
function extractFeishuAttachment(messageType, content) {
|
|
2417
|
+
if (messageType === "image") {
|
|
2418
|
+
const fileKey2 = stringifyUnknown(content.image_key);
|
|
2419
|
+
return fileKey2 ? { platform: "feishu", kind: "image", fileKey: fileKey2 } : void 0;
|
|
2420
|
+
}
|
|
2421
|
+
if (messageType === "audio") {
|
|
2422
|
+
const fileKey2 = stringifyUnknown(content.file_key);
|
|
2423
|
+
return fileKey2 ? { platform: "feishu", kind: "audio", fileKey: fileKey2 } : void 0;
|
|
2424
|
+
}
|
|
2425
|
+
if (messageType !== "file" && messageType !== "media") {
|
|
2426
|
+
return void 0;
|
|
2427
|
+
}
|
|
2428
|
+
const fileKey = stringifyUnknown(content.file_key);
|
|
2429
|
+
if (!fileKey) {
|
|
2430
|
+
return void 0;
|
|
2431
|
+
}
|
|
2432
|
+
return {
|
|
2433
|
+
platform: "feishu",
|
|
2434
|
+
kind: messageType,
|
|
2435
|
+
fileKey,
|
|
2436
|
+
fileName: stringifyUnknown(content.file_name) || void 0,
|
|
2437
|
+
mimeType: stringifyUnknown(content.mime_type) || void 0,
|
|
2438
|
+
size: numberUnknown(content.file_size ?? content.size)
|
|
2439
|
+
};
|
|
2440
|
+
}
|
|
2441
|
+
function extractMessageText(messageType, content) {
|
|
2442
|
+
if (messageType === "text") {
|
|
2443
|
+
return stringifyUnknown(content.text).trim();
|
|
2444
|
+
}
|
|
2445
|
+
if (messageType === "post") {
|
|
2446
|
+
return extractPostText(content);
|
|
2447
|
+
}
|
|
2448
|
+
if (messageType === "image") {
|
|
2449
|
+
return `[\u56FE\u7247] ${stringifyUnknown(content.image_key)}`.trim();
|
|
2450
|
+
}
|
|
2451
|
+
if (messageType === "file") {
|
|
2452
|
+
return `[\u6587\u4EF6] ${stringifyUnknown(content.file_name) || stringifyUnknown(content.file_key)}`.trim();
|
|
2453
|
+
}
|
|
2454
|
+
if (messageType === "audio") {
|
|
2455
|
+
return `[\u8BED\u97F3] ${stringifyUnknown(content.file_key)}`.trim();
|
|
2456
|
+
}
|
|
2457
|
+
if (messageType === "media") {
|
|
2458
|
+
return `[\u5A92\u4F53] ${stringifyUnknown(content.file_name) || stringifyUnknown(content.file_key)}`.trim();
|
|
2459
|
+
}
|
|
2460
|
+
const fallback = Object.entries(content).map(([key, value]) => `${key}: ${stringifyUnknown(value)}`).filter((line) => !line.endsWith(": ")).join(" ");
|
|
2461
|
+
return fallback || `[${messageType}]`;
|
|
2462
|
+
}
|
|
2463
|
+
function normalizeTimestamp(createTime) {
|
|
2464
|
+
if (!createTime) {
|
|
2465
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
2466
|
+
}
|
|
2467
|
+
const numeric = Number(createTime);
|
|
2468
|
+
if (Number.isFinite(numeric)) {
|
|
2469
|
+
const milliseconds = createTime.length <= 10 ? numeric * 1e3 : numeric;
|
|
2470
|
+
return new Date(milliseconds).toISOString();
|
|
2471
|
+
}
|
|
2472
|
+
const date = new Date(createTime);
|
|
2473
|
+
if (Number.isNaN(date.getTime())) {
|
|
2474
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
2475
|
+
}
|
|
2476
|
+
return date.toISOString();
|
|
2477
|
+
}
|
|
2478
|
+
function normalizeFeishuReceiveMessageEvent(payload) {
|
|
2479
|
+
const event = payload.event;
|
|
2480
|
+
const message = event?.message;
|
|
2481
|
+
if (!event || !message?.message_id || !message.chat_id) {
|
|
2482
|
+
return null;
|
|
2483
|
+
}
|
|
2484
|
+
const messageType = message.message_type || "unknown";
|
|
2485
|
+
const content = parseContent(message.content);
|
|
2486
|
+
const text = extractMessageText(messageType, content);
|
|
2487
|
+
if (!text) {
|
|
2488
|
+
return null;
|
|
2489
|
+
}
|
|
2490
|
+
const senderId = event.sender?.sender_id?.open_id || event.sender?.sender_id?.user_id || event.sender?.sender_id?.union_id || "unknown";
|
|
2491
|
+
return {
|
|
2492
|
+
platform: "feishu",
|
|
2493
|
+
platformChatId: message.chat_id,
|
|
2494
|
+
chatName: message.chat_id,
|
|
2495
|
+
platformMessageId: message.message_id,
|
|
2496
|
+
senderId,
|
|
2497
|
+
senderName: senderId,
|
|
2498
|
+
messageType,
|
|
2499
|
+
text,
|
|
2500
|
+
sentAt: normalizeTimestamp(message.create_time),
|
|
2501
|
+
rawPayload: {
|
|
2502
|
+
platform: "feishu",
|
|
2503
|
+
raw: payload,
|
|
2504
|
+
content,
|
|
2505
|
+
attachment: extractFeishuAttachment(messageType, content)
|
|
2506
|
+
}
|
|
2507
|
+
};
|
|
2508
|
+
}
|
|
2509
|
+
|
|
2510
|
+
// src/gateway/ingest.ts
|
|
2511
|
+
function extractAttachment(message) {
|
|
2512
|
+
const raw = message.rawPayload;
|
|
2513
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
2514
|
+
return void 0;
|
|
2515
|
+
}
|
|
2516
|
+
const attachment = raw.attachment;
|
|
2517
|
+
if (!attachment || typeof attachment !== "object" || Array.isArray(attachment)) {
|
|
2518
|
+
return void 0;
|
|
2519
|
+
}
|
|
2520
|
+
const candidate = attachment;
|
|
2521
|
+
if (candidate.platform !== "feishu" || !candidate.kind || !candidate.fileKey) {
|
|
2522
|
+
return void 0;
|
|
2523
|
+
}
|
|
2524
|
+
return candidate;
|
|
2525
|
+
}
|
|
2526
|
+
var GatewayIngestor = class {
|
|
2527
|
+
messages;
|
|
2528
|
+
jobs;
|
|
2529
|
+
constructor(database) {
|
|
2530
|
+
this.messages = new MessageRepository(database);
|
|
2531
|
+
this.jobs = new FileJobRepository(database);
|
|
2532
|
+
}
|
|
2533
|
+
ingestFeishuEvent(payload) {
|
|
2534
|
+
const normalized = normalizeFeishuReceiveMessageEvent(payload);
|
|
2535
|
+
if (!normalized) {
|
|
2536
|
+
return {
|
|
2537
|
+
accepted: false,
|
|
2538
|
+
reason: "\u4E8B\u4EF6\u4E0D\u662F\u53EF\u5165\u5E93\u7684\u98DE\u4E66\u6D88\u606F\u3002"
|
|
2539
|
+
};
|
|
2540
|
+
}
|
|
2541
|
+
const duplicate = this.messages.hasPlatformMessage(normalized.platform, normalized.platformMessageId);
|
|
2542
|
+
const messageId = this.messages.ingest(normalized);
|
|
2543
|
+
return {
|
|
2544
|
+
accepted: true,
|
|
2545
|
+
messageId,
|
|
2546
|
+
message: normalized,
|
|
2547
|
+
duplicate
|
|
2548
|
+
};
|
|
2549
|
+
}
|
|
2550
|
+
async ingestFeishuEventAndDownloadAttachments(input2) {
|
|
2551
|
+
const result = this.ingestFeishuEvent(input2.payload);
|
|
2552
|
+
if (!result.accepted || !result.messageId || !result.message || result.duplicate) {
|
|
2553
|
+
return result;
|
|
2554
|
+
}
|
|
2555
|
+
const attachment = extractAttachment(result.message);
|
|
2556
|
+
if (!attachment) {
|
|
2557
|
+
return result;
|
|
2558
|
+
}
|
|
2559
|
+
const downloaded = await input2.downloader.download({
|
|
2560
|
+
messageId: result.message.platformMessageId,
|
|
2561
|
+
attachment
|
|
2562
|
+
});
|
|
2563
|
+
if (!isSupportedTextFile(downloaded.storedPath)) {
|
|
2564
|
+
return {
|
|
2565
|
+
...result,
|
|
2566
|
+
attachment: {
|
|
2567
|
+
downloaded,
|
|
2568
|
+
skippedReason: "\u9644\u4EF6\u5DF2\u4E0B\u8F7D\uFF0C\u4F46\u5F53\u524D\u6587\u4EF6\u7C7B\u578B\u6682\u4E0D\u652F\u6301\u89E3\u6790\u3002"
|
|
2569
|
+
}
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
const indexedMessageId = await ingestLocalFile({
|
|
2573
|
+
config: input2.config,
|
|
2574
|
+
messages: this.messages,
|
|
2575
|
+
jobs: this.jobs,
|
|
2576
|
+
filePath: downloaded.storedPath
|
|
2577
|
+
}).then((file) => file.messageId);
|
|
2578
|
+
const vectorIndexed = input2.vectorIndexMessage ? await input2.vectorIndexMessage(indexedMessageId) : void 0;
|
|
2579
|
+
return {
|
|
2580
|
+
...result,
|
|
2581
|
+
attachment: {
|
|
2582
|
+
downloaded,
|
|
2583
|
+
indexedMessageId,
|
|
2584
|
+
vectorIndexed
|
|
2585
|
+
}
|
|
2586
|
+
};
|
|
2587
|
+
}
|
|
2588
|
+
};
|
|
2589
|
+
|
|
2590
|
+
// src/logs/reader.ts
|
|
2591
|
+
import fs11 from "fs/promises";
|
|
2592
|
+
import { watch } from "fs";
|
|
2593
|
+
import path13 from "path";
|
|
2594
|
+
function getLogsDirectory() {
|
|
2595
|
+
return path13.join(getChatterCatcherHome(), "logs");
|
|
2596
|
+
}
|
|
2597
|
+
function resolveLogPath(fileName, logsDir = getLogsDirectory()) {
|
|
2598
|
+
return path13.isAbsolute(fileName) ? fileName : path13.join(logsDir, fileName);
|
|
2599
|
+
}
|
|
2600
|
+
function normalizeLineCount(value, fallback = 200) {
|
|
2601
|
+
const parsed = Number(value ?? fallback);
|
|
2602
|
+
return Number.isFinite(parsed) ? Math.min(Math.max(Math.trunc(parsed), 1), 1e4) : fallback;
|
|
2603
|
+
}
|
|
2604
|
+
async function listLogFiles(logsDir = getLogsDirectory()) {
|
|
2605
|
+
let entries;
|
|
2606
|
+
try {
|
|
2607
|
+
entries = await fs11.readdir(logsDir, { withFileTypes: true });
|
|
2608
|
+
} catch (error) {
|
|
2609
|
+
if (error.code === "ENOENT") {
|
|
2610
|
+
return [];
|
|
2611
|
+
}
|
|
2612
|
+
throw error;
|
|
2613
|
+
}
|
|
2614
|
+
const files2 = await Promise.all(
|
|
2615
|
+
entries.filter((entry) => entry.isFile() && entry.name.endsWith(".log")).map(async (entry) => {
|
|
2616
|
+
const filePath = path13.join(logsDir, entry.name);
|
|
2617
|
+
const stats = await fs11.stat(filePath);
|
|
2618
|
+
return {
|
|
2619
|
+
name: entry.name,
|
|
2620
|
+
path: filePath,
|
|
2621
|
+
updatedAt: stats.mtime,
|
|
2622
|
+
bytes: stats.size
|
|
2623
|
+
};
|
|
2624
|
+
})
|
|
2625
|
+
);
|
|
2626
|
+
return files2.sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());
|
|
2627
|
+
}
|
|
2628
|
+
function tailLines(content, lines) {
|
|
2629
|
+
const normalized = content.replace(/\r\n/g, "\n");
|
|
2630
|
+
const parts = normalized.endsWith("\n") ? normalized.slice(0, -1).split("\n") : normalized.split("\n");
|
|
2631
|
+
return parts.slice(-lines).join("\n");
|
|
2632
|
+
}
|
|
2633
|
+
async function readLogTail(input2) {
|
|
2634
|
+
const stats = await fs11.stat(input2.filePath);
|
|
2635
|
+
const content = await fs11.readFile(input2.filePath, "utf8");
|
|
2636
|
+
return {
|
|
2637
|
+
file: {
|
|
2638
|
+
name: path13.basename(input2.filePath),
|
|
2639
|
+
path: input2.filePath,
|
|
2640
|
+
updatedAt: stats.mtime,
|
|
2641
|
+
bytes: stats.size
|
|
2642
|
+
},
|
|
2643
|
+
content: tailLines(content, normalizeLineCount(input2.lines))
|
|
2644
|
+
};
|
|
2645
|
+
}
|
|
2646
|
+
async function readLatestLogTail(input2 = {}) {
|
|
2647
|
+
if (input2.fileName) {
|
|
2648
|
+
return readLogTail({
|
|
2649
|
+
filePath: resolveLogPath(input2.fileName, input2.logsDir),
|
|
2650
|
+
lines: input2.lines
|
|
2651
|
+
});
|
|
2652
|
+
}
|
|
2653
|
+
const [latest] = await listLogFiles(input2.logsDir);
|
|
2654
|
+
if (!latest) {
|
|
2655
|
+
return null;
|
|
2656
|
+
}
|
|
2657
|
+
return readLogTail({ filePath: latest.path, lines: input2.lines });
|
|
2658
|
+
}
|
|
2659
|
+
async function followLogFile(input2) {
|
|
2660
|
+
let offset = (await fs11.stat(input2.filePath)).size;
|
|
2661
|
+
const directory = path13.dirname(input2.filePath);
|
|
2662
|
+
const fileName = path13.basename(input2.filePath);
|
|
2663
|
+
async function readAppended() {
|
|
2664
|
+
const stats = await fs11.stat(input2.filePath);
|
|
2665
|
+
if (stats.size < offset) {
|
|
2666
|
+
offset = 0;
|
|
2667
|
+
}
|
|
2668
|
+
if (stats.size === offset) {
|
|
2669
|
+
return;
|
|
2670
|
+
}
|
|
2671
|
+
const handle = await fs11.open(input2.filePath, "r");
|
|
2672
|
+
try {
|
|
2673
|
+
const length = stats.size - offset;
|
|
2674
|
+
const buffer = Buffer.alloc(length);
|
|
2675
|
+
await handle.read(buffer, 0, length, offset);
|
|
2676
|
+
offset = stats.size;
|
|
2677
|
+
input2.onChunk(buffer.toString("utf8"));
|
|
2678
|
+
} finally {
|
|
2679
|
+
await handle.close();
|
|
2680
|
+
}
|
|
2681
|
+
}
|
|
2682
|
+
const watcher = watch(directory, (eventType, changedFileName) => {
|
|
2683
|
+
if (eventType !== "change" || changedFileName?.toString() !== fileName) {
|
|
2684
|
+
return;
|
|
2685
|
+
}
|
|
2686
|
+
void readAppended().catch((error) => {
|
|
2687
|
+
input2.onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
2688
|
+
});
|
|
2689
|
+
});
|
|
2690
|
+
return () => watcher.close();
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
// src/rag/indexer.ts
|
|
2694
|
+
async function indexMessageChunks(input2) {
|
|
2695
|
+
const chunks = input2.messageIds ? input2.messages.listMessageChunksByMessageIds(input2.messageIds, input2.limit ?? 1e4) : input2.messages.listAllMessageChunks(input2.limit ?? 1e4);
|
|
2696
|
+
if (chunks.length === 0) {
|
|
2697
|
+
return { chunks: 0, vectors: 0 };
|
|
2698
|
+
}
|
|
2699
|
+
const vectors = await input2.embedding.embedBatch(chunks.map((chunk) => chunk.text));
|
|
2700
|
+
const records = [];
|
|
2701
|
+
for (const [index2, chunk] of chunks.entries()) {
|
|
2702
|
+
const vector = vectors[index2];
|
|
2703
|
+
if (!vector || vector.length === 0) {
|
|
2704
|
+
continue;
|
|
2705
|
+
}
|
|
2706
|
+
records.push({
|
|
2707
|
+
id: chunk.chunkId,
|
|
2708
|
+
vector,
|
|
2709
|
+
evidence: {
|
|
2710
|
+
id: chunk.chunkId,
|
|
2711
|
+
text: chunk.text,
|
|
2712
|
+
score: 1,
|
|
2713
|
+
source: toEvidenceSource2(chunk)
|
|
2714
|
+
}
|
|
2715
|
+
});
|
|
2716
|
+
}
|
|
2717
|
+
await input2.store.upsert(records);
|
|
2718
|
+
return {
|
|
2719
|
+
chunks: chunks.length,
|
|
2720
|
+
vectors: records.length
|
|
2721
|
+
};
|
|
2722
|
+
}
|
|
2723
|
+
function toEvidenceSource2(chunk) {
|
|
2724
|
+
if (chunk.messageType === "file") {
|
|
2725
|
+
return {
|
|
2726
|
+
type: "file",
|
|
2727
|
+
label: chunk.senderName,
|
|
2728
|
+
timestamp: chunk.sentAt
|
|
2729
|
+
};
|
|
2730
|
+
}
|
|
2731
|
+
return {
|
|
2732
|
+
type: "message",
|
|
2733
|
+
label: chunk.chatName,
|
|
2734
|
+
sender: chunk.senderName,
|
|
2735
|
+
timestamp: chunk.sentAt
|
|
2736
|
+
};
|
|
2737
|
+
}
|
|
2738
|
+
|
|
2739
|
+
// src/rag/manual-index.ts
|
|
2740
|
+
async function processMessagesNow(input2) {
|
|
2741
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2742
|
+
if (!hasEmbeddingConfig(input2.config, input2.secrets)) {
|
|
2743
|
+
return {
|
|
2744
|
+
status: "skipped",
|
|
2745
|
+
reason: "Embedding \u914D\u7F6E\u4E0D\u5B8C\u6574\uFF1BSQLite FTS \u5DF2\u5728\u6D88\u606F\u5165\u5E93\u65F6\u5373\u65F6\u66F4\u65B0\u3002",
|
|
2746
|
+
chunks: 0,
|
|
2747
|
+
vectors: 0,
|
|
2748
|
+
startedAt,
|
|
2749
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2750
|
+
};
|
|
2751
|
+
}
|
|
2752
|
+
const vectorStore = new SQLiteVectorStore(input2.database);
|
|
2753
|
+
try {
|
|
2754
|
+
const stats = await indexMessageChunks({
|
|
2755
|
+
messages: new MessageRepository(input2.database),
|
|
2756
|
+
embedding: createEmbeddingModel(input2.config, input2.secrets),
|
|
2757
|
+
store: vectorStore,
|
|
2758
|
+
limit: input2.limit
|
|
2759
|
+
});
|
|
2760
|
+
return {
|
|
2761
|
+
status: "completed",
|
|
2762
|
+
chunks: stats.chunks,
|
|
2763
|
+
vectors: stats.vectors,
|
|
2764
|
+
startedAt,
|
|
2765
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2766
|
+
};
|
|
2767
|
+
} finally {
|
|
2768
|
+
vectorStore.close();
|
|
2769
|
+
}
|
|
2770
|
+
}
|
|
2771
|
+
|
|
2772
|
+
// src/web/server.ts
|
|
2773
|
+
import Fastify from "fastify";
|
|
2774
|
+
function buildHtml() {
|
|
2775
|
+
return `<!doctype html>
|
|
2776
|
+
<html lang="zh-CN">
|
|
2777
|
+
<head>
|
|
2778
|
+
<meta charset="utf-8" />
|
|
2779
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
2780
|
+
<title>ChatterCatcher</title>
|
|
2781
|
+
<style>
|
|
2782
|
+
:root {
|
|
2783
|
+
color-scheme: light;
|
|
2784
|
+
--bg: #f6f5f0;
|
|
2785
|
+
--panel: #ffffff;
|
|
2786
|
+
--text: #1f2933;
|
|
2787
|
+
--muted: #667085;
|
|
2788
|
+
--line: #d9d7cf;
|
|
2789
|
+
--accent: #1f7a5a;
|
|
2790
|
+
--warn: #9a5b13;
|
|
2791
|
+
}
|
|
2792
|
+
* { box-sizing: border-box; }
|
|
2793
|
+
body {
|
|
2794
|
+
margin: 0;
|
|
2795
|
+
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
2796
|
+
background: var(--bg);
|
|
2797
|
+
color: var(--text);
|
|
2798
|
+
}
|
|
2799
|
+
main { max-width: 1120px; margin: 0 auto; padding: 32px 24px 48px; overflow-x: hidden; }
|
|
2800
|
+
header {
|
|
2801
|
+
display: flex;
|
|
2802
|
+
justify-content: space-between;
|
|
2803
|
+
gap: 20px;
|
|
2804
|
+
align-items: flex-start;
|
|
2805
|
+
padding-bottom: 24px;
|
|
2806
|
+
border-bottom: 1px solid var(--line);
|
|
2807
|
+
}
|
|
2808
|
+
h1 { margin: 0; font-size: 30px; line-height: 1.1; letter-spacing: 0; }
|
|
2809
|
+
h2 { margin: 0 0 12px; font-size: 18px; letter-spacing: 0; }
|
|
2810
|
+
p { margin: 8px 0 0; color: var(--muted); }
|
|
2811
|
+
code { background: #eceae2; border-radius: 4px; padding: 2px 6px; }
|
|
2812
|
+
button {
|
|
2813
|
+
appearance: none;
|
|
2814
|
+
border: 1px solid var(--line);
|
|
2815
|
+
background: var(--panel);
|
|
2816
|
+
color: var(--text);
|
|
2817
|
+
border-radius: 6px;
|
|
2818
|
+
padding: 8px 12px;
|
|
2819
|
+
cursor: pointer;
|
|
2820
|
+
}
|
|
2821
|
+
button:hover { border-color: var(--accent); }
|
|
2822
|
+
.actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: flex-end; }
|
|
2823
|
+
.grid {
|
|
2824
|
+
display: grid;
|
|
2825
|
+
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
|
2826
|
+
gap: 12px;
|
|
2827
|
+
margin: 24px 0;
|
|
2828
|
+
}
|
|
2829
|
+
.metric {
|
|
2830
|
+
background: var(--panel);
|
|
2831
|
+
border: 1px solid var(--line);
|
|
2832
|
+
border-radius: 8px;
|
|
2833
|
+
padding: 16px;
|
|
2834
|
+
min-height: 112px;
|
|
2835
|
+
}
|
|
2836
|
+
.label { color: var(--muted); font-size: 13px; }
|
|
2837
|
+
.value { margin-top: 10px; font-size: 22px; font-weight: 650; overflow-wrap: anywhere; line-height: 1.18; }
|
|
2838
|
+
.note { margin-top: 8px; color: var(--muted); font-size: 13px; line-height: 1.45; }
|
|
2839
|
+
.layout {
|
|
2840
|
+
display: grid;
|
|
2841
|
+
grid-template-columns: minmax(0, 1fr) minmax(280px, 380px);
|
|
2842
|
+
gap: 24px;
|
|
2843
|
+
}
|
|
2844
|
+
.layout > * { min-width: 0; }
|
|
2845
|
+
section { padding: 20px 0; border-top: 1px solid var(--line); }
|
|
2846
|
+
section:first-child { border-top: 0; }
|
|
2847
|
+
.message-list { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
|
|
2848
|
+
.message-item { padding: 14px 16px; border-bottom: 1px solid var(--line); }
|
|
2849
|
+
.message-item:last-child { border-bottom: 0; }
|
|
2850
|
+
.message-meta { display: flex; flex-wrap: wrap; gap: 8px 14px; color: var(--muted); font-size: 13px; line-height: 1.4; }
|
|
2851
|
+
.message-body { margin-top: 8px; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.55; }
|
|
2852
|
+
table { width: 100%; table-layout: fixed; border-collapse: collapse; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
|
|
2853
|
+
th, td { padding: 12px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; overflow: hidden; text-overflow: ellipsis; }
|
|
2854
|
+
th { color: var(--muted); font-size: 13px; font-weight: 600; }
|
|
2855
|
+
tr:last-child td { border-bottom: 0; }
|
|
2856
|
+
.message { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
2857
|
+
.id-text, .path { display: block; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--muted); font-size: 13px; }
|
|
2858
|
+
.compact-table th:first-child, .compact-table td:first-child { width: 120px; }
|
|
2859
|
+
.compact-table th:nth-child(2), .compact-table td:nth-child(2) { width: 180px; }
|
|
2860
|
+
.status-ok { color: var(--accent); }
|
|
2861
|
+
.status-warn { color: var(--warn); }
|
|
2862
|
+
.empty { color: var(--muted); padding: 18px; background: var(--panel); border: 1px dashed var(--line); border-radius: 8px; }
|
|
2863
|
+
.status-line { margin-top: 10px; font-size: 13px; color: var(--muted); text-align: right; }
|
|
2864
|
+
@media (max-width: 900px) {
|
|
2865
|
+
header, .layout { display: block; }
|
|
2866
|
+
.grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
|
2867
|
+
header button { margin-top: 16px; }
|
|
2868
|
+
}
|
|
2869
|
+
@media (max-width: 560px) {
|
|
2870
|
+
main { padding: 24px 16px 36px; }
|
|
2871
|
+
.grid { grid-template-columns: 1fr; }
|
|
2872
|
+
}
|
|
2873
|
+
</style>
|
|
2874
|
+
</head>
|
|
2875
|
+
<body>
|
|
2876
|
+
<main>
|
|
2877
|
+
<header>
|
|
2878
|
+
<div>
|
|
2879
|
+
<h1>ChatterCatcher</h1>
|
|
2880
|
+
<p>\u672C\u5730\u4F18\u5148\u7684\u5BB6\u5EAD\u7FA4\u77E5\u8BC6\u5E93\u3002\u95EE\u7B54\u5FC5\u987B\u5148\u68C0\u7D22 RAG \u8BC1\u636E\uFF0C\u4E0D\u5806\u53E0\u5168\u91CF\u4E0A\u4E0B\u6587\u3002</p>
|
|
2881
|
+
</div>
|
|
2882
|
+
<div>
|
|
2883
|
+
<div class="actions">
|
|
2884
|
+
<button id="process-messages" type="button">\u7ACB\u5373\u5904\u7406</button>
|
|
2885
|
+
</div>
|
|
2886
|
+
<div id="action-status" class="status-line"></div>
|
|
2887
|
+
</div>
|
|
2888
|
+
</header>
|
|
2889
|
+
|
|
2890
|
+
<div class="grid" id="metrics"></div>
|
|
2891
|
+
|
|
2892
|
+
<div class="layout">
|
|
2893
|
+
<div>
|
|
2894
|
+
<section>
|
|
2895
|
+
<h2>\u6700\u8FD1\u6D88\u606F</h2>
|
|
2896
|
+
<div id="messages" class="empty">\u6B63\u5728\u8BFB\u53D6...</div>
|
|
2897
|
+
</section>
|
|
2898
|
+
</div>
|
|
2899
|
+
<aside>
|
|
2900
|
+
<section>
|
|
2901
|
+
<h2>\u7FA4\u804A</h2>
|
|
2902
|
+
<div id="chats" class="empty">\u6B63\u5728\u8BFB\u53D6...</div>
|
|
2903
|
+
</section>
|
|
2904
|
+
<section>
|
|
2905
|
+
<h2>\u6587\u4EF6\u5E93</h2>
|
|
2906
|
+
<div id="files" class="empty">\u6B63\u5728\u8BFB\u53D6...</div>
|
|
2907
|
+
</section>
|
|
2908
|
+
<section>
|
|
2909
|
+
<h2>\u89E3\u6790\u4EFB\u52A1</h2>
|
|
2910
|
+
<div id="file-jobs" class="empty">\u6B63\u5728\u8BFB\u53D6...</div>
|
|
2911
|
+
</section>
|
|
2912
|
+
<section>
|
|
2913
|
+
<h2>\u672C\u5730\u64CD\u4F5C</h2>
|
|
2914
|
+
<p><code>chattercatcher settings</code> \u4FEE\u6539\u914D\u7F6E\u3002</p>
|
|
2915
|
+
<p><code>chattercatcher files add <path...></code> \u5BFC\u5165\u6587\u672C\u3001DOCX \u6216 PDF \u6587\u4EF6\u3002</p>
|
|
2916
|
+
<p><code>chattercatcher doctor</code> \u68C0\u67E5\u98DE\u4E66\u3001\u6A21\u578B\u3001RAG \u548C\u672C\u5730\u5B58\u50A8\u3002</p>
|
|
2917
|
+
</section>
|
|
2918
|
+
</aside>
|
|
2919
|
+
</div>
|
|
2920
|
+
</main>
|
|
2921
|
+
<script>
|
|
2922
|
+
const metrics = document.querySelector("#metrics");
|
|
2923
|
+
const messages = document.querySelector("#messages");
|
|
2924
|
+
const chats = document.querySelector("#chats");
|
|
2925
|
+
const files = document.querySelector("#files");
|
|
2926
|
+
const fileJobs = document.querySelector("#file-jobs");
|
|
2927
|
+
const processMessages = document.querySelector("#process-messages");
|
|
2928
|
+
const actionStatus = document.querySelector("#action-status");
|
|
2929
|
+
|
|
2930
|
+
function fmt(value) {
|
|
2931
|
+
return value == null || value === "" ? "-" : String(value);
|
|
2932
|
+
}
|
|
2933
|
+
|
|
2934
|
+
function escapeHtml(value) {
|
|
2935
|
+
return fmt(value)
|
|
2936
|
+
.replaceAll("&", "&")
|
|
2937
|
+
.replaceAll("<", "<")
|
|
2938
|
+
.replaceAll(">", ">")
|
|
2939
|
+
.replaceAll('"', """);
|
|
2940
|
+
}
|
|
2941
|
+
|
|
2942
|
+
function isOpaqueId(value) {
|
|
2943
|
+
return /^(ou|oc|om|cli|on|un|uid)_?[a-z0-9]+/i.test(fmt(value));
|
|
2944
|
+
}
|
|
2945
|
+
|
|
2946
|
+
function formatDateTime(value) {
|
|
2947
|
+
const date = new Date(value);
|
|
2948
|
+
if (Number.isNaN(date.getTime())) return fmt(value);
|
|
2949
|
+
const pad = (input) => String(input).padStart(2, "0");
|
|
2950
|
+
return [
|
|
2951
|
+
date.getFullYear(),
|
|
2952
|
+
pad(date.getMonth() + 1),
|
|
2953
|
+
pad(date.getDate()),
|
|
2954
|
+
].join("/") + " " + [
|
|
2955
|
+
pad(date.getHours()),
|
|
2956
|
+
pad(date.getMinutes()),
|
|
2957
|
+
pad(date.getSeconds()),
|
|
2958
|
+
].join(":");
|
|
2959
|
+
}
|
|
2960
|
+
|
|
2961
|
+
function displaySender(value) {
|
|
2962
|
+
return isOpaqueId(value) ? "\u7FA4\u6210\u5458" : fmt(value);
|
|
2963
|
+
}
|
|
2964
|
+
|
|
2965
|
+
function displayChatName(value, platform) {
|
|
2966
|
+
if (!isOpaqueId(value)) return fmt(value);
|
|
2967
|
+
return platform === "feishu" ? "\u98DE\u4E66\u7FA4\u804A" : "\u7FA4\u804A";
|
|
2968
|
+
}
|
|
2969
|
+
|
|
2970
|
+
function formatGatewayValue(gateway) {
|
|
2971
|
+
if (gateway.connection === "running") return "\u8FD0\u884C\u4E2D";
|
|
2972
|
+
if (!gateway.configured) return "\u672A\u914D\u7F6E";
|
|
2973
|
+
return "\u5F85\u542F\u52A8";
|
|
2974
|
+
}
|
|
2975
|
+
|
|
2976
|
+
function formatGatewayNote(gateway) {
|
|
2977
|
+
if (gateway.connection === "running" && gateway.pid) return "PID " + gateway.pid;
|
|
2978
|
+
return "\u98DE\u4E66\u957F\u8FDE\u63A5";
|
|
2979
|
+
}
|
|
2980
|
+
|
|
2981
|
+
function renderMetrics(status) {
|
|
2982
|
+
const gatewayClass = status.gateway.configured ? "status-ok" : "status-warn";
|
|
2983
|
+
metrics.innerHTML = [
|
|
2984
|
+
["Gateway", formatGatewayValue(status.gateway), formatGatewayNote(status.gateway), gatewayClass],
|
|
2985
|
+
["\u7FA4\u804A", status.data.chats, "\u672C\u5730\u7FA4\u804A\u6570", ""],
|
|
2986
|
+
["\u6D88\u606F", status.data.messages, "\u5DF2\u5165\u5E93\u6D88\u606F", ""],
|
|
2987
|
+
["\u6587\u4EF6", status.data.files, "\u6587\u4EF6\u77E5\u8BC6\u6E90", ""],
|
|
2988
|
+
].map(([label, value, note, extra]) => \`
|
|
2989
|
+
<div class="metric">
|
|
2990
|
+
<div class="label">\${escapeHtml(label)}</div>
|
|
2991
|
+
<div class="value \${extra}">\${escapeHtml(value)}</div>
|
|
2992
|
+
<div class="note">\${escapeHtml(note)}</div>
|
|
2993
|
+
</div>
|
|
2994
|
+
\`).join("");
|
|
2995
|
+
}
|
|
2996
|
+
|
|
2997
|
+
function renderMessages(items) {
|
|
2998
|
+
if (items.length === 0) {
|
|
2999
|
+
messages.className = "empty";
|
|
3000
|
+
messages.textContent = "\u8FD8\u6CA1\u6709\u6D88\u606F\u3002\u542F\u52A8 Gateway \u540E\uFF0C\u7FA4\u804A\u6587\u672C\u4F1A\u8FDB\u5165\u672C\u5730 RAG \u7D22\u5F15\u3002";
|
|
3001
|
+
return;
|
|
3002
|
+
}
|
|
3003
|
+
messages.className = "";
|
|
3004
|
+
messages.innerHTML = \`
|
|
3005
|
+
<div class="message-list">
|
|
3006
|
+
\${items.map((item) => \`
|
|
3007
|
+
<article class="message-item">
|
|
3008
|
+
<div class="message-meta">
|
|
3009
|
+
<span>\${escapeHtml(formatDateTime(item.sentAt))}</span>
|
|
3010
|
+
<span>\${escapeHtml(displaySender(item.senderName))}</span>
|
|
3011
|
+
<span>\${escapeHtml(displayChatName(item.chatName, item.platform))}</span>
|
|
3012
|
+
</div>
|
|
3013
|
+
<div class="message-body">\${escapeHtml(item.text)}</div>
|
|
3014
|
+
</article>
|
|
3015
|
+
\`).join("")}
|
|
3016
|
+
</div>
|
|
3017
|
+
\`;
|
|
3018
|
+
}
|
|
3019
|
+
|
|
3020
|
+
function renderChats(items) {
|
|
3021
|
+
if (items.length === 0) {
|
|
3022
|
+
chats.className = "empty";
|
|
3023
|
+
chats.textContent = "\u8FD8\u6CA1\u6709\u7FA4\u804A\u8BB0\u5F55\u3002";
|
|
3024
|
+
return;
|
|
3025
|
+
}
|
|
3026
|
+
chats.className = "";
|
|
3027
|
+
chats.innerHTML = \`
|
|
3028
|
+
<table>
|
|
3029
|
+
<thead><tr><th>\u540D\u79F0</th><th>\u5E73\u53F0</th></tr></thead>
|
|
3030
|
+
<tbody>
|
|
3031
|
+
\${items.map((item) => \`
|
|
3032
|
+
<tr>
|
|
3033
|
+
<td><span class="id-text" title="\${escapeHtml(item.name)}">\${escapeHtml(displayChatName(item.name, item.platform))}</span></td>
|
|
3034
|
+
<td>\${escapeHtml(item.platform)}</td>
|
|
3035
|
+
</tr>
|
|
3036
|
+
\`).join("")}
|
|
3037
|
+
</tbody>
|
|
3038
|
+
</table>
|
|
3039
|
+
\`;
|
|
3040
|
+
}
|
|
3041
|
+
|
|
3042
|
+
function renderFiles(items) {
|
|
3043
|
+
if (items.length === 0) {
|
|
3044
|
+
files.className = "empty";
|
|
3045
|
+
files.textContent = "\u8FD8\u6CA1\u6709\u6587\u4EF6\u3002\u53EF\u5148\u8FD0\u884C chattercatcher files add <path...> \u5BFC\u5165\u6587\u672C\u3001DOCX \u6216 PDF \u6587\u4EF6\u3002";
|
|
3046
|
+
return;
|
|
3047
|
+
}
|
|
3048
|
+
files.className = "";
|
|
3049
|
+
files.innerHTML = \`
|
|
3050
|
+
<table>
|
|
3051
|
+
<thead><tr><th>\u6587\u4EF6</th><th>\u89E3\u6790\u5668</th><th>\u5B57\u7B26</th></tr></thead>
|
|
3052
|
+
<tbody>
|
|
3053
|
+
\${items.map((item) => \`
|
|
3054
|
+
<tr>
|
|
3055
|
+
<td>
|
|
3056
|
+
<div>\${escapeHtml(item.fileName)}</div>
|
|
3057
|
+
<div class="path" title="\${escapeHtml(item.storedPath)}">\${escapeHtml(item.storedPath)}</div>
|
|
3058
|
+
</td>
|
|
3059
|
+
<td>\${escapeHtml(item.parser || "unknown")}</td>
|
|
3060
|
+
<td>\${escapeHtml(item.characters)}</td>
|
|
3061
|
+
</tr>
|
|
3062
|
+
\`).join("")}
|
|
3063
|
+
</tbody>
|
|
3064
|
+
</table>
|
|
3065
|
+
\`;
|
|
3066
|
+
}
|
|
3067
|
+
|
|
3068
|
+
function renderFileJobs(items) {
|
|
3069
|
+
if (items.length === 0) {
|
|
3070
|
+
fileJobs.className = "empty";
|
|
3071
|
+
fileJobs.textContent = "\u8FD8\u6CA1\u6709\u6587\u4EF6\u89E3\u6790\u4EFB\u52A1\u3002";
|
|
3072
|
+
return;
|
|
3073
|
+
}
|
|
3074
|
+
fileJobs.className = "";
|
|
3075
|
+
fileJobs.innerHTML = \`
|
|
3076
|
+
<table>
|
|
3077
|
+
<thead><tr><th>\u4EFB\u52A1</th><th>\u72B6\u6001</th></tr></thead>
|
|
3078
|
+
<tbody>
|
|
3079
|
+
\${items.map((item) => \`
|
|
3080
|
+
<tr>
|
|
3081
|
+
<td>
|
|
3082
|
+
<div>\${escapeHtml(item.fileName)}</div>
|
|
3083
|
+
<div class="path" title="\${escapeHtml(item.id)}">ID: \${escapeHtml(item.id)}</div>
|
|
3084
|
+
<div class="path" title="\${escapeHtml(item.error || item.storedPath)}">\${escapeHtml(item.error || item.storedPath)}</div>
|
|
3085
|
+
</td>
|
|
3086
|
+
<td>\${escapeHtml(item.status)}</td>
|
|
3087
|
+
</tr>
|
|
3088
|
+
\`).join("")}
|
|
3089
|
+
</tbody>
|
|
3090
|
+
</table>
|
|
3091
|
+
\`;
|
|
3092
|
+
}
|
|
3093
|
+
|
|
3094
|
+
async function load() {
|
|
3095
|
+
const [status, recent, chatList, fileList, jobList] = await Promise.all([
|
|
3096
|
+
fetch("/api/status").then((response) => response.json()),
|
|
3097
|
+
fetch("/api/messages/recent?limit=20").then((response) => response.json()),
|
|
3098
|
+
fetch("/api/chats").then((response) => response.json()),
|
|
3099
|
+
fetch("/api/files").then((response) => response.json()),
|
|
3100
|
+
fetch("/api/file-jobs").then((response) => response.json()),
|
|
3101
|
+
]);
|
|
3102
|
+
renderMetrics(status);
|
|
3103
|
+
renderMessages(recent.items);
|
|
3104
|
+
renderChats(chatList.items);
|
|
3105
|
+
renderFiles(fileList.items);
|
|
3106
|
+
renderFileJobs(jobList.items);
|
|
3107
|
+
}
|
|
3108
|
+
|
|
3109
|
+
async function processNow() {
|
|
3110
|
+
processMessages.disabled = true;
|
|
3111
|
+
actionStatus.textContent = "\u6B63\u5728\u5904\u7406\u6D88\u606F\u7D22\u5F15...";
|
|
3112
|
+
try {
|
|
3113
|
+
const response = await fetch("/api/process/messages", { method: "POST" });
|
|
3114
|
+
const result = await response.json();
|
|
3115
|
+
if (!response.ok) {
|
|
3116
|
+
actionStatus.textContent = result.message || "\u5904\u7406\u5931\u8D25\u3002";
|
|
3117
|
+
return;
|
|
3118
|
+
}
|
|
3119
|
+
|
|
3120
|
+
if (result.status === "skipped") {
|
|
3121
|
+
actionStatus.textContent = result.reason;
|
|
3122
|
+
} else {
|
|
3123
|
+
actionStatus.textContent = \`\u5904\u7406\u5B8C\u6210\uFF1Achunks=\${result.chunks}, vectors=\${result.vectors}\`;
|
|
3124
|
+
}
|
|
3125
|
+
await load();
|
|
3126
|
+
} catch (error) {
|
|
3127
|
+
actionStatus.textContent = error instanceof Error ? error.message : String(error);
|
|
3128
|
+
} finally {
|
|
3129
|
+
processMessages.disabled = false;
|
|
3130
|
+
}
|
|
3131
|
+
}
|
|
3132
|
+
|
|
3133
|
+
processMessages.addEventListener("click", () => void processNow());
|
|
3134
|
+
void load();
|
|
3135
|
+
setInterval(() => {
|
|
3136
|
+
if (document.visibilityState === "visible") {
|
|
3137
|
+
void load();
|
|
3138
|
+
}
|
|
3139
|
+
}, 5000);
|
|
3140
|
+
</script>
|
|
3141
|
+
</body>
|
|
3142
|
+
</html>`;
|
|
3143
|
+
}
|
|
3144
|
+
function parseLimit(value, fallback, max) {
|
|
3145
|
+
const rawLimit = Number(value ?? fallback);
|
|
3146
|
+
return Number.isFinite(rawLimit) ? Math.min(Math.max(Math.trunc(rawLimit), 1), max) : fallback;
|
|
3147
|
+
}
|
|
3148
|
+
function createWebApp(config) {
|
|
3149
|
+
const app = Fastify({ logger: false });
|
|
3150
|
+
const database = openDatabase(config);
|
|
3151
|
+
const messages = new MessageRepository(database);
|
|
3152
|
+
const fileJobs = new FileJobRepository(database);
|
|
3153
|
+
app.addHook("onClose", async () => {
|
|
3154
|
+
database.close();
|
|
3155
|
+
});
|
|
3156
|
+
app.get("/api/status", async () => ({
|
|
3157
|
+
app: "ChatterCatcher",
|
|
3158
|
+
gateway: getGatewayStatus(config),
|
|
3159
|
+
data: {
|
|
3160
|
+
chats: messages.getChatCount(),
|
|
3161
|
+
messages: messages.getMessageCount(),
|
|
3162
|
+
files: messages.listFiles(1e3).length
|
|
3163
|
+
},
|
|
3164
|
+
rag: {
|
|
3165
|
+
mode: "required",
|
|
3166
|
+
note: "\u95EE\u7B54\u5FC5\u987B\u5148\u68C0\u7D22\u8BC1\u636E\uFF0C\u7981\u6B62\u5168\u91CF\u4E0A\u4E0B\u6587\u5806\u53E0\u3002",
|
|
3167
|
+
retrieval: {
|
|
3168
|
+
keyword: "SQLite FTS5",
|
|
3169
|
+
vector: "SQLite Vector",
|
|
3170
|
+
hybrid: true
|
|
3171
|
+
}
|
|
3172
|
+
},
|
|
3173
|
+
web: config.web
|
|
3174
|
+
}));
|
|
3175
|
+
app.get("/api/chats", async () => ({
|
|
3176
|
+
items: messages.listChats()
|
|
3177
|
+
}));
|
|
3178
|
+
app.get("/api/files", async (request) => {
|
|
3179
|
+
const limit = parseLimit(request.query.limit, 50, 200);
|
|
3180
|
+
return {
|
|
3181
|
+
items: messages.listFiles(limit)
|
|
3182
|
+
};
|
|
3183
|
+
});
|
|
3184
|
+
app.get("/api/file-jobs", async (request) => {
|
|
3185
|
+
const limit = parseLimit(request.query.limit, 50, 200);
|
|
3186
|
+
const status = request.query.status;
|
|
3187
|
+
return {
|
|
3188
|
+
items: fileJobs.list(limit, status === "processing" || status === "indexed" || status === "failed" ? { status } : {})
|
|
3189
|
+
};
|
|
3190
|
+
});
|
|
3191
|
+
app.get("/api/messages/recent", async (request) => {
|
|
3192
|
+
const limit = parseLimit(request.query.limit, 20, 100);
|
|
3193
|
+
return {
|
|
3194
|
+
items: messages.listRecentMessages(limit)
|
|
3195
|
+
};
|
|
3196
|
+
});
|
|
3197
|
+
app.post("/api/process/messages", async (_request, reply) => {
|
|
3198
|
+
try {
|
|
3199
|
+
return await processMessagesNow({
|
|
3200
|
+
config,
|
|
3201
|
+
secrets: await loadSecrets(),
|
|
3202
|
+
database,
|
|
3203
|
+
limit: 1e4
|
|
3204
|
+
});
|
|
3205
|
+
} catch (error) {
|
|
3206
|
+
reply.code(500);
|
|
3207
|
+
return {
|
|
3208
|
+
status: "failed",
|
|
3209
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3210
|
+
};
|
|
3211
|
+
}
|
|
3212
|
+
});
|
|
3213
|
+
app.get("/", async (_request, reply) => {
|
|
3214
|
+
reply.type("text/html; charset=utf-8");
|
|
3215
|
+
return buildHtml();
|
|
3216
|
+
});
|
|
3217
|
+
return app;
|
|
3218
|
+
}
|
|
3219
|
+
async function startWebServer(config) {
|
|
3220
|
+
const app = createWebApp(config);
|
|
3221
|
+
await app.listen({ host: config.web.host, port: config.web.port });
|
|
3222
|
+
const address = app.server.address();
|
|
3223
|
+
const url = typeof address === "string" ? address : `http://${config.web.host}:${address?.port ?? config.web.port}`;
|
|
3224
|
+
console.log(`ChatterCatcher Web UI: ${url}`);
|
|
3225
|
+
}
|
|
3226
|
+
|
|
125
3227
|
// src/cli.ts
|
|
126
3228
|
var program = new Command();
|
|
127
3229
|
async function promptForConfiguration(config, secrets) {
|
|
@@ -184,7 +3286,7 @@ function printSettings(config, secrets) {
|
|
|
184
3286
|
2
|
|
185
3287
|
));
|
|
186
3288
|
}
|
|
187
|
-
program.name("chattercatcher").description("\u672C\u5730\u4F18\u5148\u7684\u98DE\u4E66/Lark \u5BB6\u5EAD\u7FA4\u77E5\u8BC6\u673A\u5668\u4EBA").version(
|
|
3289
|
+
program.name("chattercatcher").description("\u672C\u5730\u4F18\u5148\u7684\u98DE\u4E66/Lark \u5BB6\u5EAD\u7FA4\u77E5\u8BC6\u673A\u5668\u4EBA").version("0.1.6");
|
|
188
3290
|
program.command("setup").description("\u4EA4\u4E92\u5F0F\u521D\u59CB\u5316\u914D\u7F6E").action(async () => {
|
|
189
3291
|
const { config, secrets } = await ensureConfigFiles();
|
|
190
3292
|
await promptForConfiguration(config, secrets);
|
|
@@ -232,8 +3334,7 @@ async function startGatewayCommand() {
|
|
|
232
3334
|
return;
|
|
233
3335
|
}
|
|
234
3336
|
const database = openDatabase(config);
|
|
235
|
-
const
|
|
236
|
-
const vectorStore = LanceDbVectorStore ? await LanceDbVectorStore.connectFromConfig(config) : null;
|
|
3337
|
+
const vectorStore = hasEmbeddingConfig(config, secrets) ? new SQLiteVectorStore(database) : null;
|
|
237
3338
|
const gatewayRuntime = createFeishuGateway({
|
|
238
3339
|
config,
|
|
239
3340
|
secrets,
|
|
@@ -318,7 +3419,7 @@ async function deleteDataCommand(targetType, targetId, options) {
|
|
|
318
3419
|
if (result.skippedStoredFiles.length > 0) {
|
|
319
3420
|
console.log(`\u8DF3\u8FC7\u975E\u6570\u636E\u76EE\u5F55\u6587\u4EF6\uFF1A${result.skippedStoredFiles.join("\uFF1B")}`);
|
|
320
3421
|
}
|
|
321
|
-
console.log("SQLite FTS \u5DF2\u540C\u6B65\u5220\u9664\uFF1B\u5982\u4F7F\u7528
|
|
3422
|
+
console.log("SQLite FTS \u5DF2\u540C\u6B65\u5220\u9664\uFF1B\u5982\u4F7F\u7528\u8BED\u4E49\u68C0\u7D22\uFF0C\u8BF7\u8FD0\u884C chattercatcher index rebuild \u91CD\u5EFA SQLite Vector\u3002");
|
|
322
3423
|
} finally {
|
|
323
3424
|
database.close();
|
|
324
3425
|
}
|
|
@@ -333,20 +3434,19 @@ index.command("status").description("\u67E5\u770B\u7D22\u5F15\u72B6\u6001").acti
|
|
|
333
3434
|
const secrets = await loadSecrets();
|
|
334
3435
|
const database = openDatabase(config);
|
|
335
3436
|
const messages = new MessageRepository(database);
|
|
336
|
-
const
|
|
337
|
-
const vectorStore = await LanceDbVectorStore.connectFromConfig(config);
|
|
3437
|
+
const vectorStore = new SQLiteVectorStore(database);
|
|
338
3438
|
const vectors = await vectorStore.count();
|
|
339
3439
|
console.log(JSON.stringify(
|
|
340
3440
|
{
|
|
341
3441
|
database: getDatabasePath(config),
|
|
342
|
-
vectorDatabase:
|
|
3442
|
+
vectorDatabase: getDatabasePath(config),
|
|
343
3443
|
chats: messages.getChatCount(),
|
|
344
3444
|
messages: messages.getMessageCount(),
|
|
345
3445
|
vectors,
|
|
346
3446
|
retrieval: {
|
|
347
3447
|
keyword: "SQLite FTS5",
|
|
348
|
-
vector: hasEmbeddingConfig(config, secrets) ? "
|
|
349
|
-
hybrid: "\u542F\u7528\uFF1ASQLite FTS +
|
|
3448
|
+
vector: hasEmbeddingConfig(config, secrets) ? "SQLite Vector \u5DF2\u53EF\u7528\u4E8E\u8BED\u4E49\u68C0\u7D22" : "SQLite Vector \u5DF2\u63A5\u5165\uFF1B\u9700\u914D\u7F6E embedding \u540E\u542F\u7528\u8BED\u4E49\u68C0\u7D22",
|
|
3449
|
+
hybrid: "\u542F\u7528\uFF1ASQLite FTS + SQLite Vector",
|
|
350
3450
|
rag: "\u5F3A\u5236\u5148\u68C0\u7D22\u8BC1\u636E\u518D\u56DE\u7B54\uFF0C\u7981\u6B62\u5168\u91CF\u4E0A\u4E0B\u6587\u5806\u53E0"
|
|
351
3451
|
}
|
|
352
3452
|
},
|
|
@@ -356,7 +3456,7 @@ index.command("status").description("\u67E5\u770B\u7D22\u5F15\u72B6\u6001").acti
|
|
|
356
3456
|
vectorStore.close();
|
|
357
3457
|
database.close();
|
|
358
3458
|
});
|
|
359
|
-
index.command("rebuild").description("\u91CD\u5EFA
|
|
3459
|
+
index.command("rebuild").description("\u91CD\u5EFA SQLite \u5411\u91CF\u7D22\u5F15").option("--limit <number>", "\u6700\u591A\u7D22\u5F15\u7684 chunk \u6570", "10000").action(async (options) => {
|
|
360
3460
|
const config = await loadConfig();
|
|
361
3461
|
const secrets = await loadSecrets();
|
|
362
3462
|
if (!hasEmbeddingConfig(config, secrets)) {
|
|
@@ -364,8 +3464,7 @@ index.command("rebuild").description("\u91CD\u5EFA LanceDB \u5411\u91CF\u7D22\u5
|
|
|
364
3464
|
return;
|
|
365
3465
|
}
|
|
366
3466
|
const database = openDatabase(config);
|
|
367
|
-
const
|
|
368
|
-
const vectorStore = await LanceDbVectorStore.connectFromConfig(config);
|
|
3467
|
+
const vectorStore = new SQLiteVectorStore(database);
|
|
369
3468
|
try {
|
|
370
3469
|
const stats = await indexMessageChunks({
|
|
371
3470
|
messages: new MessageRepository(database),
|
|
@@ -380,7 +3479,7 @@ index.command("rebuild").description("\u91CD\u5EFA LanceDB \u5411\u91CF\u7D22\u5
|
|
|
380
3479
|
}
|
|
381
3480
|
});
|
|
382
3481
|
var processCommand = program.command("process").description("\u7ACB\u5373\u5904\u7406\u540E\u53F0\u4EFB\u52A1");
|
|
383
|
-
processCommand.command("messages").description("\u7ACB\u5373\u5904\u7406\u6D88\u606F\u7D22\u5F15\u4EFB\u52A1\uFF0C\u628A\u6D88\u606F chunks \u5199\u5165
|
|
3482
|
+
processCommand.command("messages").description("\u7ACB\u5373\u5904\u7406\u6D88\u606F\u7D22\u5F15\u4EFB\u52A1\uFF0C\u628A\u6D88\u606F chunks \u5199\u5165 SQLite \u5411\u91CF\u7D22\u5F15").option("--limit <number>", "\u6700\u591A\u5904\u7406\u7684 chunk \u6570", "10000").action(async (options) => {
|
|
384
3483
|
const config = await loadConfig();
|
|
385
3484
|
const secrets = await loadSecrets();
|
|
386
3485
|
const database = openDatabase(config);
|
|
@@ -414,7 +3513,7 @@ files.command("add").description("\u628A\u672C\u5730\u6587\u4EF6\u89E3\u6790\u30
|
|
|
414
3513
|
`\u5DF2\u5BFC\u5165\u6587\u4EF6\uFF1A${result.fileName}\uFF0C\u89E3\u6790\u5668=${result.parser}\uFF0C\u5B57\u7B26\u6570=${result.characters}\uFF0C\u6D88\u606FID=${result.messageId}`
|
|
415
3514
|
);
|
|
416
3515
|
}
|
|
417
|
-
console.log("\u6587\u4EF6\u5DF2\u8FDB\u5165 SQLite FTS \u68C0\u7D22\uFF1B\u5982\u5DF2\u914D\u7F6E embedding\uFF0C\u53EF\u8FD0\u884C chattercatcher index rebuild \u66F4\u65B0
|
|
3516
|
+
console.log("\u6587\u4EF6\u5DF2\u8FDB\u5165 SQLite FTS \u68C0\u7D22\uFF1B\u5982\u5DF2\u914D\u7F6E embedding\uFF0C\u53EF\u8FD0\u884C chattercatcher index rebuild \u66F4\u65B0 SQLite \u5411\u91CF\u7D22\u5F15\u3002");
|
|
418
3517
|
} finally {
|
|
419
3518
|
database.close();
|
|
420
3519
|
}
|
|
@@ -543,7 +3642,7 @@ program.command("restore").description("\u4ECE ChatterCatcher \u5BFC\u51FA\u6587
|
|
|
543
3642
|
console.log(`\u6062\u590D\u5B8C\u6210\uFF1A${result.inputPath}`);
|
|
544
3643
|
console.log(`\u6A21\u5F0F\uFF1A${result.mode === "replace" ? "\u66FF\u6362" : "\u5408\u5E76"}`);
|
|
545
3644
|
console.log(`\u5305\u542B\uFF1A\u7FA4\u804A=${result.chats}\uFF0C\u6D88\u606F=${result.messages}\uFF0Cchunks=${result.chunks}\uFF0C\u6587\u4EF6\u4EFB\u52A1=${result.fileJobs}`);
|
|
546
|
-
console.log("SQLite FTS \u5DF2\u91CD\u5EFA\uFF1B\u5982\u4F7F\u7528
|
|
3645
|
+
console.log("SQLite FTS \u5DF2\u91CD\u5EFA\uFF1B\u5982\u4F7F\u7528\u8BED\u4E49\u68C0\u7D22\uFF0C\u8BF7\u8FD0\u884C chattercatcher index rebuild \u91CD\u5EFA SQLite Vector\u3002");
|
|
547
3646
|
} finally {
|
|
548
3647
|
database.close();
|
|
549
3648
|
}
|
|
@@ -573,7 +3672,7 @@ dev.command("ingest-feishu-event").description("\u4ECE JSON \u6587\u4EF6\u6A21\u
|
|
|
573
3672
|
const config = await loadConfig();
|
|
574
3673
|
const database = openDatabase(config);
|
|
575
3674
|
try {
|
|
576
|
-
const raw = await
|
|
3675
|
+
const raw = await fs12.readFile(options.file, "utf8");
|
|
577
3676
|
const payload = JSON.parse(raw);
|
|
578
3677
|
const result = new GatewayIngestor(database).ingestFeishuEvent(payload);
|
|
579
3678
|
if (!result.accepted) {
|