luckytri 1.0.0 → 1.0.1

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 (133) 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 +192 -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 +192 -216
  12. package/docs/zh/npm-release.md +33 -33
  13. package/package.json +109 -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-B9Odvzfz.js +3 -0
  19. package/public/app/assets/Empty-SkA8PyMo.js +2 -0
  20. package/public/app/assets/Field-BjLhi8pL.js +1 -0
  21. package/public/app/assets/HeartPage-CscKqMsr.js +1 -0
  22. package/public/app/assets/LifePage-BHCmBHlH.js +1 -0
  23. package/public/app/assets/MemoryPage-Bhs2xa1k.js +1 -0
  24. package/public/app/assets/NaturePage-CaPIar_5.js +3 -0
  25. package/public/app/assets/PeoplePage-CuwSSVeX.js +1 -0
  26. package/public/app/assets/PluginsPage-BhVm1SUi.js +2 -0
  27. package/public/app/assets/PluginsPage-CVVQwEBI.css +1 -0
  28. package/public/app/assets/{SystemPage-CAMPoYqM.css → SystemPage-5yYqyUgR.css} +1 -1
  29. package/public/app/assets/SystemPage-Chm5fiGP.js +1 -0
  30. package/public/app/assets/TimePage-BUm4eUzB.js +3 -0
  31. package/public/app/assets/index-BIAdfObg.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-DNDLyN9m.js} +1 -1
  34. package/public/app/assets/media-CKVAvML2.js +1 -0
  35. package/public/app/index.html +3 -3
  36. package/public/guide.en.html +32 -99
  37. package/public/guide.html +21 -86
  38. package/public/tutorial.en.md +15 -39
  39. package/public/tutorial.md +15 -39
  40. package/scripts/backup.js +311 -311
  41. package/scripts/browser.js +41 -41
  42. package/scripts/launch.js +101 -94
  43. package/scripts/plugin.js +150 -150
  44. package/scripts/reset-password.js +22 -0
  45. package/scripts/runtime.js +25 -25
  46. package/scripts/service.js +56 -47
  47. package/scripts/setup.js +50 -50
  48. package/scripts/start-server.js +41 -41
  49. package/scripts/stop.js +36 -36
  50. package/server/app.js +110 -96
  51. package/server/auth.js +217 -0
  52. package/server/channels/contract.js +57 -57
  53. package/server/channels/hub.js +165 -165
  54. package/server/channels/index.js +28 -25
  55. package/server/channels/onebot/index.js +335 -336
  56. package/server/channels/onebot/token.js +22 -3
  57. package/server/core/capabilities.js +208 -208
  58. package/server/core/events.js +64 -60
  59. package/server/core/image-preprocessor.js +208 -208
  60. package/server/core/model-manager.js +1213 -1213
  61. package/server/core/net-guard.js +49 -49
  62. package/server/core/orchestrator.js +569 -569
  63. package/server/core/perceivers.js +91 -91
  64. package/server/core/persona-manager.js +243 -243
  65. package/server/core/repository.js +293 -293
  66. package/server/core/response-validator.js +508 -508
  67. package/server/core/turn-processor.js +630 -630
  68. package/server/core/turn.js +236 -236
  69. package/server/core/vision-manager.js +633 -633
  70. package/server/i18n/errors.js +512 -497
  71. package/server/i18n/labels.js +649 -653
  72. package/server/index.js +107 -102
  73. package/server/knowledge/manager.js +386 -386
  74. package/server/local-access.js +32 -0
  75. package/server/mind/anticipations.js +507 -507
  76. package/server/mind/api.js +703 -703
  77. package/server/mind/budget.js +152 -152
  78. package/server/mind/context-selection.js +61 -61
  79. package/server/mind/day-planner.js +324 -324
  80. package/server/mind/evidence.js +148 -148
  81. package/server/mind/index.js +445 -445
  82. package/server/mind/life/diary.js +786 -786
  83. package/server/mind/life/index.js +1049 -1049
  84. package/server/mind/observations.js +84 -84
  85. package/server/mind/own-day.js +324 -324
  86. package/server/mind/own-voice.js +318 -318
  87. package/server/mind/senses.js +53 -53
  88. package/server/mind/time/activity-clock.js +196 -196
  89. package/server/mind/time/availability.js +69 -69
  90. package/server/mind/time/commitment-review.js +198 -198
  91. package/server/mind/time/executor.js +512 -512
  92. package/server/mind/time/experiences.js +128 -128
  93. package/server/mind/time/games.js +562 -562
  94. package/server/mind/time/index.js +739 -739
  95. package/server/mind/time/intent.js +166 -166
  96. package/server/mind/time/kinds.js +171 -171
  97. package/server/mind/time/plugin-activity.js +207 -207
  98. package/server/mind/time/tasks.js +587 -587
  99. package/server/mind/util.js +110 -110
  100. package/server/mind/view.js +273 -273
  101. package/server/paths.js +102 -102
  102. package/server/plugins/api.js +204 -204
  103. package/server/plugins/host.js +967 -967
  104. package/server/plugins/install.js +295 -295
  105. package/server/plugins/manifest.js +201 -201
  106. package/server/plugins/permissions.js +42 -42
  107. package/server/plugins/runner/guard.mjs +36 -36
  108. package/server/plugins/runner/worker.mjs +250 -250
  109. package/server/plugins/schema.js +91 -91
  110. package/server/plugins/zip.js +112 -112
  111. package/server/startup-lock.js +118 -118
  112. package/server/storage/archive.js +241 -241
  113. package/server/storage/backup-cleanup-worker.js +8 -8
  114. package/server/storage/backup-cleanup.js +414 -414
  115. package/server/storage/backup-lock.js +76 -76
  116. package/server/storage/backup-scheduler.js +131 -131
  117. package/server/storage/store.js +199 -199
  118. package/server/studio/readiness.js +181 -190
  119. package/server/studio/settings.js +236 -236
  120. package/public/app/assets/ChatsPage-C-FcRapR.js +0 -3
  121. package/public/app/assets/Empty-CpP5kQHH.js +0 -2
  122. package/public/app/assets/Field-D4gY-INU.js +0 -1
  123. package/public/app/assets/HeartPage-CPy_thQd.js +0 -1
  124. package/public/app/assets/LifePage-CxWvwmSf.js +0 -1
  125. package/public/app/assets/MemoryPage-DC4rhQ68.js +0 -1
  126. package/public/app/assets/NaturePage-IvYw04Zq.js +0 -3
  127. package/public/app/assets/PeoplePage-Cqefm9-q.js +0 -1
  128. package/public/app/assets/PluginsPage-DKSaKvXb.js +0 -2
  129. package/public/app/assets/PluginsPage-HyBe5D8w.css +0 -1
  130. package/public/app/assets/SystemPage-CJmtJkrK.js +0 -1
  131. package/public/app/assets/TimePage-Cw44inM4.js +0 -3
  132. package/public/app/assets/index-BheRW-1t.js +0 -4
  133. package/public/app/assets/media-BzPDBm7e.js +0 -1
