luckytri 1.0.0 → 1.0.2

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.
Files changed (139) hide show
  1. package/.github/SECURITY.md +4 -4
  2. package/README.en.md +252 -250
  3. package/README.md +252 -250
  4. package/bin/luckytri.js +5 -1
  5. package/docs/en/CHANGELOG.md +8 -0
  6. package/docs/en/connect.md +18 -18
  7. package/docs/en/guide.md +202 -216
  8. package/docs/en/npm-release.md +25 -25
  9. package/docs/zh/CHANGELOG.md +8 -0
  10. package/docs/zh/connect.md +17 -17
  11. package/docs/zh/guide.md +202 -216
  12. package/docs/zh/npm-release.md +33 -33
  13. package/package.json +110 -108
  14. package/plugins/sdk/index.d.ts +155 -155
  15. package/plugins/sdk/testing.js +58 -58
  16. package/plugins/weather/index.js +82 -82
  17. package/plugins/weather/luckytri-plugin.json +29 -29
  18. package/public/app/assets/ChatsPage-BhlJHseG.js +3 -0
  19. package/public/app/assets/Empty-DP6WMGHi.js +2 -0
  20. package/public/app/assets/Field-CtbdqaiB.js +1 -0
  21. package/public/app/assets/HeartPage-32BeTPn2.js +1 -0
  22. package/public/app/assets/LifePage-CxSm0XKI.js +1 -0
  23. package/public/app/assets/MemoryPage-BeKBcPCY.js +1 -0
  24. package/public/app/assets/NaturePage-NEPYl2HS.js +3 -0
  25. package/public/app/assets/PeoplePage-DxtpekwM.js +1 -0
  26. package/public/app/assets/PluginsPage-CVVQwEBI.css +1 -0
  27. package/public/app/assets/PluginsPage-DksEZbUU.js +2 -0
  28. package/public/app/assets/{SystemPage-CAMPoYqM.css → SystemPage-BkRu0Rvx.css} +1 -1
  29. package/public/app/assets/SystemPage-BvzJlHuY.js +1 -0
  30. package/public/app/assets/TimePage-7-awH5XL.js +3 -0
  31. package/public/app/assets/index-4rItIkD-.js +4 -0
  32. package/public/app/assets/{index-YDz1ree1.css → index-DY4e15Kh.css} +1 -1
  33. package/public/app/assets/{knowledge-DG0e0uKw.js → knowledge-C6_HvoyB.js} +1 -1
  34. package/public/app/assets/media-SMfTT-yc.js +1 -0
  35. package/public/app/index.html +3 -3
  36. package/public/guide.en.html +72 -99
  37. package/public/guide.html +44 -86
  38. package/public/tutorial.en.md +25 -39
  39. package/public/tutorial.md +25 -39
  40. package/scripts/backup.js +311 -311
  41. package/scripts/browser.js +41 -41
  42. package/scripts/import-data.js +128 -0
  43. package/scripts/launch.js +101 -94
  44. package/scripts/plugin.js +150 -150
  45. package/scripts/reset-password.js +22 -0
  46. package/scripts/runtime.js +25 -25
  47. package/scripts/service.js +56 -47
  48. package/scripts/setup.js +50 -50
  49. package/scripts/start-server.js +41 -41
  50. package/scripts/stop.js +36 -36
  51. package/server/app.js +112 -96
  52. package/server/auth.js +217 -0
  53. package/server/channels/contract.js +57 -57
  54. package/server/channels/hub.js +165 -165
  55. package/server/channels/index.js +28 -25
  56. package/server/channels/onebot/index.js +335 -336
  57. package/server/channels/onebot/token.js +22 -3
  58. package/server/core/capabilities.js +208 -208
  59. package/server/core/events.js +64 -60
  60. package/server/core/image-preprocessor.js +208 -208
  61. package/server/core/model-manager.js +1213 -1213
  62. package/server/core/net-guard.js +49 -49
  63. package/server/core/orchestrator.js +569 -569
  64. package/server/core/perceivers.js +91 -91
  65. package/server/core/persona-manager.js +243 -243
  66. package/server/core/repository.js +293 -293
  67. package/server/core/response-validator.js +508 -508
  68. package/server/core/turn-processor.js +630 -630
  69. package/server/core/turn.js +236 -236
  70. package/server/core/vision-manager.js +633 -633
  71. package/server/i18n/errors.js +548 -497
  72. package/server/i18n/labels.js +649 -653
  73. package/server/index.js +151 -102
  74. package/server/knowledge/manager.js +386 -386
  75. package/server/knowledge/schema.js +12 -8
  76. package/server/local-access.js +32 -0
  77. package/server/mind/anticipations.js +507 -507
  78. package/server/mind/api.js +703 -703
  79. package/server/mind/budget.js +152 -152
  80. package/server/mind/context-selection.js +61 -61
  81. package/server/mind/day-planner.js +324 -324
  82. package/server/mind/evidence.js +148 -148
  83. package/server/mind/index.js +445 -445
  84. package/server/mind/life/diary.js +786 -786
  85. package/server/mind/life/index.js +1049 -1049
  86. package/server/mind/observations.js +84 -84
  87. package/server/mind/own-day.js +324 -324
  88. package/server/mind/own-voice.js +318 -318
  89. package/server/mind/senses.js +53 -53
  90. package/server/mind/time/activity-clock.js +196 -196
  91. package/server/mind/time/availability.js +69 -69
  92. package/server/mind/time/commitment-review.js +198 -198
  93. package/server/mind/time/executor.js +512 -512
  94. package/server/mind/time/experiences.js +128 -128
  95. package/server/mind/time/games.js +562 -562
  96. package/server/mind/time/index.js +739 -739
  97. package/server/mind/time/intent.js +166 -166
  98. package/server/mind/time/kinds.js +171 -171
  99. package/server/mind/time/plugin-activity.js +207 -207
  100. package/server/mind/time/tasks.js +587 -587
  101. package/server/mind/util.js +110 -110
  102. package/server/mind/view.js +273 -273
  103. package/server/paths.js +102 -102
  104. package/server/plugins/api.js +204 -204
  105. package/server/plugins/host.js +967 -967
  106. package/server/plugins/install.js +295 -295
  107. package/server/plugins/manifest.js +201 -201
  108. package/server/plugins/permissions.js +42 -42
  109. package/server/plugins/runner/guard.mjs +36 -36
  110. package/server/plugins/runner/worker.mjs +250 -250
  111. package/server/plugins/schema.js +91 -91
  112. package/server/plugins/zip.js +112 -112
  113. package/server/startup-lock.js +118 -118
  114. package/server/storage/archive.js +242 -241
  115. package/server/storage/backup-cleanup-worker.js +8 -8
  116. package/server/storage/backup-cleanup.js +415 -414
  117. package/server/storage/backup-lock.js +76 -76
  118. package/server/storage/backup-scheduler.js +131 -131
  119. package/server/storage/data-package.js +298 -0
  120. package/server/storage/data-transfer-api.js +50 -0
  121. package/server/storage/data-transfer-worker.js +18 -0
  122. package/server/storage/data-transfer.js +415 -0
  123. package/server/storage/store.js +202 -199
  124. package/server/studio/readiness.js +181 -190
  125. package/server/studio/settings.js +236 -236
  126. package/public/app/assets/ChatsPage-C-FcRapR.js +0 -3
  127. package/public/app/assets/Empty-CpP5kQHH.js +0 -2
  128. package/public/app/assets/Field-D4gY-INU.js +0 -1
  129. package/public/app/assets/HeartPage-CPy_thQd.js +0 -1
  130. package/public/app/assets/LifePage-CxWvwmSf.js +0 -1
  131. package/public/app/assets/MemoryPage-DC4rhQ68.js +0 -1
  132. package/public/app/assets/NaturePage-IvYw04Zq.js +0 -3
  133. package/public/app/assets/PeoplePage-Cqefm9-q.js +0 -1
  134. package/public/app/assets/PluginsPage-DKSaKvXb.js +0 -2
  135. package/public/app/assets/PluginsPage-HyBe5D8w.css +0 -1
  136. package/public/app/assets/SystemPage-CJmtJkrK.js +0 -1
  137. package/public/app/assets/TimePage-Cw44inM4.js +0 -3
  138. package/public/app/assets/index-BheRW-1t.js +0 -4
  139. package/public/app/assets/media-BzPDBm7e.js +0 -1
