chattercatcher 0.1.5 → 0.1.7

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