@@ -1,47 +1,56 @@
1
- import { runtimePaths } from "../server/paths.js";
2
-
3
- export function serviceUrl(env = process.env) {
4
- const port = Number(env.PORT || 3210);
5
- if (!Number.isInteger(port) || port < 1 || port > 65535)
6
- throw Error("PORT 必须是 1–65535 / PORT must be between 1 and 65535");
7
- const raw = env.HOST || "127.0.0.1";
8
- const host = raw === "0.0.0.0" ? "127.0.0.1" : raw === "::" ? "::1" : raw;
9
- return new URL(`http://${host.includes(":") ? `[${host}]` : host}:${port}`)
10
- .origin;
11
- }
12
-
13
- export const serviceHeaders = () => ({
14
- "Content-Type": "application/json",
15
- Authorization: `Bearer ${process.env.ADMIN_TOKEN || ""}`,
16
- });
17
-
18
- export async function running({ base = serviceUrl(), lenient = false } = {}) {
19
- let response;
20
- try {
21
- response = await fetch(base + "/api/service/status", {
22
- headers: serviceHeaders(),
23
- signal: AbortSignal.timeout(1500),
24
- });
25
- } catch (error) {
26
- if (lenient || error.cause?.code === "ECONNREFUSED") return false;
27
- throw Error("无法确认端口状态,请检查服务或网络;未重复启动。");
28
- }
29
- if (!response.ok)
30
- throw Error("端口已被占用或管理令牌不匹配,请检查本机配置。");
31
- let info;
32
- try {
33
- info = await response.json();
34
- } catch {
35
- throw Error("此端口运行的不是 LuckyTri。");
36
- }
37
- const paths = runtimePaths();
38
- const normalize = (value) =>
39
- process.platform === "win32" ? value.toLowerCase() : value;
40
- if (
41
- !["luckytri", "luckybot", "lucky", "xiaoman"].includes(info.app) ||
42
- typeof (info.home ?? info.workspace) !== "string" ||
43
- normalize(info.home ?? info.workspace) !== normalize(paths.home)
44
- )
45
- throw Error("此端口已被其他实例占用,未操作任何进程。");
46
- return true;
47
- }
1
+ import { runtimePaths } from "../server/paths.js";
2
+ import { localServiceKey } from "../server/local-access.js";
3
+ let legacy = false;
4
+
5
+ export function serviceUrl(env = process.env) {
6
+ const port = Number(env.PORT || 3210);
7
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
8
+ throw Error("PORT 必须是 1–65535 / PORT must be between 1 and 65535");
9
+ const raw = env.HOST || "127.0.0.1";
10
+ const host = raw === "0.0.0.0" ? "127.0.0.1" : raw === "::" ? "::1" : raw;
11
+ return new URL(`http://${host.includes(":") ? `[${host}]` : host}:${port}`)
12
+ .origin;
13
+ }
14
+
15
+ export const serviceHeaders = () => ({
16
+ "Content-Type": "application/json",
17
+ Authorization: `Bearer ${legacy ? process.env.ADMIN_TOKEN : localServiceKey()}`,
18
+ });
19
+
20
+ export async function running({ base = serviceUrl(), lenient = false } = {}) {
21
+ let response;
22
+ try {
23
+ response = await fetch(base + "/api/service/status", {
24
+ headers: serviceHeaders(),
25
+ signal: AbortSignal.timeout(1500),
26
+ });
27
+ } catch (error) {
28
+ if (lenient || error.cause?.code === "ECONNREFUSED") {
29
+ legacy = false;
30
+ return false;
31
+ }
32
+ throw Error("无法确认端口状态,请检查服务或网络;未重复启动。");
33
+ }
34
+ if (response.status === 401 && !legacy && process.env.ADMIN_TOKEN) {
35
+ // Allow the new CLI to gracefully stop a still-running 1.0.0 instance.
36
+ legacy = true;
37
+ return running({ base, lenient });
38
+ }
39
+ if (!response.ok) throw Error("端口已被占用或不是当前实例,请检查本机配置。");
40
+ let info;
41
+ try {
42
+ info = await response.json();
43
+ } catch {
44
+ throw Error("此端口运行的不是 LuckyTri。");
45
+ }
46
+ const paths = runtimePaths();
47
+ const normalize = (value) =>
48
+ process.platform === "win32" ? value.toLowerCase() : value;
49
+ if (
50
+ !["luckytri", "luckybot", "lucky", "xiaoman"].includes(info.app) ||
51
+ typeof (info.home ?? info.workspace) !== "string" ||
52
+ normalize(info.home ?? info.workspace) !== normalize(paths.home)
53
+ )
54
+ throw Error("此端口已被其他实例占用,未操作任何进程。");
55
+ return info;
56
+ }
package/scripts/setup.js CHANGED
@@ -1,50 +1,50 @@
1
- import { randomBytes } from "node:crypto";
2
- import { mkdirSync, writeFileSync } from "node:fs";
3
- import { resolve } from "node:path";
4
- import { pathToFileURL } from "node:url";
5
- import { runtimePaths } from "../server/paths.js";
6
-
7
- export function initializeEnvironment(directory = runtimePaths().home) {
8
- mkdirSync(directory, { recursive: true, mode: 0o700 });
9
- const file = resolve(directory, ".env");
10
- const token = () => randomBytes(32).toString("hex");
11
- const content = [
12
- "# LuckyTri 本机配置。修改后重启服务,不要公开此文件。",
13
- "# LuckyTri local configuration. Restart after editing and never share this file.",
14
- "HOST=127.0.0.1",
15
- "PORT=3210",
16
- `ADMIN_TOKEN=${token()}`,
17
- "",
18
- "# 连接 QQ 的方式二选一,也可以在管理界面「连接 QQ」里选择。",
19
- "# Pick one way to connect QQ; it can also be chosen in the studio under Connect QQ.",
20
- "# LUCKYTRI_CHANNEL=onebot # onebot | qqbot;设置后界面里不能再改 / locks the choice when set",
21
- "",
22
- "# OneBot 11",
23
- `ONEBOT_TOKEN=${token()}`,
24
- "",
25
- "# QQ 官方机器人 / QQ official bot",
26
- "# QQBOT_APP_ID=",
27
- "# QQBOT_APP_SECRET=",
28
- "",
29
- "LLM_API_KEY=",
30
- "",
31
- ].join("\n");
32
- try {
33
- writeFileSync(file, content, { flag: "wx", mode: 0o600 });
34
- return true;
35
- } catch (error) {
36
- if (error.code === "EEXIST") return false;
37
- throw error;
38
- }
39
- }
40
- if (
41
- process.argv[1] &&
42
- import.meta.url === pathToFileURL(resolve(process.argv[1])).href
43
- ) {
44
- const created = initializeEnvironment();
45
- console.log(
46
- created
47
- ? "已生成 .env 与两枚不同的随机令牌。请在本机编辑器中查看,修改后重启服务。\nCreated .env with two different random tokens. Open it in a local editor and restart after changes."
48
- : "已有 .env,已保留原文件,不覆盖任何配置。\nA .env already exists and was left untouched.",
49
- );
50
- }
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { runtimePaths } from "../server/paths.js";
5
+
6
+ export function initializeEnvironment(directory = runtimePaths().home) {
7
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
8
+ const file = resolve(directory, ".env");
9
+ const content = [
10
+ "# LuckyTri 本机配置。修改后重启服务,不要公开此文件。",
11
+ "# LuckyTri local configuration. Restart after editing and never share this file.",
12
+ "HOST=127.0.0.1",
13
+ "PORT=3210",
14
+ "# 首次打开管理台时设置一个管理密码。",
15
+ "# Set your management password on the first visit to the studio.",
16
+ "",
17
+ "# 连接 QQ 的方式二选一,也可以在管理界面「连接 QQ」里选择。",
18
+ "# Pick one way to connect QQ; it can also be chosen in the studio under Connect QQ.",
19
+ "# LUCKYTRI_CHANNEL=onebot # onebot | qqbot;设置后界面里不能再改 / locks the choice when set",
20
+ "",
21
+ "# OneBot 11",
22
+ "# 本机 OneBot 接入无需单独令牌;远程接入可使用管理密码。",
23
+ "# Local OneBot clients need no separate token; remote clients can use the management password.",
24
+ "",
25
+ "# QQ 官方机器人 / QQ official bot",
26
+ "# QQBOT_APP_ID=",
27
+ "# QQBOT_APP_SECRET=",
28
+ "",
29
+ "LLM_API_KEY=",
30
+ "",
31
+ ].join("\n");
32
+ try {
33
+ writeFileSync(file, content, { flag: "wx", mode: 0o600 });
34
+ return true;
35
+ } catch (error) {
36
+ if (error.code === "EEXIST") return false;
37
+ throw error;
38
+ }
39
+ }
40
+ if (
41
+ process.argv[1] &&
42
+ import.meta.url === pathToFileURL(resolve(process.argv[1])).href
43
+ ) {
44
+ const created = initializeEnvironment();
45
+ console.log(
46
+ created
47
+ ? "已生成本机配置,首次打开管理台时设置密码。\nCreated local configuration. Set a password on the first visit to the studio."
48
+ : "已有 .env,已保留原文件,不覆盖任何配置。\nA .env already exists and was left untouched.",
49
+ );
50
+ }
@@ -1,41 +1,41 @@
1
- import { spawn } from "node:child_process";
2
- import { join } from "node:path";
3
- import { prepareRuntime } from "./runtime.js";
4
- import {
5
- resolveProxyEnvironment,
6
- supportsNodeEnvironmentProxy,
7
- } from "./proxy-config.js";
8
-
9
- const paths = prepareRuntime();
10
- const proxy = await resolveProxyEnvironment(process.env);
11
- if (proxy.enabled && !supportsNodeEnvironmentProxy())
12
- throw new Error(
13
- "系统代理转发需要 Node.js 24.5 或更高版本。请升级 Node.js 后重启 LuckyTri。",
14
- );
15
-
16
- const args = [
17
- ...(proxy.enabled ? ["--use-env-proxy"] : []),
18
- join(paths.package, "server", "index.js"),
19
- ];
20
- const env = { ...process.env, ...proxy.env };
21
- if (proxy.enabled) console.log("已启用系统代理,外部 API 请求将经代理转发。");
22
- else if (proxy.source === "windows-pac-unsupported")
23
- console.log(
24
- "检测到 PAC 自动代理;LuckyTri 暂不解析 PAC,请改用本机 HTTP 代理或配置 HTTPS_PROXY。",
25
- );
26
- else console.log("未检测到系统代理,外部 API 请求将直连。");
27
-
28
- const child = spawn(process.execPath, args, {
29
- cwd: paths.home,
30
- env,
31
- stdio: "inherit",
32
- });
33
- for (const signal of ["SIGINT", "SIGTERM"])
34
- process.on(signal, () => child.kill(signal));
35
- child.once("error", (error) => {
36
- console.error(`LuckyTri 启动失败:${error.message}`);
37
- process.exitCode = 1;
38
- });
39
- child.once("exit", (code, signal) => {
40
- process.exitCode = signal ? 1 : (code ?? 1);
41
- });
1
+ import { spawn } from "node:child_process";
2
+ import { join } from "node:path";
3
+ import { prepareRuntime } from "./runtime.js";
4
+ import {
5
+ resolveProxyEnvironment,
6
+ supportsNodeEnvironmentProxy,
7
+ } from "./proxy-config.js";
8
+
9
+ const paths = prepareRuntime();
10
+ const proxy = await resolveProxyEnvironment(process.env);
11
+ if (proxy.enabled && !supportsNodeEnvironmentProxy())
12
+ throw new Error(
13
+ "系统代理转发需要 Node.js 24.5 或更高版本。请升级 Node.js 后重启 LuckyTri。",
14
+ );
15
+
16
+ const args = [
17
+ ...(proxy.enabled ? ["--use-env-proxy"] : []),
18
+ join(paths.package, "server", "index.js"),
19
+ ];
20
+ const env = { ...process.env, ...proxy.env };
21
+ if (proxy.enabled) console.log("已启用系统代理,外部 API 请求将经代理转发。");
22
+ else if (proxy.source === "windows-pac-unsupported")
23
+ console.log(
24
+ "检测到 PAC 自动代理;LuckyTri 暂不解析 PAC,请改用本机 HTTP 代理或配置 HTTPS_PROXY。",
25
+ );
26
+ else console.log("未检测到系统代理,外部 API 请求将直连。");
27
+
28
+ const child = spawn(process.execPath, args, {
29
+ cwd: paths.home,
30
+ env,
31
+ stdio: "inherit",
32
+ });
33
+ for (const signal of ["SIGINT", "SIGTERM"])
34
+ process.on(signal, () => child.kill(signal));
35
+ child.once("error", (error) => {
36
+ console.error(`LuckyTri 启动失败:${error.message}`);
37
+ process.exitCode = 1;
38
+ });
39
+ child.once("exit", (code, signal) => {
40
+ process.exitCode = signal ? 1 : (code ?? 1);
41
+ });
package/scripts/stop.js CHANGED
@@ -1,36 +1,36 @@
1
- import { prepareRuntime } from "./runtime.js";
2
- import { running, serviceHeaders, serviceUrl } from "./service.js";
3
- import { starting } from "../server/startup-lock.js";
4
- try {
5
- prepareRuntime({ initialize: false });
6
- const base = serviceUrl();
7
- if (!(await running({ base }))) {
8
- console.log("LuckyTri 已经停止 / LuckyTri is already stopped");
9
- } else {
10
- const stopped = await fetch(base + "/api/service/stop", {
11
- method: "POST",
12
- headers: serviceHeaders(),
13
- body: "{}",
14
- signal: AbortSignal.timeout(5000),
15
- });
16
- if (!stopped.ok) throw new Error("服务拒绝停止请求");
17
- let stoppedConfirmed = false;
18
- for (let attempt = 0; attempt < 40; attempt++) {
19
- await new Promise((resolve) => setTimeout(resolve, 150));
20
- if (!(await running({ base, lenient: true })) && !starting()) {
21
- stoppedConfirmed = true;
22
- break;
23
- }
24
- }
25
- if (!stoppedConfirmed)
26
- throw Error("服务仍在停止中,请稍后再检查 / Service is still stopping");
27
- console.log("LuckyTri 已停止 / LuckyTri stopped");
28
- }
29
- } catch (error) {
30
- console.error(
31
- error instanceof TypeError
32
- ? "未连接到 LuckyTri,可能已经停止"
33
- : error.message,
34
- );
35
- process.exitCode = 1;
36
- }
1
+ import { prepareRuntime } from "./runtime.js";
2
+ import { running, serviceHeaders, serviceUrl } from "./service.js";
3
+ import { starting } from "../server/startup-lock.js";
4
+ try {
5
+ prepareRuntime({ initialize: false });
6
+ const base = serviceUrl();
7
+ if (!(await running({ base }))) {
8
+ console.log("LuckyTri 已经停止 / LuckyTri is already stopped");
9
+ } else {
10
+ const stopped = await fetch(base + "/api/service/stop", {
11
+ method: "POST",
12
+ headers: serviceHeaders(),
13
+ body: "{}",
14
+ signal: AbortSignal.timeout(5000),
15
+ });
16
+ if (!stopped.ok) throw new Error("服务拒绝停止请求");
17
+ let stoppedConfirmed = false;
18
+ for (let attempt = 0; attempt < 40; attempt++) {
19
+ await new Promise((resolve) => setTimeout(resolve, 150));
20
+ if (!(await running({ base, lenient: true })) && !starting()) {
21
+ stoppedConfirmed = true;
22
+ break;
23
+ }
24
+ }
25
+ if (!stoppedConfirmed)
26
+ throw Error("服务仍在停止中,请稍后再检查 / Service is still stopping");
27
+ console.log("LuckyTri 已停止 / LuckyTri stopped");
28
+ }
29
+ } catch (error) {
30
+ console.error(
31
+ error instanceof TypeError
32
+ ? "未连接到 LuckyTri,可能已经停止"
33
+ : error.message,
34
+ );
35
+ process.exitCode = 1;
36
+ }
package/server/app.js CHANGED
@@ -1,96 +1,110 @@
1
- import express from "express";
2
- import { existsSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { tokenEqual } from "./http.js";
5
- import { localizeApi } from "./i18n/index.js";
6
- import { mountStudio } from "./studio/settings.js";
7
- import { mountManagement } from "./studio/management.js";
8
- import { mountCore } from "./core/api.js";
9
- import { mountKnowledge } from "./knowledge/api.js";
10
- import { mountEvents } from "./core/events.js";
11
- import { mountMind } from "./mind/api.js";
12
- import { mountPlugins } from "./plugins/api.js";
13
- import { Life } from "./mind/life/index.js";
14
- import { runtimePaths } from "./paths.js";
15
-
16
- export function createApp({ store, chatSystem, runtime, life, plugins }) {
17
- const app = express();
18
- app.use("/api", localizeApi);
19
- app.use("/api", (req, res, next) => {
20
- res.setHeader("Cache-Control", "no-store");
21
- if (
22
- req.headers.origin &&
23
- req.headers.origin !== `${req.protocol}://${req.headers.host}`
24
- )
25
- return res.status(403).json({ error: "不允许跨站访问" });
26
- if (
27
- process.env.ADMIN_TOKEN &&
28
- !tokenEqual(
29
- req.headers.authorization,
30
- `Bearer ${process.env.ADMIN_TOKEN}`,
31
- )
32
- )
33
- return res.status(401).json({ error: "请输入管理令牌" });
34
- next();
35
- });
36
- if (plugins) {
37
- app.post(
38
- "/api/plugins/import/upload",
39
- express.raw({ type: "*/*", limit: "21mb" }),
40
- (req, res) => {
41
- try {
42
- res.json(plugins.install.stageUpload(req.body));
43
- } catch (error) {
44
- res.status(400).json({ error: error.message });
45
- }
46
- },
47
- );
48
- }
49
- app.use(express.json({ limit: "4mb" }));
50
- app.use("/api", (req, res, next) => {
51
- if (
52
- ["POST", "PATCH", "PUT"].includes(req.method) &&
53
- (!req.body || typeof req.body !== "object" || Array.isArray(req.body))
54
- )
55
- return res.status(400).json({ error: "请提交 JSON 对象" });
56
- next();
57
- });
58
- mountStudio(app, store, runtime, chatSystem);
59
- mountManagement(app, store, chatSystem);
60
- mountCore(app, chatSystem);
61
- mountMind(app, chatSystem, life || new Life(chatSystem));
62
- mountKnowledge(app, chatSystem);
63
- mountEvents(app, chatSystem);
64
- mountPlugins(app, plugins);
65
- // Built assets carry a content hash; the page that names them must not be
66
- // cached, or an upgrade leaves the browser asking for files that are gone.
67
- app.use(
68
- "/app",
69
- express.static(join(runtimePaths().public, "app"), {
70
- setHeaders(res, path) {
71
- res.setHeader(
72
- "Cache-Control",
73
- path.endsWith(".html")
74
- ? "no-cache"
75
- : "public, max-age=31536000, immutable",
76
- );
77
- },
78
- }),
79
- );
80
- const studioIndex = join(runtimePaths().public, "app", "index.html");
81
- app.get(["/", "/index.html", "/app", "/app/"], (req, res, next) => {
82
- if (!existsSync(studioIndex)) return next();
83
- res.setHeader("Cache-Control", "no-cache");
84
- res.sendFile(studioIndex);
85
- });
86
- app.use(express.static(runtimePaths().public));
87
- app.use((err, req, res, next) => {
88
- console.error(err.message);
89
- if (err.type === "entity.too.large")
90
- return res.status(413).json({ error: "请求内容过大" });
91
- if (err.type === "entity.parse.failed")
92
- return res.status(400).json({ error: "JSON 格式无效" });
93
- res.status(500).json({ error: "请求失败,请检查输入或服务日志" });
94
- });
95
- return app;
96
- }
1
+ import express from "express";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { createManagementAuth } from "./auth.js";
5
+ import { localizeApi } from "./i18n/index.js";
6
+ import { mountStudio } from "./studio/settings.js";
7
+ import { mountManagement } from "./studio/management.js";
8
+ import { mountCore } from "./core/api.js";
9
+ import { mountKnowledge } from "./knowledge/api.js";
10
+ import { mountEvents } from "./core/events.js";
11
+ import { mountMind } from "./mind/api.js";
12
+ import { mountPlugins } from "./plugins/api.js";
13
+ import { Life } from "./mind/life/index.js";
14
+ import { runtimePaths } from "./paths.js";
15
+
16
+ export function createApp({
17
+ store,
18
+ chatSystem,
19
+ runtime,
20
+ life,
21
+ plugins,
22
+ auth = createManagementAuth(store),
23
+ }) {
24
+ const app = express();
25
+ app.use("/api", localizeApi);
26
+ app.use("/api", (req, res, next) => {
27
+ res.setHeader("Cache-Control", "no-store");
28
+ if (
29
+ req.headers.origin &&
30
+ req.headers.origin !== `${req.protocol}://${req.headers.host}`
31
+ )
32
+ return res.status(403).json({ error: "不允许跨站访问" });
33
+ if (req.headers["sec-fetch-site"] === "cross-site")
34
+ return res.status(403).json({ error: "不允许跨站访问" });
35
+ next();
36
+ });
37
+ app.use(express.json({ limit: "4mb" }));
38
+ const objectBody = (req, res, next) => {
39
+ if (
40
+ ["POST", "PATCH", "PUT"].includes(req.method) &&
41
+ (!req.body || typeof req.body !== "object" || Array.isArray(req.body)) &&
42
+ req.path !== "/plugins/import/upload"
43
+ )
44
+ return res.status(400).json({ error: "请提交 JSON 对象" });
45
+ next();
46
+ };
47
+ app.use("/api/auth", objectBody);
48
+ auth.mount(app);
49
+ app.use("/api", (req, res, next) => {
50
+ if (
51
+ auth.authorized(req) ||
52
+ (["/service/status", "/service/stop"].includes(req.path) &&
53
+ auth.service(req))
54
+ )
55
+ return next();
56
+ res.status(401).json({ error: "请先登录管理台" });
57
+ });
58
+ app.use("/api", objectBody);
59
+ if (plugins) {
60
+ app.post(
61
+ "/api/plugins/import/upload",
62
+ express.raw({ type: "*/*", limit: "21mb" }),
63
+ (req, res) => {
64
+ try {
65
+ res.json(plugins.install.stageUpload(req.body));
66
+ } catch (error) {
67
+ res.status(400).json({ error: error.message });
68
+ }
69
+ },
70
+ );
71
+ }
72
+ mountStudio(app, store, runtime, chatSystem);
73
+ mountManagement(app, store, chatSystem);
74
+ mountCore(app, chatSystem);
75
+ mountMind(app, chatSystem, life || new Life(chatSystem));
76
+ mountKnowledge(app, chatSystem);
77
+ mountEvents(app, chatSystem, auth.authorized);
78
+ mountPlugins(app, plugins);
79
+ // Built assets carry a content hash; the page that names them must not be
80
+ // cached, or an upgrade leaves the browser asking for files that are gone.
81
+ app.use(
82
+ "/app",
83
+ express.static(join(runtimePaths().public, "app"), {
84
+ setHeaders(res, path) {
85
+ res.setHeader(
86
+ "Cache-Control",
87
+ path.endsWith(".html")
88
+ ? "no-cache"
89
+ : "public, max-age=31536000, immutable",
90
+ );
91
+ },
92
+ }),
93
+ );
94
+ const studioIndex = join(runtimePaths().public, "app", "index.html");
95
+ app.get(["/", "/index.html", "/app", "/app/"], (req, res, next) => {
96
+ if (!existsSync(studioIndex)) return next();
97
+ res.setHeader("Cache-Control", "no-cache");
98
+ res.sendFile(studioIndex);
99
+ });
100
+ app.use(express.static(runtimePaths().public));
101
+ app.use((err, req, res, next) => {
102
+ console.error(err.message);
103
+ if (err.type === "entity.too.large")
104
+ return res.status(413).json({ error: "请求内容过大" });
105
+ if (err.type === "entity.parse.failed")
106
+ return res.status(400).json({ error: "JSON 格式无效" });
107
+ res.status(500).json({ error: "请求失败,请检查输入或服务日志" });
108
+ });
109
+ return app;
110
+ }