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