luckytri 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/SECURITY.md +71 -0
- package/LICENSE +21 -0
- package/README.en.md +250 -0
- package/README.md +250 -0
- package/bin/luckytri.js +107 -0
- package/docs/brand/banner.png +0 -0
- package/docs/brand/palette.png +0 -0
- package/docs/brand/portrait.png +0 -0
- package/docs/en/CHANGELOG.md +113 -0
- package/docs/en/architecture.md +152 -0
- package/docs/en/chat-style.md +62 -0
- package/docs/en/connect.md +63 -0
- package/docs/en/guide.md +216 -0
- package/docs/en/her-life.md +189 -0
- package/docs/en/npm-release.md +25 -0
- package/docs/en/plugins.md +82 -0
- package/docs/en/recovery.md +28 -0
- package/docs/en/time.md +71 -0
- package/docs/en/webui.md +73 -0
- package/docs/zh/CHANGELOG.md +113 -0
- package/docs/zh/architecture.md +152 -0
- package/docs/zh/chat-style.md +62 -0
- package/docs/zh/connect.md +63 -0
- package/docs/zh/guide.md +216 -0
- package/docs/zh/her-life.md +189 -0
- package/docs/zh/npm-release.md +33 -0
- package/docs/zh/plugins.md +82 -0
- package/docs/zh/recovery.md +28 -0
- package/docs/zh/time.md +71 -0
- package/docs/zh/webui.md +73 -0
- package/package.json +108 -0
- package/plugins/sdk/index.d.ts +155 -0
- package/plugins/sdk/testing.js +58 -0
- package/plugins/weather/index.js +82 -0
- package/plugins/weather/luckytri-plugin.json +29 -0
- package/public/app/assets/ChatsPage-C-FcRapR.js +3 -0
- package/public/app/assets/ChatsPage-DfyPCS9N.css +1 -0
- package/public/app/assets/Empty-CpP5kQHH.js +2 -0
- package/public/app/assets/Empty-DmUB2-Bk.css +1 -0
- package/public/app/assets/Field-D4gY-INU.js +1 -0
- package/public/app/assets/HeartPage-Bft9wZp5.css +1 -0
- package/public/app/assets/HeartPage-CPy_thQd.js +1 -0
- package/public/app/assets/LifePage-BUi5euBF.css +1 -0
- package/public/app/assets/LifePage-CxWvwmSf.js +1 -0
- package/public/app/assets/MemoryPage-DC4rhQ68.js +1 -0
- package/public/app/assets/MemoryPage-cZvXfkXb.css +1 -0
- package/public/app/assets/NaturePage-CTXHCE2D.css +1 -0
- package/public/app/assets/NaturePage-IvYw04Zq.js +3 -0
- package/public/app/assets/PeoplePage-BmUxkrOU.css +1 -0
- package/public/app/assets/PeoplePage-Cqefm9-q.js +1 -0
- package/public/app/assets/PluginsPage-DKSaKvXb.js +2 -0
- package/public/app/assets/PluginsPage-HyBe5D8w.css +1 -0
- package/public/app/assets/SystemPage-CAMPoYqM.css +1 -0
- package/public/app/assets/SystemPage-CJmtJkrK.js +1 -0
- package/public/app/assets/TimePage-BOms_n4I.css +1 -0
- package/public/app/assets/TimePage-Cw44inM4.js +3 -0
- package/public/app/assets/formatters-ZmW_xFHw.js +1 -0
- package/public/app/assets/index-BheRW-1t.js +4 -0
- package/public/app/assets/index-YDz1ree1.css +1 -0
- package/public/app/assets/knowledge-DG0e0uKw.js +1 -0
- package/public/app/assets/liquid-garden-IMoHBwzc.png +0 -0
- package/public/app/assets/luckytri-home-95QKeMtc.png +0 -0
- package/public/app/assets/media-BzPDBm7e.js +1 -0
- package/public/app/index.html +27 -0
- package/public/guide.en.html +1053 -0
- package/public/guide.html +893 -0
- package/public/plugin-kit/v1/bridge.js +30 -0
- package/public/plugin-kit/v1/kit.css +14 -0
- package/public/tutorial.en.md +214 -0
- package/public/tutorial.md +214 -0
- package/scripts/backup.js +311 -0
- package/scripts/browser.js +41 -0
- package/scripts/launch.js +94 -0
- package/scripts/plugin.js +150 -0
- package/scripts/proxy-config.js +167 -0
- package/scripts/recover.js +26 -0
- package/scripts/runtime.js +25 -0
- package/scripts/service.js +47 -0
- package/scripts/setup.js +50 -0
- package/scripts/start-server.js +41 -0
- package/scripts/stop.js +36 -0
- package/server/app.js +96 -0
- package/server/channels/adapters.js +27 -0
- package/server/channels/contract.js +57 -0
- package/server/channels/hub.js +165 -0
- package/server/channels/index.js +25 -0
- package/server/channels/onebot/adapter.js +288 -0
- package/server/channels/onebot/index.js +336 -0
- package/server/channels/onebot/token.js +3 -0
- package/server/channels/qqbot/adapter.js +253 -0
- package/server/channels/qqbot/api.js +199 -0
- package/server/channels/qqbot/credentials.js +11 -0
- package/server/channels/qqbot/gateway.js +274 -0
- package/server/channels/qqbot/index.js +389 -0
- package/server/channels/segments.js +40 -0
- package/server/channels/session-key.js +153 -0
- package/server/channels/state.js +42 -0
- package/server/core/api.js +564 -0
- package/server/core/capabilities.js +208 -0
- package/server/core/context-builder.js +288 -0
- package/server/core/context-compactor.js +454 -0
- package/server/core/conversation-cues.js +325 -0
- package/server/core/conversation-manager.js +87 -0
- package/server/core/events.js +60 -0
- package/server/core/feedback.js +8 -0
- package/server/core/group-style.js +72 -0
- package/server/core/image-preprocessor.js +208 -0
- package/server/core/initiative-context.js +66 -0
- package/server/core/input-budget.js +32 -0
- package/server/core/local-demo.js +98 -0
- package/server/core/message-manager.js +118 -0
- package/server/core/message-scheduler.js +78 -0
- package/server/core/model-json.js +190 -0
- package/server/core/model-manager.js +1213 -0
- package/server/core/model-presets.js +900 -0
- package/server/core/name-call.js +29 -0
- package/server/core/net-guard.js +49 -0
- package/server/core/network.js +157 -0
- package/server/core/orchestrator.js +569 -0
- package/server/core/perceivers.js +91 -0
- package/server/core/person-name.js +22 -0
- package/server/core/persona-manager.js +243 -0
- package/server/core/reply-delivery.js +393 -0
- package/server/core/reply-target-resolver.js +50 -0
- package/server/core/repository.js +293 -0
- package/server/core/response-generator.js +50 -0
- package/server/core/response-validator.js +508 -0
- package/server/core/retired-prompts.js +51 -0
- package/server/core/sessions.js +109 -0
- package/server/core/speaker-names.js +92 -0
- package/server/core/topic-tracker.js +65 -0
- package/server/core/turn-processor.js +630 -0
- package/server/core/turn.js +236 -0
- package/server/core/vision-manager.js +633 -0
- package/server/http.js +18 -0
- package/server/i18n/decisions.js +206 -0
- package/server/i18n/errors.js +497 -0
- package/server/i18n/index.js +144 -0
- package/server/i18n/labels.js +653 -0
- package/server/i18n/models.js +111 -0
- package/server/index.js +102 -0
- package/server/knowledge/api.js +342 -0
- package/server/knowledge/embedding-profile.js +114 -0
- package/server/knowledge/index.js +13 -0
- package/server/knowledge/manager.js +386 -0
- package/server/knowledge/retrieval.js +93 -0
- package/server/knowledge/schema.js +154 -0
- package/server/knowledge/vector-index.js +90 -0
- package/server/mind/affect.js +265 -0
- package/server/mind/anticipations.js +507 -0
- package/server/mind/api.js +703 -0
- package/server/mind/attention.js +200 -0
- package/server/mind/bonds.js +558 -0
- package/server/mind/budget.js +152 -0
- package/server/mind/clock.js +83 -0
- package/server/mind/context-selection.js +61 -0
- package/server/mind/continuity.js +562 -0
- package/server/mind/conversation-origin.js +175 -0
- package/server/mind/day-planner.js +324 -0
- package/server/mind/days.js +210 -0
- package/server/mind/evidence-read.js +45 -0
- package/server/mind/evidence.js +148 -0
- package/server/mind/faces.js +138 -0
- package/server/mind/guard.js +60 -0
- package/server/mind/index.js +445 -0
- package/server/mind/initiative.js +333 -0
- package/server/mind/life/activities.js +21 -0
- package/server/mind/life/context.js +309 -0
- package/server/mind/life/diary.js +786 -0
- package/server/mind/life/growth.js +252 -0
- package/server/mind/life/index.js +1049 -0
- package/server/mind/life/presence.js +305 -0
- package/server/mind/meetings.js +1069 -0
- package/server/mind/memory-policy.js +48 -0
- package/server/mind/memory.js +888 -0
- package/server/mind/nature.js +262 -0
- package/server/mind/novelty.js +19 -0
- package/server/mind/observations.js +84 -0
- package/server/mind/own-day.js +324 -0
- package/server/mind/own-voice.js +318 -0
- package/server/mind/periods.js +118 -0
- package/server/mind/reading.js +120 -0
- package/server/mind/salience.js +201 -0
- package/server/mind/schema.js +562 -0
- package/server/mind/self.js +484 -0
- package/server/mind/senses.js +53 -0
- package/server/mind/thoughts.js +274 -0
- package/server/mind/time/activity-clock.js +196 -0
- package/server/mind/time/agenda.js +242 -0
- package/server/mind/time/api.js +200 -0
- package/server/mind/time/attention.js +34 -0
- package/server/mind/time/availability.js +69 -0
- package/server/mind/time/commitment-review.js +198 -0
- package/server/mind/time/delivery-links.js +130 -0
- package/server/mind/time/executor.js +512 -0
- package/server/mind/time/experiences.js +128 -0
- package/server/mind/time/games.js +562 -0
- package/server/mind/time/index.js +739 -0
- package/server/mind/time/intent.js +166 -0
- package/server/mind/time/kinds.js +171 -0
- package/server/mind/time/model-material.js +77 -0
- package/server/mind/time/plugin-activity.js +207 -0
- package/server/mind/time/presentation.js +51 -0
- package/server/mind/time/schedule.js +83 -0
- package/server/mind/time/schema.js +84 -0
- package/server/mind/time/search.js +383 -0
- package/server/mind/time/sharing.js +472 -0
- package/server/mind/time/task-links.js +311 -0
- package/server/mind/time/tasks.js +587 -0
- package/server/mind/time/works.js +432 -0
- package/server/mind/traits.js +191 -0
- package/server/mind/util.js +110 -0
- package/server/mind/view.js +273 -0
- package/server/paths.js +102 -0
- package/server/plugins/api.js +204 -0
- package/server/plugins/host.js +967 -0
- package/server/plugins/install.js +295 -0
- package/server/plugins/manifest.js +201 -0
- package/server/plugins/permissions.js +42 -0
- package/server/plugins/runner/guard.mjs +36 -0
- package/server/plugins/runner/worker.mjs +250 -0
- package/server/plugins/schema.js +91 -0
- package/server/plugins/zip.js +112 -0
- package/server/startup-lock.js +118 -0
- package/server/storage/archive.js +241 -0
- package/server/storage/backup-cleanup-worker.js +8 -0
- package/server/storage/backup-cleanup.js +414 -0
- package/server/storage/backup-lock.js +76 -0
- package/server/storage/backup-scheduler.js +131 -0
- package/server/storage/store.js +199 -0
- package/server/studio/display-names.js +138 -0
- package/server/studio/management.js +102 -0
- package/server/studio/readiness.js +190 -0
- package/server/studio/settings.js +236 -0
- package/server/version.js +10 -0
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { runtimePaths } from "../paths.js";
|
|
5
|
+
import {
|
|
6
|
+
asPlainDocument,
|
|
7
|
+
chunkText,
|
|
8
|
+
cosine,
|
|
9
|
+
ftsMatchQuery,
|
|
10
|
+
overlapScore,
|
|
11
|
+
lexicalTerms,
|
|
12
|
+
packVector,
|
|
13
|
+
unpackVector,
|
|
14
|
+
} from "./retrieval.js";
|
|
15
|
+
import { indexChunk } from "./schema.js";
|
|
16
|
+
import { ensureVectorIndex, vectorCandidates } from "./vector-index.js";
|
|
17
|
+
import { resolveEmbeddingProfile, embedBatches } from "./embedding-profile.js";
|
|
18
|
+
import {
|
|
19
|
+
parseSessionKey,
|
|
20
|
+
scopedSessionAliases,
|
|
21
|
+
} from "../channels/session-key.js";
|
|
22
|
+
|
|
23
|
+
function scopesFor(db, session) {
|
|
24
|
+
try {
|
|
25
|
+
const parsed = parseSessionKey(session);
|
|
26
|
+
const aliases = scopedSessionAliases(db, session);
|
|
27
|
+
return {
|
|
28
|
+
aliases,
|
|
29
|
+
kind: parsed.kind,
|
|
30
|
+
privateKey: `__private__:${parsed.nativeId}`,
|
|
31
|
+
};
|
|
32
|
+
} catch {
|
|
33
|
+
return { aliases: [session], kind: "group", privateKey: "" };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function saidBy(rows) {
|
|
38
|
+
const groups = new Map();
|
|
39
|
+
let anon = 0;
|
|
40
|
+
for (const row of rows || []) {
|
|
41
|
+
if (row?.role === "assistant") continue;
|
|
42
|
+
const id = String(row?.userId || "");
|
|
43
|
+
const key = id || `\0${anon++}`;
|
|
44
|
+
const texts = groups.get(key) || [];
|
|
45
|
+
if (row?.text) texts.push(String(row.text));
|
|
46
|
+
groups.set(key, texts);
|
|
47
|
+
}
|
|
48
|
+
return [...groups.values()]
|
|
49
|
+
.map((texts) => texts.join(" "))
|
|
50
|
+
.filter((text) => text.trim());
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function allowedCollection(db, collection, session) {
|
|
54
|
+
if (!session) return true;
|
|
55
|
+
const { aliases, kind, privateKey } = scopesFor(db, session);
|
|
56
|
+
if (collection.scope === "shared") return true;
|
|
57
|
+
if (privateKey && collection.scope === privateKey) return true;
|
|
58
|
+
if (aliases.includes(collection.scope)) return true;
|
|
59
|
+
if (String(collection.scope).startsWith("__private__") && kind !== "private")
|
|
60
|
+
return false;
|
|
61
|
+
if (!aliases.length) return false;
|
|
62
|
+
return !!db
|
|
63
|
+
.prepare(
|
|
64
|
+
`SELECT 1 FROM core_collection_sessions WHERE collection_id=? AND session_id IN (${aliases.map(() => "?").join(",")})`,
|
|
65
|
+
)
|
|
66
|
+
.get(collection.id, ...aliases);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class KnowledgeManager {
|
|
70
|
+
constructor(repo, models) {
|
|
71
|
+
this.repo = repo;
|
|
72
|
+
this.models = models;
|
|
73
|
+
}
|
|
74
|
+
collections(session = "") {
|
|
75
|
+
return this.repo.db
|
|
76
|
+
.prepare("SELECT * FROM core_collections ORDER BY updated DESC")
|
|
77
|
+
.all()
|
|
78
|
+
.filter((c) => allowedCollection(this.repo.db, c, session));
|
|
79
|
+
}
|
|
80
|
+
createCollection({ name, scope = "shared", sessions = [] }) {
|
|
81
|
+
if (typeof name !== "string" || !name.trim() || name.length > 100)
|
|
82
|
+
throw Error("知识库名称无效");
|
|
83
|
+
const id = randomUUID(),
|
|
84
|
+
now = Date.now();
|
|
85
|
+
this.repo.db
|
|
86
|
+
.prepare(
|
|
87
|
+
"INSERT INTO core_collections(id,name,scope,created,updated) VALUES (?,?,?,?,?)",
|
|
88
|
+
)
|
|
89
|
+
.run(id, name.trim(), scope || "shared", now, now);
|
|
90
|
+
for (const session of sessions)
|
|
91
|
+
this.repo.db
|
|
92
|
+
.prepare("INSERT OR IGNORE INTO core_collection_sessions VALUES (?,?)")
|
|
93
|
+
.run(id, session);
|
|
94
|
+
this.repo.store.revision++;
|
|
95
|
+
return this.repo.db
|
|
96
|
+
.prepare("SELECT * FROM core_collections WHERE id=?")
|
|
97
|
+
.get(id);
|
|
98
|
+
}
|
|
99
|
+
documents(collectionId) {
|
|
100
|
+
return this.repo.db
|
|
101
|
+
.prepare(
|
|
102
|
+
"SELECT * FROM core_documents WHERE collection_id=? ORDER BY updated DESC",
|
|
103
|
+
)
|
|
104
|
+
.all(collectionId);
|
|
105
|
+
}
|
|
106
|
+
async ingest({ collectionId, title, text, source = "paste", embed = true }) {
|
|
107
|
+
const collection = this.repo.db
|
|
108
|
+
.prepare("SELECT * FROM core_collections WHERE id=?")
|
|
109
|
+
.get(collectionId);
|
|
110
|
+
if (!collection) throw Error("知识库不存在");
|
|
111
|
+
if (typeof text !== "string" || !text.trim() || text.length > 400000)
|
|
112
|
+
throw Error("文档内容应为 1–400000 字");
|
|
113
|
+
const safeTitle = String(title || "未命名文档").slice(0, 200);
|
|
114
|
+
const plain = asPlainDocument(text);
|
|
115
|
+
const chunks = chunkText(plain);
|
|
116
|
+
if (!chunks.length) throw Error("文档切分后为空");
|
|
117
|
+
const id = randomUUID(),
|
|
118
|
+
now = Date.now(),
|
|
119
|
+
hash = createHash("sha256").update(text).digest("hex");
|
|
120
|
+
mkdirSync(runtimePaths().knowledge, { recursive: true, mode: 0o700 });
|
|
121
|
+
const path = join(runtimePaths().knowledge, id + ".md");
|
|
122
|
+
writeFileSync(path, text);
|
|
123
|
+
this.repo.db
|
|
124
|
+
.prepare(
|
|
125
|
+
"INSERT INTO core_documents(id,collection_id,title,source,path,status,created,updated,bytes,hash) VALUES (?,?,?,?,?,'processing',?,?,?,?)",
|
|
126
|
+
)
|
|
127
|
+
.run(
|
|
128
|
+
id,
|
|
129
|
+
collectionId,
|
|
130
|
+
safeTitle,
|
|
131
|
+
source,
|
|
132
|
+
path,
|
|
133
|
+
now,
|
|
134
|
+
now,
|
|
135
|
+
Buffer.byteLength(text),
|
|
136
|
+
hash,
|
|
137
|
+
);
|
|
138
|
+
let vectors = [];
|
|
139
|
+
let embeddingProfile = "";
|
|
140
|
+
try {
|
|
141
|
+
if (embed) {
|
|
142
|
+
const resolved = resolveEmbeddingProfile(this.repo, this.models);
|
|
143
|
+
vectors = await embedBatches(
|
|
144
|
+
this.models,
|
|
145
|
+
resolved.profile,
|
|
146
|
+
chunks.map((c) => c.text),
|
|
147
|
+
);
|
|
148
|
+
if (vectors.length) embeddingProfile = resolved.signature;
|
|
149
|
+
}
|
|
150
|
+
} catch (error) {
|
|
151
|
+
this.repo.db
|
|
152
|
+
.prepare(
|
|
153
|
+
"UPDATE core_documents SET status='failed',error=?,updated=? WHERE id=?",
|
|
154
|
+
)
|
|
155
|
+
.run(error.message, Date.now(), id);
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
this.repo.db.exec("BEGIN IMMEDIATE");
|
|
159
|
+
try {
|
|
160
|
+
chunks.forEach((chunk, i) => {
|
|
161
|
+
const chunkId = randomUUID();
|
|
162
|
+
this.repo.db
|
|
163
|
+
.prepare(
|
|
164
|
+
"INSERT INTO core_chunks(id,document_id,collection_id,ordinal,heading,text,tokens,embedding,hash,created,embedding_profile) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
|
165
|
+
)
|
|
166
|
+
.run(
|
|
167
|
+
chunkId,
|
|
168
|
+
id,
|
|
169
|
+
collectionId,
|
|
170
|
+
i,
|
|
171
|
+
chunk.heading,
|
|
172
|
+
chunk.text,
|
|
173
|
+
chunk.text.slice(0, 200),
|
|
174
|
+
vectors[i] ? packVector(vectors[i]) : null,
|
|
175
|
+
createHash("sha256").update(chunk.text).digest("hex"),
|
|
176
|
+
now,
|
|
177
|
+
embeddingProfile,
|
|
178
|
+
);
|
|
179
|
+
indexChunk(this.repo.db, chunkId, chunk.text);
|
|
180
|
+
});
|
|
181
|
+
this.repo.db
|
|
182
|
+
.prepare(
|
|
183
|
+
"UPDATE core_documents SET status='ready',error=NULL,updated=? WHERE id=?",
|
|
184
|
+
)
|
|
185
|
+
.run(Date.now(), id);
|
|
186
|
+
this.repo.db
|
|
187
|
+
.prepare("UPDATE core_collections SET updated=? WHERE id=?")
|
|
188
|
+
.run(Date.now(), collectionId);
|
|
189
|
+
this.repo.db.exec("COMMIT");
|
|
190
|
+
} catch (error) {
|
|
191
|
+
this.repo.db.exec("ROLLBACK");
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
this.repo.store.revision++;
|
|
195
|
+
return this.repo.db
|
|
196
|
+
.prepare("SELECT * FROM core_documents WHERE id=?")
|
|
197
|
+
.get(id);
|
|
198
|
+
}
|
|
199
|
+
async embedTexts(texts) {
|
|
200
|
+
const { profile } = resolveEmbeddingProfile(this.repo, this.models);
|
|
201
|
+
return embedBatches(this.models, profile, texts);
|
|
202
|
+
}
|
|
203
|
+
retrieve(
|
|
204
|
+
session,
|
|
205
|
+
rows,
|
|
206
|
+
cutoff = Date.now(),
|
|
207
|
+
{ vectors = [], signature = null, legacy = true } = {},
|
|
208
|
+
) {
|
|
209
|
+
const allowed = new Set(
|
|
210
|
+
this.repo.db
|
|
211
|
+
.prepare("SELECT id,scope FROM core_collections")
|
|
212
|
+
.all()
|
|
213
|
+
.filter((c) => allowedCollection(this.repo.db, c, session))
|
|
214
|
+
.map((c) => c.id),
|
|
215
|
+
);
|
|
216
|
+
if (!allowed.size) return [];
|
|
217
|
+
const queries = saidBy(rows).slice(0, 8);
|
|
218
|
+
if (!queries.length) return [];
|
|
219
|
+
// Each person's own words. Two people are not added together, and a
|
|
220
|
+
// line she already said does not count as the room asking. A prepared
|
|
221
|
+
// vector belongs to that same person, not to the batch mixed together.
|
|
222
|
+
if (vectors.some((vector) => vector?.length))
|
|
223
|
+
ensureVectorIndex(this.repo.db);
|
|
224
|
+
const best = new Map();
|
|
225
|
+
const selected = new Map();
|
|
226
|
+
for (let i = 0; i < queries.length; i++) {
|
|
227
|
+
const query = queries[i];
|
|
228
|
+
const match = ftsMatchQuery(query);
|
|
229
|
+
const fts = new Set();
|
|
230
|
+
if (match)
|
|
231
|
+
try {
|
|
232
|
+
for (const hit of this.repo.db
|
|
233
|
+
.prepare(
|
|
234
|
+
`SELECT f.chunk_id FROM core_chunk_fts f JOIN core_chunks c ON c.id=f.chunk_id JOIN core_documents d ON d.id=c.document_id WHERE f.tokens MATCH ? AND c.collection_id IN (${[...allowed].map(() => "?").join(",")}) AND d.status='ready' AND d.created<=? ORDER BY f.rank LIMIT 128`,
|
|
235
|
+
)
|
|
236
|
+
.all(match, ...allowed, cutoff))
|
|
237
|
+
fts.add(hit.chunk_id);
|
|
238
|
+
} catch {
|
|
239
|
+
/* malformed MATCH */
|
|
240
|
+
}
|
|
241
|
+
const queryTerms = lexicalTerms(query);
|
|
242
|
+
const vec = vectors[i] || null;
|
|
243
|
+
const ids = [
|
|
244
|
+
...new Set([
|
|
245
|
+
...fts,
|
|
246
|
+
...(vec
|
|
247
|
+
? vectorCandidates(this.repo.db, vec, [...allowed], cutoff, {
|
|
248
|
+
signature,
|
|
249
|
+
legacy,
|
|
250
|
+
})
|
|
251
|
+
: []),
|
|
252
|
+
]),
|
|
253
|
+
];
|
|
254
|
+
const chunks = ids.length
|
|
255
|
+
? this.repo.db
|
|
256
|
+
.prepare(
|
|
257
|
+
`SELECT c.*,d.title,d.created AS document_created FROM core_chunks c JOIN core_documents d ON d.id=c.document_id WHERE c.id IN (${ids.map(() => "?").join(",")})`,
|
|
258
|
+
)
|
|
259
|
+
.all(...ids)
|
|
260
|
+
: [];
|
|
261
|
+
for (const chunk of chunks) {
|
|
262
|
+
selected.set(chunk.id, chunk);
|
|
263
|
+
let score =
|
|
264
|
+
(fts.has(chunk.id) ? 2 : 0) +
|
|
265
|
+
overlapScore(chunk.text, queryTerms) * 0.5;
|
|
266
|
+
if (
|
|
267
|
+
vec &&
|
|
268
|
+
chunk.embedding &&
|
|
269
|
+
(!signature ||
|
|
270
|
+
chunk.embedding_profile === signature ||
|
|
271
|
+
(legacy && !chunk.embedding_profile))
|
|
272
|
+
)
|
|
273
|
+
score += cosine(vec, unpackVector(chunk.embedding)) * 4;
|
|
274
|
+
const ageDays = (cutoff - (chunk.document_created || 0)) / 86400000;
|
|
275
|
+
if (ageDays > 30) score *= 0.85;
|
|
276
|
+
if (score > (best.get(chunk.id) || 0)) best.set(chunk.id, score);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return [...best.entries()]
|
|
280
|
+
.sort((a, b) => b[1] - a[1])
|
|
281
|
+
.slice(0, 8)
|
|
282
|
+
.map(([id, score]) => {
|
|
283
|
+
const chunk = selected.get(id);
|
|
284
|
+
if (!chunk) return null;
|
|
285
|
+
return {
|
|
286
|
+
id: chunk.id,
|
|
287
|
+
documentId: chunk.document_id,
|
|
288
|
+
title: chunk.title,
|
|
289
|
+
heading: chunk.heading,
|
|
290
|
+
text: chunk.text.slice(0, 800),
|
|
291
|
+
score,
|
|
292
|
+
whySelected: score >= 4 ? "semantic+lexical" : "lexical",
|
|
293
|
+
};
|
|
294
|
+
})
|
|
295
|
+
.filter((c) => c?.text);
|
|
296
|
+
}
|
|
297
|
+
async retrieveWithEmbed(session, rows, cutoff = Date.now()) {
|
|
298
|
+
const { profile, signature, legacy } = resolveEmbeddingProfile(
|
|
299
|
+
this.repo,
|
|
300
|
+
this.models,
|
|
301
|
+
);
|
|
302
|
+
const queries = saidBy(rows).slice(0, 8);
|
|
303
|
+
let vectors = [];
|
|
304
|
+
if (profile.embedding && queries.length) {
|
|
305
|
+
try {
|
|
306
|
+
vectors = await embedBatches(
|
|
307
|
+
this.models,
|
|
308
|
+
profile,
|
|
309
|
+
queries.map((query) => query.slice(0, 2000)),
|
|
310
|
+
);
|
|
311
|
+
} catch {
|
|
312
|
+
vectors = [];
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return this.retrieve(session, rows, cutoff, { vectors, signature, legacy });
|
|
316
|
+
}
|
|
317
|
+
async reembedDocument(id) {
|
|
318
|
+
const rows = this.repo.db
|
|
319
|
+
.prepare(
|
|
320
|
+
"SELECT id,text FROM core_chunks WHERE document_id=? ORDER BY ordinal",
|
|
321
|
+
)
|
|
322
|
+
.all(id);
|
|
323
|
+
if (!rows.length) throw Error("文档没有可建立向量的段落");
|
|
324
|
+
const { profile, signature } = resolveEmbeddingProfile(
|
|
325
|
+
this.repo,
|
|
326
|
+
this.models,
|
|
327
|
+
);
|
|
328
|
+
if (!profile.embedding) throw Error("请先启用知识向量模型");
|
|
329
|
+
const vectors = await embedBatches(
|
|
330
|
+
this.models,
|
|
331
|
+
profile,
|
|
332
|
+
rows.map((row) => row.text),
|
|
333
|
+
);
|
|
334
|
+
const db = this.repo.db;
|
|
335
|
+
db.exec("SAVEPOINT reembed_document");
|
|
336
|
+
try {
|
|
337
|
+
const update = db.prepare(
|
|
338
|
+
"UPDATE core_chunks SET embedding=?,embedding_profile=? WHERE id=? AND document_id=? AND text=?",
|
|
339
|
+
);
|
|
340
|
+
rows.forEach((row, index) => {
|
|
341
|
+
if (
|
|
342
|
+
!update.run(
|
|
343
|
+
packVector(vectors[index]),
|
|
344
|
+
signature,
|
|
345
|
+
row.id,
|
|
346
|
+
id,
|
|
347
|
+
row.text,
|
|
348
|
+
).changes
|
|
349
|
+
)
|
|
350
|
+
throw Error("文档已变化,请重新建立向量");
|
|
351
|
+
});
|
|
352
|
+
db.exec("RELEASE reembed_document");
|
|
353
|
+
} catch (error) {
|
|
354
|
+
db.exec("ROLLBACK TO reembed_document");
|
|
355
|
+
db.exec("RELEASE reembed_document");
|
|
356
|
+
throw error;
|
|
357
|
+
}
|
|
358
|
+
this.repo.store.revision++;
|
|
359
|
+
return { chunks: rows.length };
|
|
360
|
+
}
|
|
361
|
+
removeDocument(id) {
|
|
362
|
+
const row = this.repo.db
|
|
363
|
+
.prepare("SELECT * FROM core_documents WHERE id=?")
|
|
364
|
+
.get(id);
|
|
365
|
+
if (!row) throw Error("文档不存在");
|
|
366
|
+
const chunks = this.repo.db
|
|
367
|
+
.prepare("SELECT id FROM core_chunks WHERE document_id=?")
|
|
368
|
+
.all(id);
|
|
369
|
+
this.repo.db.exec("BEGIN IMMEDIATE");
|
|
370
|
+
try {
|
|
371
|
+
for (const chunk of chunks)
|
|
372
|
+
this.repo.db
|
|
373
|
+
.prepare("DELETE FROM core_chunk_fts WHERE chunk_id=?")
|
|
374
|
+
.run(chunk.id);
|
|
375
|
+
this.repo.db
|
|
376
|
+
.prepare("DELETE FROM core_chunks WHERE document_id=?")
|
|
377
|
+
.run(id);
|
|
378
|
+
this.repo.db.prepare("DELETE FROM core_documents WHERE id=?").run(id);
|
|
379
|
+
this.repo.db.exec("COMMIT");
|
|
380
|
+
} catch (e) {
|
|
381
|
+
this.repo.db.exec("ROLLBACK");
|
|
382
|
+
throw e;
|
|
383
|
+
}
|
|
384
|
+
this.repo.store.revision++;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export function lexicalTerms(s) {
|
|
2
|
+
return new Set(
|
|
3
|
+
String(s)
|
|
4
|
+
.toLowerCase()
|
|
5
|
+
.match(/[a-z0-9]+|[\u4e00-\u9fff]{1,2}/g) || [],
|
|
6
|
+
);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function ftsTokens(s) {
|
|
10
|
+
return [...lexicalTerms(s)].join(" ");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function ftsMatchQuery(s) {
|
|
14
|
+
return [...lexicalTerms(s)]
|
|
15
|
+
.slice(0, 24)
|
|
16
|
+
.map((t) => `"${t.replace(/"/g, "")}"`)
|
|
17
|
+
.filter((t) => t.length > 2)
|
|
18
|
+
.join(" OR ");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function overlapScore(text, queryTerms) {
|
|
22
|
+
if (!queryTerms?.size) return 0;
|
|
23
|
+
return [...lexicalTerms(text)].filter((t) => queryTerms.has(t)).length;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function cosine(a, b) {
|
|
27
|
+
if (!a?.length || !b?.length || a.length !== b.length) return 0;
|
|
28
|
+
let dot = 0,
|
|
29
|
+
na = 0,
|
|
30
|
+
nb = 0;
|
|
31
|
+
for (let i = 0; i < a.length; i++) {
|
|
32
|
+
dot += a[i] * b[i];
|
|
33
|
+
na += a[i] * a[i];
|
|
34
|
+
nb += b[i] * b[i];
|
|
35
|
+
}
|
|
36
|
+
return dot / (Math.sqrt(na) * Math.sqrt(nb) || 1);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function packVector(values) {
|
|
40
|
+
return Buffer.from(new Float32Array(values).buffer);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function unpackVector(blob) {
|
|
44
|
+
if (!blob) return null;
|
|
45
|
+
const buf = Buffer.isBuffer(blob) ? blob : Buffer.from(blob);
|
|
46
|
+
return Array.from(
|
|
47
|
+
new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function asPlainDocument(text) {
|
|
52
|
+
let source = String(text || "").replace(/\r\n/g, "\n");
|
|
53
|
+
if (/<\/?[a-z][\s\S]*>/i.test(source))
|
|
54
|
+
source = source
|
|
55
|
+
.replace(/<script[\s\S]*?<\/script>/gi, "\n")
|
|
56
|
+
.replace(/<style[\s\S]*?<\/style>/gi, "\n")
|
|
57
|
+
.replace(/<h([1-3])[^>]*>([\s\S]*?)<\/h\1>/gi, (_, level, title) => {
|
|
58
|
+
const hashes = "#".repeat(Number(level) || 1);
|
|
59
|
+
return `\n${hashes} ${title.replace(/<[^>]+>/g, "").trim()}\n`;
|
|
60
|
+
})
|
|
61
|
+
.replace(/<[^>]+>/g, " ");
|
|
62
|
+
return source
|
|
63
|
+
.replace(/[ \t]+\n/g, "\n")
|
|
64
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
65
|
+
.trim();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function chunkText(text, { size = 600, overlap = 80 } = {}) {
|
|
69
|
+
const source = String(text || "")
|
|
70
|
+
.replace(/\r\n/g, "\n")
|
|
71
|
+
.trim();
|
|
72
|
+
if (!source) return [];
|
|
73
|
+
const parts = source.split(/(?=^#{1,3} )/m);
|
|
74
|
+
const chunks = [];
|
|
75
|
+
for (const part of parts) {
|
|
76
|
+
const heading = part.match(/^#{1,3} ([^\n]+)/)?.[1] || "";
|
|
77
|
+
const chars = Array.from(part.trim());
|
|
78
|
+
if (!chars.length) continue;
|
|
79
|
+
if (chars.length <= size) {
|
|
80
|
+
chunks.push({ heading, text: part.trim() });
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
for (let i = 0; i < chars.length; i += Math.max(1, size - overlap)) {
|
|
84
|
+
const slice = chars
|
|
85
|
+
.slice(i, i + size)
|
|
86
|
+
.join("")
|
|
87
|
+
.trim();
|
|
88
|
+
if (slice) chunks.push({ heading, text: slice });
|
|
89
|
+
if (i + size >= chars.length) break;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return chunks;
|
|
93
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { ftsTokens } from "./retrieval.js";
|
|
2
|
+
|
|
3
|
+
export function indexMemory(db, id, content) {
|
|
4
|
+
db.prepare("DELETE FROM core_memory_fts WHERE memory_id=?").run(id);
|
|
5
|
+
const tokens = ftsTokens(content);
|
|
6
|
+
if (tokens)
|
|
7
|
+
db.prepare(
|
|
8
|
+
"INSERT INTO core_memory_fts(memory_id, tokens) VALUES (?,?)",
|
|
9
|
+
).run(id, tokens);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function indexChunk(db, id, content) {
|
|
13
|
+
db.prepare("DELETE FROM core_chunk_fts WHERE chunk_id=?").run(id);
|
|
14
|
+
const tokens = ftsTokens(content);
|
|
15
|
+
if (tokens)
|
|
16
|
+
db.prepare("INSERT INTO core_chunk_fts(chunk_id, tokens) VALUES (?,?)").run(
|
|
17
|
+
id,
|
|
18
|
+
tokens,
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function mergeLegacyMemories(db) {
|
|
23
|
+
if (db.prepare("SELECT id FROM core_config WHERE id='memory-merge-v1'").get())
|
|
24
|
+
return;
|
|
25
|
+
db.exec("BEGIN IMMEDIATE");
|
|
26
|
+
try {
|
|
27
|
+
for (const m of db.prepare("SELECT * FROM memories").all()) {
|
|
28
|
+
const sessionId =
|
|
29
|
+
m.scope === "shared"
|
|
30
|
+
? "__shared__"
|
|
31
|
+
: m.scope === "private"
|
|
32
|
+
? `__private__:${m.user_id}`
|
|
33
|
+
: m.scope;
|
|
34
|
+
const id = "legacy:" + m.id;
|
|
35
|
+
if (db.prepare("SELECT id FROM core_memories WHERE id=?").get(id))
|
|
36
|
+
continue;
|
|
37
|
+
db.prepare(
|
|
38
|
+
"INSERT INTO core_memories(id,session_id,subject,content,type,confidence,importance,status,locked,sources,created,updated) VALUES (?,?,?,?,'reviewed',1,1,'confirmed',1,'[]',?,?)",
|
|
39
|
+
).run(
|
|
40
|
+
id,
|
|
41
|
+
sessionId,
|
|
42
|
+
m.user_id,
|
|
43
|
+
m.content,
|
|
44
|
+
m.time || Date.now(),
|
|
45
|
+
Date.now(),
|
|
46
|
+
);
|
|
47
|
+
indexMemory(db, id, m.content);
|
|
48
|
+
}
|
|
49
|
+
db.prepare("INSERT INTO core_config(id,value) VALUES (?,?)").run(
|
|
50
|
+
"memory-merge-v1",
|
|
51
|
+
JSON.stringify({ time: Date.now() }),
|
|
52
|
+
);
|
|
53
|
+
db.exec("COMMIT");
|
|
54
|
+
} catch (e) {
|
|
55
|
+
db.exec("ROLLBACK");
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function migrateKnowledge(db) {
|
|
61
|
+
db.exec(`
|
|
62
|
+
CREATE TABLE IF NOT EXISTS core_collections (
|
|
63
|
+
id TEXT PRIMARY KEY,
|
|
64
|
+
name TEXT NOT NULL,
|
|
65
|
+
scope TEXT NOT NULL,
|
|
66
|
+
created INTEGER NOT NULL,
|
|
67
|
+
updated INTEGER NOT NULL
|
|
68
|
+
);
|
|
69
|
+
CREATE TABLE IF NOT EXISTS core_collection_sessions (
|
|
70
|
+
collection_id TEXT NOT NULL,
|
|
71
|
+
session_id TEXT NOT NULL,
|
|
72
|
+
PRIMARY KEY(collection_id, session_id)
|
|
73
|
+
);
|
|
74
|
+
CREATE TABLE IF NOT EXISTS core_documents (
|
|
75
|
+
id TEXT PRIMARY KEY,
|
|
76
|
+
collection_id TEXT NOT NULL,
|
|
77
|
+
title TEXT NOT NULL,
|
|
78
|
+
source TEXT,
|
|
79
|
+
path TEXT,
|
|
80
|
+
status TEXT NOT NULL,
|
|
81
|
+
error TEXT,
|
|
82
|
+
created INTEGER NOT NULL,
|
|
83
|
+
updated INTEGER NOT NULL,
|
|
84
|
+
bytes INTEGER,
|
|
85
|
+
hash TEXT
|
|
86
|
+
);
|
|
87
|
+
CREATE TABLE IF NOT EXISTS core_chunks (
|
|
88
|
+
id TEXT PRIMARY KEY,
|
|
89
|
+
document_id TEXT NOT NULL,
|
|
90
|
+
collection_id TEXT NOT NULL,
|
|
91
|
+
ordinal INTEGER NOT NULL,
|
|
92
|
+
heading TEXT,
|
|
93
|
+
text TEXT NOT NULL,
|
|
94
|
+
tokens TEXT,
|
|
95
|
+
embedding BLOB,
|
|
96
|
+
hash TEXT,
|
|
97
|
+
created INTEGER NOT NULL
|
|
98
|
+
);
|
|
99
|
+
`);
|
|
100
|
+
db.exec(
|
|
101
|
+
"CREATE VIRTUAL TABLE IF NOT EXISTS core_memory_fts USING fts5(memory_id UNINDEXED, tokens)",
|
|
102
|
+
);
|
|
103
|
+
db.exec(
|
|
104
|
+
"CREATE VIRTUAL TABLE IF NOT EXISTS core_chunk_fts USING fts5(chunk_id UNINDEXED, tokens)",
|
|
105
|
+
);
|
|
106
|
+
if (
|
|
107
|
+
!db
|
|
108
|
+
.prepare("PRAGMA table_info(core_chunks)")
|
|
109
|
+
.all()
|
|
110
|
+
.some((c) => c.name === "vector_indexed")
|
|
111
|
+
)
|
|
112
|
+
db.exec(
|
|
113
|
+
"ALTER TABLE core_chunks ADD COLUMN vector_indexed INTEGER NOT NULL DEFAULT 0",
|
|
114
|
+
);
|
|
115
|
+
if (
|
|
116
|
+
!db
|
|
117
|
+
.prepare("PRAGMA table_info(core_chunks)")
|
|
118
|
+
.all()
|
|
119
|
+
.some((c) => c.name === "embedding_profile")
|
|
120
|
+
)
|
|
121
|
+
db.exec(
|
|
122
|
+
"ALTER TABLE core_chunks ADD COLUMN embedding_profile TEXT NOT NULL DEFAULT ''",
|
|
123
|
+
);
|
|
124
|
+
db.exec(`CREATE INDEX IF NOT EXISTS core_chunks_collection ON core_chunks(collection_id, document_id);
|
|
125
|
+
CREATE INDEX IF NOT EXISTS core_chunks_unindexed ON core_chunks(vector_indexed) WHERE embedding IS NOT NULL;
|
|
126
|
+
CREATE TABLE IF NOT EXISTS core_vector_buckets(dimension INTEGER NOT NULL,band INTEGER NOT NULL,bucket INTEGER NOT NULL,chunk_id TEXT NOT NULL,PRIMARY KEY(dimension,band,bucket,chunk_id));
|
|
127
|
+
CREATE INDEX IF NOT EXISTS core_vector_buckets_chunk ON core_vector_buckets(chunk_id);
|
|
128
|
+
CREATE TRIGGER IF NOT EXISTS core_vector_changed AFTER UPDATE OF embedding ON core_chunks BEGIN
|
|
129
|
+
DELETE FROM core_vector_buckets WHERE chunk_id=NEW.id;
|
|
130
|
+
UPDATE core_chunks SET vector_indexed=0 WHERE id=NEW.id;
|
|
131
|
+
END;
|
|
132
|
+
CREATE TRIGGER IF NOT EXISTS core_vector_deleted AFTER DELETE ON core_chunks BEGIN
|
|
133
|
+
DELETE FROM core_vector_buckets WHERE chunk_id=OLD.id;
|
|
134
|
+
END;`);
|
|
135
|
+
if (
|
|
136
|
+
!db
|
|
137
|
+
.prepare("SELECT id FROM core_collections WHERE id='shared-default'")
|
|
138
|
+
.get()
|
|
139
|
+
)
|
|
140
|
+
db.prepare(
|
|
141
|
+
"INSERT INTO core_collections(id,name,scope,created,updated) VALUES ('shared-default','共享知识库','shared',?,?)",
|
|
142
|
+
).run(Date.now(), Date.now());
|
|
143
|
+
mergeLegacyMemories(db);
|
|
144
|
+
if (
|
|
145
|
+
!db.prepare("SELECT id FROM core_config WHERE id='memory-fts-v1'").get()
|
|
146
|
+
) {
|
|
147
|
+
for (const m of db.prepare("SELECT id,content FROM core_memories").all())
|
|
148
|
+
indexMemory(db, m.id, m.content);
|
|
149
|
+
db.prepare("INSERT INTO core_config(id,value) VALUES (?,?)").run(
|
|
150
|
+
"memory-fts-v1",
|
|
151
|
+
JSON.stringify({ time: Date.now() }),
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
}
|