chattercatcher 0.1.2 → 0.1.5

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