chattercatcher 0.1.0

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