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