@@ -1,295 +1,295 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { lookup } from "node:dns/promises";
3
- import { cpSync, mkdirSync, readdirSync, rmSync } from "node:fs";
4
- import { join } from "node:path";
5
- import { assertPublicHost } from "../core/net-guard.js";
6
- import { VERSION } from "../version.js";
7
- import { readManifest, satisfies, validateManifest } from "./manifest.js";
8
- import { readZip, stripRoot, writeTree } from "./zip.js";
9
-
10
- const DOWNLOAD = 20 * 1024 * 1024;
11
- const STAGED_FOR = 30 * 60000;
12
-
13
- async function download(url, hops = 0, timeoutMs = 30000) {
14
- if (hops > 3) throw new Error("跳转过多");
15
- const parsed = new URL(url);
16
- if (parsed.protocol !== "https:" || parsed.username || parsed.password)
17
- throw new Error("这个地址不能访问");
18
- await assertPublicHost(parsed.hostname, lookup, "这个地址不能访问");
19
- let response;
20
- try {
21
- response = await fetch(parsed, {
22
- redirect: "manual",
23
- headers: { "User-Agent": `LuckyTri/${VERSION}` },
24
- signal: AbortSignal.timeout(timeoutMs),
25
- });
26
- } catch {
27
- throw new Error("插件包下载失败");
28
- }
29
- if ([301, 302, 303, 307, 308].includes(response.status)) {
30
- const next = new URL(response.headers.get("location") || "", parsed).href;
31
- return download(next, hops + 1, timeoutMs);
32
- }
33
- if (!response.ok) throw new Error("插件包下载失败");
34
- const length = Number(response.headers.get("content-length"));
35
- if (length > DOWNLOAD) throw new Error("插件包过大");
36
- const bytes = Buffer.from(await response.arrayBuffer());
37
- if (bytes.length > DOWNLOAD) throw new Error("插件包过大");
38
- return bytes;
39
- }
40
-
41
- function preview(bytes, { source, trusted = false, sha256 = "" }) {
42
- const hash = createHash("sha256").update(bytes).digest("hex");
43
- if (sha256 && sha256.toLowerCase() !== hash)
44
- throw new Error("插件包校验不符");
45
- const files = stripRoot(readZip(bytes));
46
- const manifestFile = files.find(
47
- (file) => file.name === "luckytri-plugin.json",
48
- );
49
- if (!manifestFile) throw new Error("插件清单无法读取");
50
- const manifest = validateManifest(
51
- JSON.parse(manifestFile.bytes.toString("utf8")),
52
- );
53
- return {
54
- token: randomUUID(),
55
- bytes,
56
- files,
57
- manifest,
58
- sha256: hash,
59
- source,
60
- trusted: trusted && !!sha256,
61
- at: Date.now(),
62
- };
63
- }
64
-
65
- export function createInstaller(host) {
66
- const staged = new Map();
67
- function remember(item) {
68
- for (const [token, old] of staged)
69
- if (Date.now() - old.at > STAGED_FOR) staged.delete(token);
70
- staged.set(item.token, item);
71
- return describe(item);
72
- }
73
- function describe(item) {
74
- return {
75
- token: item.token,
76
- trusted: item.trusted,
77
- sha256: item.sha256,
78
- source: item.source,
79
- manifest: item.manifest,
80
- permissions: item.manifest.permissions,
81
- network: item.manifest.network,
82
- };
83
- }
84
- return {
85
- async stageUrl({ url, sha256 = "" }) {
86
- const bytes = await download(url);
87
- return remember(
88
- preview(bytes, { source: "url", sha256, trusted: !!sha256 }),
89
- );
90
- },
91
- async stageRegistry({ url, sha256, id }) {
92
- const bytes = await download(url);
93
- const item = preview(bytes, { source: "market", sha256, trusted: true });
94
- if (id && item.manifest.id !== id) throw new Error("插件包和索引不一致");
95
- return remember(item);
96
- },
97
- async stageGithub(repository) {
98
- const parsed = new URL(repository);
99
- if (parsed.hostname !== "github.com") throw new Error("这个地址不能访问");
100
- const [owner, repo] = parsed.pathname.split("/").filter(Boolean);
101
- if (!owner || !repo) throw new Error("插件仓库地址无效");
102
- const name = repo.replace(/\.git$/, "");
103
- let bytes;
104
- try {
105
- const release = await download(
106
- `https://api.github.com/repos/${owner}/${name}/releases/latest`,
107
- );
108
- const data = JSON.parse(bytesToText(release));
109
- const asset = (data.assets || []).find((item) =>
110
- String(item.name || "").endsWith(".zip"),
111
- );
112
- bytes = await download(asset?.browser_download_url || data.zipball_url);
113
- } catch {
114
- bytes = await download(
115
- `https://codeload.github.com/${owner}/${name}/zip/refs/heads/main`,
116
- );
117
- }
118
- return remember(preview(bytes, { source: "github", trusted: false }));
119
- },
120
- stageUpload(bytes) {
121
- return remember(
122
- preview(Buffer.from(bytes), { source: "upload", trusted: false }),
123
- );
124
- },
125
- stageDir(dir) {
126
- const manifest = readManifest(dir);
127
- const item = {
128
- token: randomUUID(),
129
- dir,
130
- manifest,
131
- sha256: "",
132
- source: "dev",
133
- trusted: false,
134
- at: Date.now(),
135
- };
136
- return remember(item);
137
- },
138
- commit(token) {
139
- const item = staged.get(token);
140
- if (!item || Date.now() - item.at > STAGED_FOR)
141
- throw new Error("这次导入已经过期");
142
- const { manifest } = item;
143
- const target =
144
- item.source === "dev"
145
- ? item.dir
146
- : join(host.dataRoot, manifest.id, manifest.version);
147
- if (item.source !== "dev") {
148
- rmSync(target, { recursive: true, force: true });
149
- mkdirSync(target, { recursive: true });
150
- writeTree(target, item.files);
151
- const checked = readManifest(target);
152
- if (checked.id !== manifest.id || checked.version !== manifest.version)
153
- throw new Error("插件包和索引不一致");
154
- }
155
- host.db
156
- .prepare(
157
- `INSERT INTO plugin_installs(id,version,enabled,state,source,sha256,api,permissions,granted,manifest,path,error,installed,updated)
158
- VALUES (?,?,0,'installed',?,?,?,?,'[]',?,?, '',?,?)
159
- ON CONFLICT(id) DO UPDATE SET version=excluded.version,source=excluded.source,sha256=excluded.sha256,api=excluded.api,permissions=excluded.permissions,manifest=excluded.manifest,path=excluded.path,error='',updated=excluded.updated`,
160
- )
161
- .run(
162
- manifest.id,
163
- manifest.version,
164
- item.source,
165
- item.sha256,
166
- manifest.pluginApi,
167
- JSON.stringify(manifest.permissions),
168
- JSON.stringify(manifest),
169
- target,
170
- host.now(),
171
- host.now(),
172
- );
173
- staged.delete(token);
174
- host.store.revision++;
175
- return host.list().find((row) => row.id === manifest.id);
176
- },
177
- async registries() {
178
- const saved = host.db
179
- .prepare("SELECT id,url FROM plugin_sources ORDER BY created")
180
- .all();
181
- if (saved.length) return saved;
182
- const url =
183
- "https://raw.githubusercontent.com/TodayYueC/LuckyTri-Plugins/main/index.json";
184
- return [{ id: "default", url }];
185
- },
186
- saveRegistry(url) {
187
- const parsed = new URL(url);
188
- if (parsed.protocol !== "https:") throw new Error("这个地址不能访问");
189
- const id = createHash("sha256").update(url).digest("hex").slice(0, 16);
190
- host.db
191
- .prepare(
192
- "INSERT INTO plugin_sources(id,url,created) VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET url=excluded.url",
193
- )
194
- .run(id, url, host.now());
195
- return id;
196
- },
197
- removeRegistry(id) {
198
- host.db.prepare("DELETE FROM plugin_sources WHERE id=?").run(id);
199
- },
200
- async catalog() {
201
- const plugins = [];
202
- let unavailable = false;
203
- for (const source of await this.registries()) {
204
- try {
205
- const bytes = await download(source.url, 0, 8000);
206
- const index = JSON.parse(bytes.toString("utf8"));
207
- if (index.format !== 1 || !Array.isArray(index.plugins))
208
- throw new Error("插件索引无效");
209
- for (const plugin of index.plugins) {
210
- const versions = (plugin.versions || []).filter(
211
- (item) =>
212
- item.pluginApi &&
213
- satisfies(item.luckytri || ">=1.0.0 <2.0.0", VERSION),
214
- );
215
- if (!versions.length) continue;
216
- plugins.push({
217
- ...plugin,
218
- source: source.url,
219
- versions,
220
- latest: versions[versions.length - 1],
221
- });
222
- }
223
- } catch {
224
- unavailable = true;
225
- }
226
- }
227
- return { plugins, unavailable };
228
- },
229
- async remove(id, { data = false } = {}) {
230
- await host.disable(id);
231
- const row = host.db
232
- .prepare("SELECT * FROM plugin_installs WHERE id=?")
233
- .get(id);
234
- if (row?.source !== "builtin" && row?.source !== "dev" && row?.path)
235
- rmSync(row.path, { recursive: true, force: true });
236
- if (data) {
237
- rmSync(join(host.dataRoot, id, "data"), {
238
- recursive: true,
239
- force: true,
240
- });
241
- host.db
242
- .prepare("DELETE FROM plugin_settings WHERE plugin_id=?")
243
- .run(id);
244
- host.db.prepare("DELETE FROM plugin_kv WHERE plugin_id=?").run(id);
245
- }
246
- if (row?.source !== "builtin")
247
- host.db.prepare("DELETE FROM plugin_installs WHERE id=?").run(id);
248
- else
249
- host.db
250
- .prepare(
251
- "UPDATE plugin_installs SET enabled=0,state='installed',granted='[]' WHERE id=?",
252
- )
253
- .run(id);
254
- host.store.revision++;
255
- return host.list();
256
- },
257
- rollback(id) {
258
- const row = host.db
259
- .prepare("SELECT * FROM plugin_installs WHERE id=?")
260
- .get(id);
261
- if (!row) throw new Error("插件不存在");
262
- const parent = join(host.dataRoot, id);
263
- const versions = readdirSync(parent).filter(
264
- (name) => name !== "data" && name !== row.version,
265
- );
266
- const previous = versions.sort().at(-1);
267
- if (!previous) throw new Error("没有可以退回的版本");
268
- const dir = join(parent, previous);
269
- const manifest = readManifest(dir);
270
- host.db
271
- .prepare(
272
- "UPDATE plugin_installs SET version=?,path=?,manifest=?,permissions=?,updated=? WHERE id=?",
273
- )
274
- .run(
275
- manifest.version,
276
- dir,
277
- JSON.stringify(manifest),
278
- JSON.stringify(manifest.permissions),
279
- host.now(),
280
- id,
281
- );
282
- host.store.revision++;
283
- return host.list().find((item) => item.id === id);
284
- },
285
- };
286
- }
287
-
288
- function bytesToText(bytes) {
289
- return Buffer.from(bytes).toString("utf8");
290
- }
291
-
292
- export function copyPlugin(from, to) {
293
- mkdirSync(to, { recursive: true });
294
- cpSync(from, to, { recursive: true });
295
- }
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lookup } from "node:dns/promises";
3
+ import { cpSync, mkdirSync, readdirSync, rmSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { assertPublicHost } from "../core/net-guard.js";
6
+ import { VERSION } from "../version.js";
7
+ import { readManifest, satisfies, validateManifest } from "./manifest.js";
8
+ import { readZip, stripRoot, writeTree } from "./zip.js";
9
+
10
+ const DOWNLOAD = 20 * 1024 * 1024;
11
+ const STAGED_FOR = 30 * 60000;
12
+
13
+ async function download(url, hops = 0, timeoutMs = 30000) {
14
+ if (hops > 3) throw new Error("跳转过多");
15
+ const parsed = new URL(url);
16
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password)
17
+ throw new Error("这个地址不能访问");
18
+ await assertPublicHost(parsed.hostname, lookup, "这个地址不能访问");
19
+ let response;
20
+ try {
21
+ response = await fetch(parsed, {
22
+ redirect: "manual",
23
+ headers: { "User-Agent": `LuckyTri/${VERSION}` },
24
+ signal: AbortSignal.timeout(timeoutMs),
25
+ });
26
+ } catch {
27
+ throw new Error("插件包下载失败");
28
+ }
29
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
30
+ const next = new URL(response.headers.get("location") || "", parsed).href;
31
+ return download(next, hops + 1, timeoutMs);
32
+ }
33
+ if (!response.ok) throw new Error("插件包下载失败");
34
+ const length = Number(response.headers.get("content-length"));
35
+ if (length > DOWNLOAD) throw new Error("插件包过大");
36
+ const bytes = Buffer.from(await response.arrayBuffer());
37
+ if (bytes.length > DOWNLOAD) throw new Error("插件包过大");
38
+ return bytes;
39
+ }
40
+
41
+ function preview(bytes, { source, trusted = false, sha256 = "" }) {
42
+ const hash = createHash("sha256").update(bytes).digest("hex");
43
+ if (sha256 && sha256.toLowerCase() !== hash)
44
+ throw new Error("插件包校验不符");
45
+ const files = stripRoot(readZip(bytes));
46
+ const manifestFile = files.find(
47
+ (file) => file.name === "luckytri-plugin.json",
48
+ );
49
+ if (!manifestFile) throw new Error("插件清单无法读取");
50
+ const manifest = validateManifest(
51
+ JSON.parse(manifestFile.bytes.toString("utf8")),
52
+ );
53
+ return {
54
+ token: randomUUID(),
55
+ bytes,
56
+ files,
57
+ manifest,
58
+ sha256: hash,
59
+ source,
60
+ trusted: trusted && !!sha256,
61
+ at: Date.now(),
62
+ };
63
+ }
64
+
65
+ export function createInstaller(host) {
66
+ const staged = new Map();
67
+ function remember(item) {
68
+ for (const [token, old] of staged)
69
+ if (Date.now() - old.at > STAGED_FOR) staged.delete(token);
70
+ staged.set(item.token, item);
71
+ return describe(item);
72
+ }
73
+ function describe(item) {
74
+ return {
75
+ token: item.token,
76
+ trusted: item.trusted,
77
+ sha256: item.sha256,
78
+ source: item.source,
79
+ manifest: item.manifest,
80
+ permissions: item.manifest.permissions,
81
+ network: item.manifest.network,
82
+ };
83
+ }
84
+ return {
85
+ async stageUrl({ url, sha256 = "" }) {
86
+ const bytes = await download(url);
87
+ return remember(
88
+ preview(bytes, { source: "url", sha256, trusted: !!sha256 }),
89
+ );
90
+ },
91
+ async stageRegistry({ url, sha256, id }) {
92
+ const bytes = await download(url);
93
+ const item = preview(bytes, { source: "market", sha256, trusted: true });
94
+ if (id && item.manifest.id !== id) throw new Error("插件包和索引不一致");
95
+ return remember(item);
96
+ },
97
+ async stageGithub(repository) {
98
+ const parsed = new URL(repository);
99
+ if (parsed.hostname !== "github.com") throw new Error("这个地址不能访问");
100
+ const [owner, repo] = parsed.pathname.split("/").filter(Boolean);
101
+ if (!owner || !repo) throw new Error("插件仓库地址无效");
102
+ const name = repo.replace(/\.git$/, "");
103
+ let bytes;
104
+ try {
105
+ const release = await download(
106
+ `https://api.github.com/repos/${owner}/${name}/releases/latest`,
107
+ );
108
+ const data = JSON.parse(bytesToText(release));
109
+ const asset = (data.assets || []).find((item) =>
110
+ String(item.name || "").endsWith(".zip"),
111
+ );
112
+ bytes = await download(asset?.browser_download_url || data.zipball_url);
113
+ } catch {
114
+ bytes = await download(
115
+ `https://codeload.github.com/${owner}/${name}/zip/refs/heads/main`,
116
+ );
117
+ }
118
+ return remember(preview(bytes, { source: "github", trusted: false }));
119
+ },
120
+ stageUpload(bytes) {
121
+ return remember(
122
+ preview(Buffer.from(bytes), { source: "upload", trusted: false }),
123
+ );
124
+ },
125
+ stageDir(dir) {
126
+ const manifest = readManifest(dir);
127
+ const item = {
128
+ token: randomUUID(),
129
+ dir,
130
+ manifest,
131
+ sha256: "",
132
+ source: "dev",
133
+ trusted: false,
134
+ at: Date.now(),
135
+ };
136
+ return remember(item);
137
+ },
138
+ commit(token) {
139
+ const item = staged.get(token);
140
+ if (!item || Date.now() - item.at > STAGED_FOR)
141
+ throw new Error("这次导入已经过期");
142
+ const { manifest } = item;
143
+ const target =
144
+ item.source === "dev"
145
+ ? item.dir
146
+ : join(host.dataRoot, manifest.id, manifest.version);
147
+ if (item.source !== "dev") {
148
+ rmSync(target, { recursive: true, force: true });
149
+ mkdirSync(target, { recursive: true });
150
+ writeTree(target, item.files);
151
+ const checked = readManifest(target);
152
+ if (checked.id !== manifest.id || checked.version !== manifest.version)
153
+ throw new Error("插件包和索引不一致");
154
+ }
155
+ host.db
156
+ .prepare(
157
+ `INSERT INTO plugin_installs(id,version,enabled,state,source,sha256,api,permissions,granted,manifest,path,error,installed,updated)
158
+ VALUES (?,?,0,'installed',?,?,?,?,'[]',?,?, '',?,?)
159
+ ON CONFLICT(id) DO UPDATE SET version=excluded.version,source=excluded.source,sha256=excluded.sha256,api=excluded.api,permissions=excluded.permissions,manifest=excluded.manifest,path=excluded.path,error='',updated=excluded.updated`,
160
+ )
161
+ .run(
162
+ manifest.id,
163
+ manifest.version,
164
+ item.source,
165
+ item.sha256,
166
+ manifest.pluginApi,
167
+ JSON.stringify(manifest.permissions),
168
+ JSON.stringify(manifest),
169
+ target,
170
+ host.now(),
171
+ host.now(),
172
+ );
173
+ staged.delete(token);
174
+ host.store.revision++;
175
+ return host.list().find((row) => row.id === manifest.id);
176
+ },
177
+ async registries() {
178
+ const saved = host.db
179
+ .prepare("SELECT id,url FROM plugin_sources ORDER BY created")
180
+ .all();
181
+ if (saved.length) return saved;
182
+ const url =
183
+ "https://raw.githubusercontent.com/TodayYueC/LuckyTri-Plugins/main/index.json";
184
+ return [{ id: "default", url }];
185
+ },
186
+ saveRegistry(url) {
187
+ const parsed = new URL(url);
188
+ if (parsed.protocol !== "https:") throw new Error("这个地址不能访问");
189
+ const id = createHash("sha256").update(url).digest("hex").slice(0, 16);
190
+ host.db
191
+ .prepare(
192
+ "INSERT INTO plugin_sources(id,url,created) VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET url=excluded.url",
193
+ )
194
+ .run(id, url, host.now());
195
+ return id;
196
+ },
197
+ removeRegistry(id) {
198
+ host.db.prepare("DELETE FROM plugin_sources WHERE id=?").run(id);
199
+ },
200
+ async catalog() {
201
+ const plugins = [];
202
+ let unavailable = false;
203
+ for (const source of await this.registries()) {
204
+ try {
205
+ const bytes = await download(source.url, 0, 8000);
206
+ const index = JSON.parse(bytes.toString("utf8"));
207
+ if (index.format !== 1 || !Array.isArray(index.plugins))
208
+ throw new Error("插件索引无效");
209
+ for (const plugin of index.plugins) {
210
+ const versions = (plugin.versions || []).filter(
211
+ (item) =>
212
+ item.pluginApi &&
213
+ satisfies(item.luckytri || ">=1.0.0 <2.0.0", VERSION),
214
+ );
215
+ if (!versions.length) continue;
216
+ plugins.push({
217
+ ...plugin,
218
+ source: source.url,
219
+ versions,
220
+ latest: versions[versions.length - 1],
221
+ });
222
+ }
223
+ } catch {
224
+ unavailable = true;
225
+ }
226
+ }
227
+ return { plugins, unavailable };
228
+ },
229
+ async remove(id, { data = false } = {}) {
230
+ await host.disable(id);
231
+ const row = host.db
232
+ .prepare("SELECT * FROM plugin_installs WHERE id=?")
233
+ .get(id);
234
+ if (row?.source !== "builtin" && row?.source !== "dev" && row?.path)
235
+ rmSync(row.path, { recursive: true, force: true });
236
+ if (data) {
237
+ rmSync(join(host.dataRoot, id, "data"), {
238
+ recursive: true,
239
+ force: true,
240
+ });
241
+ host.db
242
+ .prepare("DELETE FROM plugin_settings WHERE plugin_id=?")
243
+ .run(id);
244
+ host.db.prepare("DELETE FROM plugin_kv WHERE plugin_id=?").run(id);
245
+ }
246
+ if (row?.source !== "builtin")
247
+ host.db.prepare("DELETE FROM plugin_installs WHERE id=?").run(id);
248
+ else
249
+ host.db
250
+ .prepare(
251
+ "UPDATE plugin_installs SET enabled=0,state='installed',granted='[]' WHERE id=?",
252
+ )
253
+ .run(id);
254
+ host.store.revision++;
255
+ return host.list();
256
+ },
257
+ rollback(id) {
258
+ const row = host.db
259
+ .prepare("SELECT * FROM plugin_installs WHERE id=?")
260
+ .get(id);
261
+ if (!row) throw new Error("插件不存在");
262
+ const parent = join(host.dataRoot, id);
263
+ const versions = readdirSync(parent).filter(
264
+ (name) => name !== "data" && name !== row.version,
265
+ );
266
+ const previous = versions.sort().at(-1);
267
+ if (!previous) throw new Error("没有可以退回的版本");
268
+ const dir = join(parent, previous);
269
+ const manifest = readManifest(dir);
270
+ host.db
271
+ .prepare(
272
+ "UPDATE plugin_installs SET version=?,path=?,manifest=?,permissions=?,updated=? WHERE id=?",
273
+ )
274
+ .run(
275
+ manifest.version,
276
+ dir,
277
+ JSON.stringify(manifest),
278
+ JSON.stringify(manifest.permissions),
279
+ host.now(),
280
+ id,
281
+ );
282
+ host.store.revision++;
283
+ return host.list().find((item) => item.id === id);
284
+ },
285
+ };
286
+ }
287
+
288
+ function bytesToText(bytes) {
289
+ return Buffer.from(bytes).toString("utf8");
290
+ }
291
+
292
+ export function copyPlugin(from, to) {
293
+ mkdirSync(to, { recursive: true });
294
+ cpSync(from, to, { recursive: true });
295
+ }