chattercatcher 0.1.0

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