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,241 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
openSync,
|
|
5
|
+
readSync,
|
|
6
|
+
closeSync,
|
|
7
|
+
existsSync,
|
|
8
|
+
readFileSync,
|
|
9
|
+
writeFileSync,
|
|
10
|
+
renameSync,
|
|
11
|
+
rmSync,
|
|
12
|
+
mkdirSync,
|
|
13
|
+
linkSync,
|
|
14
|
+
} from "node:fs";
|
|
15
|
+
import { dirname, basename, resolve, join } from "node:path";
|
|
16
|
+
import { VERSION } from "../version.js";
|
|
17
|
+
import { withBackupLock } from "./backup-lock.js";
|
|
18
|
+
|
|
19
|
+
export const DATABASE_VERSION = 4;
|
|
20
|
+
const appVersion = VERSION;
|
|
21
|
+
const IDENTITY = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
|
|
22
|
+
|
|
23
|
+
export function archiveIdentity(file) {
|
|
24
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
25
|
+
try {
|
|
26
|
+
const row = db.prepare("SELECT value FROM settings WHERE id=1").get();
|
|
27
|
+
const value = row && JSON.parse(row.value).backupIdentity;
|
|
28
|
+
return typeof value === "string" && IDENTITY.test(value) ? value : null;
|
|
29
|
+
} finally {
|
|
30
|
+
db.close();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function ensureArchiveIdentity(file) {
|
|
35
|
+
const db = new DatabaseSync(file);
|
|
36
|
+
try {
|
|
37
|
+
db.exec("PRAGMA busy_timeout=5000; BEGIN IMMEDIATE");
|
|
38
|
+
const row = db.prepare("SELECT value FROM settings WHERE id=1").get();
|
|
39
|
+
if (!row) throw Error("这不是 LuckyTri 数据库");
|
|
40
|
+
const settings = JSON.parse(row.value);
|
|
41
|
+
let value = settings.backupIdentity;
|
|
42
|
+
if (typeof value !== "string" || !IDENTITY.test(value)) {
|
|
43
|
+
value = randomUUID();
|
|
44
|
+
db.prepare("UPDATE settings SET value=? WHERE id=1").run(
|
|
45
|
+
JSON.stringify({ ...settings, backupIdentity: value }),
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
db.exec("COMMIT");
|
|
49
|
+
return value;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (db.isTransaction) db.exec("ROLLBACK");
|
|
52
|
+
throw error;
|
|
53
|
+
} finally {
|
|
54
|
+
db.close();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function fileHash(file) {
|
|
59
|
+
const fd = openSync(file, "r"),
|
|
60
|
+
hash = createHash("sha256"),
|
|
61
|
+
buffer = Buffer.alloc(1024 * 1024);
|
|
62
|
+
try {
|
|
63
|
+
let bytes;
|
|
64
|
+
while ((bytes = readSync(fd, buffer, 0, buffer.length, null)))
|
|
65
|
+
hash.update(buffer.subarray(0, bytes));
|
|
66
|
+
return hash.digest("hex");
|
|
67
|
+
} finally {
|
|
68
|
+
closeSync(fd);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function inspectDatabase(file) {
|
|
73
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
74
|
+
try {
|
|
75
|
+
const schemaVersion = db.prepare("PRAGMA user_version").get().user_version;
|
|
76
|
+
if (schemaVersion > DATABASE_VERSION)
|
|
77
|
+
throw Error("数据库来自更新版本,请先升级 LuckyTri;未修改数据");
|
|
78
|
+
const check = db.prepare("PRAGMA integrity_check").all();
|
|
79
|
+
if (check.length !== 1 || check[0].integrity_check !== "ok")
|
|
80
|
+
throw Error("数据库完整性检查失败");
|
|
81
|
+
if (db.prepare("PRAGMA foreign_key_check").all().length)
|
|
82
|
+
throw Error("数据库引用检查失败");
|
|
83
|
+
const schema = db
|
|
84
|
+
.prepare(
|
|
85
|
+
"SELECT type,name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name",
|
|
86
|
+
)
|
|
87
|
+
.all();
|
|
88
|
+
if (!schema.some((row) => row.type === "table" && row.name === "settings"))
|
|
89
|
+
throw Error("这不是 LuckyTri 数据库");
|
|
90
|
+
const tables = {};
|
|
91
|
+
for (const row of schema.filter(
|
|
92
|
+
(row) =>
|
|
93
|
+
row.type === "table" &&
|
|
94
|
+
/^(mind_|core_events$|core_memories$|core_chunks$|settings$|plugin_installs$)/.test(
|
|
95
|
+
row.name,
|
|
96
|
+
),
|
|
97
|
+
))
|
|
98
|
+
tables[row.name] = Number(
|
|
99
|
+
db
|
|
100
|
+
.prepare(`SELECT COUNT(*) n FROM "${row.name.replace(/"/g, '""')}"`)
|
|
101
|
+
.get().n,
|
|
102
|
+
);
|
|
103
|
+
return {
|
|
104
|
+
schemaVersion,
|
|
105
|
+
schemaHash: createHash("sha256")
|
|
106
|
+
.update(JSON.stringify(schema))
|
|
107
|
+
.digest("hex"),
|
|
108
|
+
tables,
|
|
109
|
+
};
|
|
110
|
+
} finally {
|
|
111
|
+
db.close();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function writeArchiveManifest(
|
|
116
|
+
file,
|
|
117
|
+
{ kind = "full", filename = basename(file) } = {},
|
|
118
|
+
) {
|
|
119
|
+
const inspected = inspectDatabase(file);
|
|
120
|
+
const manifest = {
|
|
121
|
+
format: 1,
|
|
122
|
+
app: "luckytri",
|
|
123
|
+
appVersion,
|
|
124
|
+
created: Date.now(),
|
|
125
|
+
kind,
|
|
126
|
+
databaseId: archiveIdentity(file),
|
|
127
|
+
file: filename,
|
|
128
|
+
sha256: fileHash(file),
|
|
129
|
+
...inspected,
|
|
130
|
+
};
|
|
131
|
+
const temporary = `${file}.json.${randomUUID()}.partial`;
|
|
132
|
+
try {
|
|
133
|
+
writeFileSync(temporary, JSON.stringify(manifest, null, 2), {
|
|
134
|
+
flush: true,
|
|
135
|
+
});
|
|
136
|
+
renameSync(temporary, `${file}.json`);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
rmSync(temporary, { force: true });
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
return manifest;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function verifyArchive(file) {
|
|
145
|
+
const inspected = inspectDatabase(file);
|
|
146
|
+
const sidecar = `${file}.json`;
|
|
147
|
+
if (!existsSync(sidecar)) return { ...inspected, manifest: false }; // Readable legacy backups remain usable.
|
|
148
|
+
const manifest = JSON.parse(readFileSync(sidecar, "utf8"));
|
|
149
|
+
if (
|
|
150
|
+
manifest.format !== 1 ||
|
|
151
|
+
manifest.app !== "luckytri" ||
|
|
152
|
+
manifest.sha256 !== fileHash(file) ||
|
|
153
|
+
manifest.schemaHash !== inspected.schemaHash ||
|
|
154
|
+
(manifest.databaseId && manifest.databaseId !== archiveIdentity(file)) ||
|
|
155
|
+
JSON.stringify(manifest.tables) !== JSON.stringify(inspected.tables)
|
|
156
|
+
)
|
|
157
|
+
throw Error("备份校验清单不匹配");
|
|
158
|
+
return {
|
|
159
|
+
...inspected,
|
|
160
|
+
manifest: true,
|
|
161
|
+
kind: manifest.kind,
|
|
162
|
+
databaseId: manifest.databaseId || null,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function copyDatabaseFile(source, target) {
|
|
167
|
+
const db = new DatabaseSync(source, { readOnly: true });
|
|
168
|
+
try {
|
|
169
|
+
db.prepare("VACUUM INTO ?").run(target);
|
|
170
|
+
} finally {
|
|
171
|
+
db.close();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function restoreToNewFile(source, destination) {
|
|
176
|
+
const target = resolve(destination);
|
|
177
|
+
if ([target, `${target}-wal`, `${target}-shm`].some(existsSync))
|
|
178
|
+
throw Error("恢复目标或伴随文件已存在,请选一个新文件;未覆盖任何数据");
|
|
179
|
+
verifyArchive(source);
|
|
180
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
181
|
+
const partial = `${target}.${randomUUID()}.partial`;
|
|
182
|
+
try {
|
|
183
|
+
copyDatabaseFile(source, partial);
|
|
184
|
+
inspectDatabase(partial);
|
|
185
|
+
// Another process may have created the destination during the copy.
|
|
186
|
+
if (existsSync(target)) throw Error("恢复目标已被其他进程创建");
|
|
187
|
+
// Publish the verified file atomically and exclusively in the same directory.
|
|
188
|
+
linkSync(partial, target);
|
|
189
|
+
rmSync(partial);
|
|
190
|
+
return target;
|
|
191
|
+
} catch (error) {
|
|
192
|
+
rmSync(partial, { force: true });
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function prepareDatabaseMigration(file) {
|
|
198
|
+
if (file === ":memory:" || !existsSync(file)) return null;
|
|
199
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
200
|
+
let version, hasData;
|
|
201
|
+
try {
|
|
202
|
+
version = db.prepare("PRAGMA user_version").get().user_version;
|
|
203
|
+
if (version > DATABASE_VERSION)
|
|
204
|
+
throw Error("数据库版本较新,请升级 LuckyTri;未修改数据");
|
|
205
|
+
hasData = !!db
|
|
206
|
+
.prepare(
|
|
207
|
+
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='settings'",
|
|
208
|
+
)
|
|
209
|
+
.get();
|
|
210
|
+
} finally {
|
|
211
|
+
db.close();
|
|
212
|
+
}
|
|
213
|
+
if (version === DATABASE_VERSION || !hasData) return null;
|
|
214
|
+
console.log(
|
|
215
|
+
`正在把数据库从 v${version} 升级到 v${DATABASE_VERSION}。会先复制整份数据,记录越多越久,请不要关闭窗口。`,
|
|
216
|
+
);
|
|
217
|
+
const directory = join(dirname(resolve(file)), "backups");
|
|
218
|
+
mkdirSync(directory, { recursive: true });
|
|
219
|
+
const target = join(
|
|
220
|
+
directory,
|
|
221
|
+
`luckytri-migration-v${version}-to-v${DATABASE_VERSION}-${Date.now()}-${randomUUID().slice(0, 8)}.db`,
|
|
222
|
+
);
|
|
223
|
+
return withBackupLock(directory, () => {
|
|
224
|
+
const partial = `${target}.partial`;
|
|
225
|
+
try {
|
|
226
|
+
ensureArchiveIdentity(file);
|
|
227
|
+
copyDatabaseFile(file, partial);
|
|
228
|
+
writeArchiveManifest(partial, {
|
|
229
|
+
kind: "migration",
|
|
230
|
+
filename: basename(target),
|
|
231
|
+
});
|
|
232
|
+
renameSync(partial, target);
|
|
233
|
+
renameSync(`${partial}.json`, `${target}.json`);
|
|
234
|
+
return target;
|
|
235
|
+
} catch (error) {
|
|
236
|
+
rmSync(partial, { force: true });
|
|
237
|
+
rmSync(`${partial}.json`, { force: true });
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import { executeCleanup } from "./backup-cleanup.js";
|
|
3
|
+
|
|
4
|
+
try {
|
|
5
|
+
parentPort.postMessage({ result: executeCleanup(workerData) });
|
|
6
|
+
} catch (error) {
|
|
7
|
+
parentPort.postMessage({ error: error.message });
|
|
8
|
+
}
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
import { runtimePaths } from "../paths.js";
|
|
3
|
+
import { backupDirectory } from "../../scripts/backup.js";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
existsSync,
|
|
7
|
+
lstatSync,
|
|
8
|
+
readdirSync,
|
|
9
|
+
readFileSync,
|
|
10
|
+
realpathSync,
|
|
11
|
+
rmSync,
|
|
12
|
+
statSync,
|
|
13
|
+
} from "node:fs";
|
|
14
|
+
import { archiveIdentity, verifyArchive } from "./archive.js";
|
|
15
|
+
import { withBackupLock } from "./backup-lock.js";
|
|
16
|
+
|
|
17
|
+
const DAY = 86400000;
|
|
18
|
+
const DEFAULTS = Object.freeze({
|
|
19
|
+
enabled: true,
|
|
20
|
+
time: "04:30",
|
|
21
|
+
retainDays: 14,
|
|
22
|
+
keepFull: 2,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function kind(scope, name) {
|
|
26
|
+
if (scope === "root")
|
|
27
|
+
return /^friend\.pre-[\w-]+\.db$/.test(name) ? "snapshot" : null;
|
|
28
|
+
if (/^luckytri-auto-\d{4}-\d\d-\d\dT[\d-]+Z\.db$/.test(name)) return "auto";
|
|
29
|
+
if (/^luckytri-migration-v\d+-to-v\d+-\d+-[\da-f]{8}\.db$/.test(name))
|
|
30
|
+
return "migration";
|
|
31
|
+
if (/^luckytri-\d{4}-\d\d-\d\dT[\d-]+Z-[\da-f]{8}\.db$/.test(name))
|
|
32
|
+
return "full";
|
|
33
|
+
if (/^(?:luckybot|unlucky|xiaoman)-[\w-]+\.db$/.test(name)) return "legacy";
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function stamped(name, modified) {
|
|
38
|
+
const match = /(\d{4}-\d\d-\d\d)T(\d\d)-(\d\d)-(\d\d)-(\d{3})Z/.exec(name);
|
|
39
|
+
const value = match
|
|
40
|
+
? Date.parse(`${match[1]}T${match[2]}:${match[3]}:${match[4]}.${match[5]}Z`)
|
|
41
|
+
: NaN;
|
|
42
|
+
return Number.isFinite(value) ? value : modified;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function cleanupPolicy(value = {}) {
|
|
46
|
+
if (
|
|
47
|
+
typeof value !== "object" ||
|
|
48
|
+
!value ||
|
|
49
|
+
Array.isArray(value) ||
|
|
50
|
+
typeof value.enabled !== "boolean" ||
|
|
51
|
+
!/^([01]\d|2[0-3]):[0-5]\d$/.test(value.time) ||
|
|
52
|
+
!Number.isInteger(value.retainDays) ||
|
|
53
|
+
value.retainDays < 1 ||
|
|
54
|
+
value.retainDays > 3650 ||
|
|
55
|
+
!Number.isInteger(value.keepFull) ||
|
|
56
|
+
value.keepFull < 0 ||
|
|
57
|
+
value.keepFull > 100
|
|
58
|
+
)
|
|
59
|
+
throw Error("清理规则无效:保留天数为 1–3650,完整备份数量为 0–100");
|
|
60
|
+
return Object.fromEntries(
|
|
61
|
+
Object.keys(DEFAULTS).map((key) => [key, value[key]]),
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function backupInventory({ directory, source }) {
|
|
66
|
+
const root = dirname(resolve(source));
|
|
67
|
+
const sourcePath = existsSync(source)
|
|
68
|
+
? realpathSync(source)
|
|
69
|
+
: resolve(source);
|
|
70
|
+
const sourceStat = existsSync(source) ? statSync(source) : null;
|
|
71
|
+
const sourceId = sourceStat ? archiveIdentity(source) : null;
|
|
72
|
+
const normalize = (path) =>
|
|
73
|
+
process.platform === "win32" ? path.toLowerCase() : path;
|
|
74
|
+
const folders = [
|
|
75
|
+
["backup", resolve(directory)],
|
|
76
|
+
["root", root],
|
|
77
|
+
];
|
|
78
|
+
const entries = [];
|
|
79
|
+
for (const [scope, folder] of folders) {
|
|
80
|
+
if (!existsSync(folder)) continue;
|
|
81
|
+
for (const entry of readdirSync(folder, { withFileTypes: true })) {
|
|
82
|
+
const category = kind(scope, entry.name);
|
|
83
|
+
if (!category || !entry.isFile()) continue;
|
|
84
|
+
const path = join(folder, entry.name);
|
|
85
|
+
const stat = lstatSync(path);
|
|
86
|
+
if (!stat.isFile()) continue;
|
|
87
|
+
if (
|
|
88
|
+
normalize(realpathSync(path)) === normalize(sourcePath) ||
|
|
89
|
+
(sourceStat?.ino &&
|
|
90
|
+
stat.ino === sourceStat.ino &&
|
|
91
|
+
stat.dev === sourceStat.dev)
|
|
92
|
+
)
|
|
93
|
+
continue;
|
|
94
|
+
let databaseId = null;
|
|
95
|
+
const manifestPath = `${path}.json`;
|
|
96
|
+
if (existsSync(manifestPath)) {
|
|
97
|
+
try {
|
|
98
|
+
if (lstatSync(manifestPath).isFile())
|
|
99
|
+
databaseId =
|
|
100
|
+
JSON.parse(readFileSync(manifestPath, "utf8")).databaseId || null;
|
|
101
|
+
} catch {
|
|
102
|
+
// A damaged manifest is not a trusted recovery point.
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const inUse = existsSync(`${path}-wal`) || existsSync(`${path}-shm`);
|
|
106
|
+
entries.push({
|
|
107
|
+
scope,
|
|
108
|
+
name: entry.name,
|
|
109
|
+
kind: category,
|
|
110
|
+
bytes: stat.size,
|
|
111
|
+
modified: stat.mtimeMs,
|
|
112
|
+
at: stamped(entry.name, stat.mtimeMs),
|
|
113
|
+
manifest: existsSync(`${path}.json`),
|
|
114
|
+
databaseId,
|
|
115
|
+
protected: inUse,
|
|
116
|
+
protectionReason: inUse ? "存在运行伴随文件" : "",
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
entries.sort((a, b) => b.at - a.at || b.name.localeCompare(a.name));
|
|
121
|
+
for (const entry of entries
|
|
122
|
+
.filter(
|
|
123
|
+
(item) =>
|
|
124
|
+
item.kind === "auto" && sourceId && item.databaseId === sourceId,
|
|
125
|
+
)
|
|
126
|
+
.slice(0, 2)) {
|
|
127
|
+
entry.protected = true;
|
|
128
|
+
entry.protectionReason = "近期自动恢复点";
|
|
129
|
+
}
|
|
130
|
+
return entries;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function cleanupPlan(entries, policy, now = Date.now()) {
|
|
134
|
+
const full = entries.filter((item) => item.kind === "full");
|
|
135
|
+
const items = full.filter(
|
|
136
|
+
(item, index) =>
|
|
137
|
+
!item.protected &&
|
|
138
|
+
(index >= policy.keepFull || item.at < now - policy.retainDays * DAY),
|
|
139
|
+
);
|
|
140
|
+
return { items, bytes: items.reduce((sum, item) => sum + item.bytes, 0) };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function safeRecoveryPoint(entries, directory, source, now, chosen) {
|
|
144
|
+
const identity = archiveIdentity(source);
|
|
145
|
+
const selected = new Set(chosen.map((item) => `${item.scope}:${item.name}`));
|
|
146
|
+
for (const candidate of entries.filter(
|
|
147
|
+
(item) =>
|
|
148
|
+
item.kind === "auto" &&
|
|
149
|
+
identity &&
|
|
150
|
+
item.databaseId === identity &&
|
|
151
|
+
item.manifest &&
|
|
152
|
+
now - item.at <= 72 * 3600000 &&
|
|
153
|
+
item.at <= now + 5 * 60000 &&
|
|
154
|
+
!selected.has(`${item.scope}:${item.name}`),
|
|
155
|
+
)) {
|
|
156
|
+
try {
|
|
157
|
+
const result = verifyArchive(join(resolve(directory), candidate.name));
|
|
158
|
+
if (result.databaseId === identity)
|
|
159
|
+
return {
|
|
160
|
+
name: candidate.name,
|
|
161
|
+
at: candidate.at,
|
|
162
|
+
bytes: candidate.bytes,
|
|
163
|
+
};
|
|
164
|
+
} catch {
|
|
165
|
+
// A newer damaged copy must not hide an older valid recovery point.
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
throw Error("缺少同一实例近 72 小时内可校验的自动备份,已停止清理");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function executeCleanup({
|
|
172
|
+
directory,
|
|
173
|
+
source,
|
|
174
|
+
policy,
|
|
175
|
+
mode,
|
|
176
|
+
selection = [],
|
|
177
|
+
now = Date.now(),
|
|
178
|
+
remove = rmSync,
|
|
179
|
+
}) {
|
|
180
|
+
return withBackupLock(directory, () =>
|
|
181
|
+
cleanupBatch({ directory, source, policy, mode, selection, now, remove }),
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function cleanupBatch({
|
|
186
|
+
directory,
|
|
187
|
+
source,
|
|
188
|
+
policy,
|
|
189
|
+
mode,
|
|
190
|
+
selection,
|
|
191
|
+
now,
|
|
192
|
+
remove,
|
|
193
|
+
}) {
|
|
194
|
+
const entries = backupInventory({ directory, source });
|
|
195
|
+
const chosen =
|
|
196
|
+
mode === "scheduled"
|
|
197
|
+
? cleanupPlan(entries, cleanupPolicy(policy), now).items
|
|
198
|
+
: selection.map((request) => {
|
|
199
|
+
if (
|
|
200
|
+
!request ||
|
|
201
|
+
typeof request.name !== "string" ||
|
|
202
|
+
typeof request.scope !== "string" ||
|
|
203
|
+
!Number.isSafeInteger(request.bytes) ||
|
|
204
|
+
!Number.isFinite(request.modified)
|
|
205
|
+
)
|
|
206
|
+
throw Error("选择的备份信息无效");
|
|
207
|
+
const found = entries.find(
|
|
208
|
+
(item) =>
|
|
209
|
+
item.name === request.name && item.scope === request.scope,
|
|
210
|
+
);
|
|
211
|
+
if (
|
|
212
|
+
!found ||
|
|
213
|
+
found.protected ||
|
|
214
|
+
found.bytes !== request.bytes ||
|
|
215
|
+
found.modified !== request.modified
|
|
216
|
+
)
|
|
217
|
+
throw Error("备份已变化或属于必须保留的恢复点,请刷新列表");
|
|
218
|
+
return found;
|
|
219
|
+
});
|
|
220
|
+
if (!["scheduled", "manual"].includes(mode)) throw Error("清理方式无效");
|
|
221
|
+
if (
|
|
222
|
+
new Set(chosen.map((item) => `${item.scope}:${item.name}`)).size !==
|
|
223
|
+
chosen.length
|
|
224
|
+
)
|
|
225
|
+
throw Error("不能重复选择同一份备份");
|
|
226
|
+
if (!chosen.length) return { removed: [], bytes: 0, failures: [] };
|
|
227
|
+
const recovery = safeRecoveryPoint(entries, directory, source, now, chosen);
|
|
228
|
+
const removed = [];
|
|
229
|
+
const failures = [];
|
|
230
|
+
for (const item of chosen) {
|
|
231
|
+
const folder =
|
|
232
|
+
item.scope === "root" ? dirname(resolve(source)) : resolve(directory);
|
|
233
|
+
const path = join(folder, item.name);
|
|
234
|
+
try {
|
|
235
|
+
const stat = lstatSync(path);
|
|
236
|
+
if (
|
|
237
|
+
!stat.isFile() ||
|
|
238
|
+
stat.size !== item.bytes ||
|
|
239
|
+
stat.mtimeMs !== item.modified ||
|
|
240
|
+
existsSync(`${path}-wal`) ||
|
|
241
|
+
existsSync(`${path}-shm`)
|
|
242
|
+
)
|
|
243
|
+
throw Error("备份在清理期间发生变化,已停止后续清理");
|
|
244
|
+
remove(path);
|
|
245
|
+
removed.push({ scope: item.scope, name: item.name, bytes: item.bytes });
|
|
246
|
+
remove(`${path}.json`, { force: true });
|
|
247
|
+
} catch (error) {
|
|
248
|
+
failures.push({
|
|
249
|
+
scope: item.scope,
|
|
250
|
+
name: item.name,
|
|
251
|
+
error: error.code
|
|
252
|
+
? `删除失败(${error.code})`
|
|
253
|
+
: "备份文件已变化或不可删除",
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
removed,
|
|
259
|
+
bytes: removed.reduce((sum, item) => sum + item.bytes, 0),
|
|
260
|
+
failures,
|
|
261
|
+
recovery,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function localDay(now) {
|
|
266
|
+
const d = new Date(now);
|
|
267
|
+
const day = [
|
|
268
|
+
d.getFullYear(),
|
|
269
|
+
String(d.getMonth() + 1).padStart(2, "0"),
|
|
270
|
+
String(d.getDate()).padStart(2, "0"),
|
|
271
|
+
].join("-");
|
|
272
|
+
const time = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
|
273
|
+
return { day, time };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function workerRun(payload) {
|
|
277
|
+
return new Promise((resolve, reject) => {
|
|
278
|
+
const worker = new Worker(
|
|
279
|
+
new URL("./backup-cleanup-worker.js", import.meta.url),
|
|
280
|
+
{
|
|
281
|
+
workerData: payload,
|
|
282
|
+
},
|
|
283
|
+
);
|
|
284
|
+
worker.once("message", ({ result, error }) =>
|
|
285
|
+
error ? reject(Error(error)) : resolve(result),
|
|
286
|
+
);
|
|
287
|
+
worker.once("error", reject);
|
|
288
|
+
worker.once("exit", (code) => {
|
|
289
|
+
if (code) reject(Error(`清理工作异常结束:${code}`));
|
|
290
|
+
});
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export function createBackupCleanup({
|
|
295
|
+
store,
|
|
296
|
+
backup,
|
|
297
|
+
source = runtimePaths().database,
|
|
298
|
+
directory = backupDirectory(source),
|
|
299
|
+
now = () => Date.now(),
|
|
300
|
+
run = workerRun,
|
|
301
|
+
log = console,
|
|
302
|
+
} = {}) {
|
|
303
|
+
let running = false;
|
|
304
|
+
const policy = () => ({ ...DEFAULTS, ...store.settings().backupCleanup });
|
|
305
|
+
const last = () => store.settings().backupCleanupLast || null;
|
|
306
|
+
const info = () => {
|
|
307
|
+
const entries = backupInventory({ directory, source });
|
|
308
|
+
return {
|
|
309
|
+
policy: policy(),
|
|
310
|
+
last: last(),
|
|
311
|
+
running,
|
|
312
|
+
serverTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
313
|
+
totalBytes: entries.reduce((sum, item) => sum + item.bytes, 0),
|
|
314
|
+
plan: cleanupPlan(entries, policy(), now()),
|
|
315
|
+
entries,
|
|
316
|
+
};
|
|
317
|
+
};
|
|
318
|
+
const launch = async (mode, selection = []) => {
|
|
319
|
+
if (running || backup?.running)
|
|
320
|
+
throw Error("备份或清理正在进行,请稍后再试");
|
|
321
|
+
running = true;
|
|
322
|
+
try {
|
|
323
|
+
return await run({
|
|
324
|
+
directory,
|
|
325
|
+
source,
|
|
326
|
+
policy: policy(),
|
|
327
|
+
mode,
|
|
328
|
+
selection,
|
|
329
|
+
now: now(),
|
|
330
|
+
});
|
|
331
|
+
} finally {
|
|
332
|
+
running = false;
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
return {
|
|
336
|
+
info,
|
|
337
|
+
get running() {
|
|
338
|
+
return running;
|
|
339
|
+
},
|
|
340
|
+
save(value) {
|
|
341
|
+
const next = cleanupPolicy(value);
|
|
342
|
+
store.save({ backupCleanup: next });
|
|
343
|
+
return info();
|
|
344
|
+
},
|
|
345
|
+
async manual(selection) {
|
|
346
|
+
if (
|
|
347
|
+
!Array.isArray(selection) ||
|
|
348
|
+
!selection.length ||
|
|
349
|
+
selection.length > 100
|
|
350
|
+
)
|
|
351
|
+
throw Error("请先选择要清理的备份,单次最多 100 份");
|
|
352
|
+
return launch("manual", selection);
|
|
353
|
+
},
|
|
354
|
+
tick() {
|
|
355
|
+
const current = policy();
|
|
356
|
+
const clock = localDay(now());
|
|
357
|
+
if (
|
|
358
|
+
!current.enabled ||
|
|
359
|
+
running ||
|
|
360
|
+
backup?.running ||
|
|
361
|
+
last()?.day === clock.day ||
|
|
362
|
+
clock.time < current.time
|
|
363
|
+
)
|
|
364
|
+
return false;
|
|
365
|
+
const preview = cleanupPlan(
|
|
366
|
+
backupInventory({ directory, source }),
|
|
367
|
+
current,
|
|
368
|
+
now(),
|
|
369
|
+
);
|
|
370
|
+
if (!preview.items.length) {
|
|
371
|
+
store.save({
|
|
372
|
+
backupCleanupLast: {
|
|
373
|
+
day: clock.day,
|
|
374
|
+
at: now(),
|
|
375
|
+
removed: 0,
|
|
376
|
+
bytes: 0,
|
|
377
|
+
},
|
|
378
|
+
});
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
launch("scheduled")
|
|
382
|
+
.then((result) => {
|
|
383
|
+
store.save({
|
|
384
|
+
backupCleanupLast: {
|
|
385
|
+
day: clock.day,
|
|
386
|
+
at: now(),
|
|
387
|
+
removed: result.removed.length,
|
|
388
|
+
bytes: result.bytes,
|
|
389
|
+
...(result.failures?.length
|
|
390
|
+
? {
|
|
391
|
+
error: "部分备份未清理,请刷新列表后重试",
|
|
392
|
+
failures: result.failures,
|
|
393
|
+
}
|
|
394
|
+
: {}),
|
|
395
|
+
},
|
|
396
|
+
});
|
|
397
|
+
log.log(`定时备份整理完成:${result.removed.length} 份`);
|
|
398
|
+
})
|
|
399
|
+
.catch((error) => {
|
|
400
|
+
store.save({
|
|
401
|
+
backupCleanupLast: {
|
|
402
|
+
day: clock.day,
|
|
403
|
+
at: now(),
|
|
404
|
+
removed: 0,
|
|
405
|
+
bytes: 0,
|
|
406
|
+
error: error.message,
|
|
407
|
+
},
|
|
408
|
+
});
|
|
409
|
+
log.error(`定时备份整理失败:${error.message}`);
|
|
410
|
+
});
|
|
411
|
+
return true;
|
|
412
|
+
},
|
|
413
|
+
};
|
|
414
|
+
}
|