chattercatcher 0.1.5 → 0.1.7

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