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.
Files changed (235) hide show
  1. package/.github/SECURITY.md +71 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +250 -0
  4. package/README.md +250 -0
  5. package/bin/luckytri.js +107 -0
  6. package/docs/brand/banner.png +0 -0
  7. package/docs/brand/palette.png +0 -0
  8. package/docs/brand/portrait.png +0 -0
  9. package/docs/en/CHANGELOG.md +113 -0
  10. package/docs/en/architecture.md +152 -0
  11. package/docs/en/chat-style.md +62 -0
  12. package/docs/en/connect.md +63 -0
  13. package/docs/en/guide.md +216 -0
  14. package/docs/en/her-life.md +189 -0
  15. package/docs/en/npm-release.md +25 -0
  16. package/docs/en/plugins.md +82 -0
  17. package/docs/en/recovery.md +28 -0
  18. package/docs/en/time.md +71 -0
  19. package/docs/en/webui.md +73 -0
  20. package/docs/zh/CHANGELOG.md +113 -0
  21. package/docs/zh/architecture.md +152 -0
  22. package/docs/zh/chat-style.md +62 -0
  23. package/docs/zh/connect.md +63 -0
  24. package/docs/zh/guide.md +216 -0
  25. package/docs/zh/her-life.md +189 -0
  26. package/docs/zh/npm-release.md +33 -0
  27. package/docs/zh/plugins.md +82 -0
  28. package/docs/zh/recovery.md +28 -0
  29. package/docs/zh/time.md +71 -0
  30. package/docs/zh/webui.md +73 -0
  31. package/package.json +108 -0
  32. package/plugins/sdk/index.d.ts +155 -0
  33. package/plugins/sdk/testing.js +58 -0
  34. package/plugins/weather/index.js +82 -0
  35. package/plugins/weather/luckytri-plugin.json +29 -0
  36. package/public/app/assets/ChatsPage-C-FcRapR.js +3 -0
  37. package/public/app/assets/ChatsPage-DfyPCS9N.css +1 -0
  38. package/public/app/assets/Empty-CpP5kQHH.js +2 -0
  39. package/public/app/assets/Empty-DmUB2-Bk.css +1 -0
  40. package/public/app/assets/Field-D4gY-INU.js +1 -0
  41. package/public/app/assets/HeartPage-Bft9wZp5.css +1 -0
  42. package/public/app/assets/HeartPage-CPy_thQd.js +1 -0
  43. package/public/app/assets/LifePage-BUi5euBF.css +1 -0
  44. package/public/app/assets/LifePage-CxWvwmSf.js +1 -0
  45. package/public/app/assets/MemoryPage-DC4rhQ68.js +1 -0
  46. package/public/app/assets/MemoryPage-cZvXfkXb.css +1 -0
  47. package/public/app/assets/NaturePage-CTXHCE2D.css +1 -0
  48. package/public/app/assets/NaturePage-IvYw04Zq.js +3 -0
  49. package/public/app/assets/PeoplePage-BmUxkrOU.css +1 -0
  50. package/public/app/assets/PeoplePage-Cqefm9-q.js +1 -0
  51. package/public/app/assets/PluginsPage-DKSaKvXb.js +2 -0
  52. package/public/app/assets/PluginsPage-HyBe5D8w.css +1 -0
  53. package/public/app/assets/SystemPage-CAMPoYqM.css +1 -0
  54. package/public/app/assets/SystemPage-CJmtJkrK.js +1 -0
  55. package/public/app/assets/TimePage-BOms_n4I.css +1 -0
  56. package/public/app/assets/TimePage-Cw44inM4.js +3 -0
  57. package/public/app/assets/formatters-ZmW_xFHw.js +1 -0
  58. package/public/app/assets/index-BheRW-1t.js +4 -0
  59. package/public/app/assets/index-YDz1ree1.css +1 -0
  60. package/public/app/assets/knowledge-DG0e0uKw.js +1 -0
  61. package/public/app/assets/liquid-garden-IMoHBwzc.png +0 -0
  62. package/public/app/assets/luckytri-home-95QKeMtc.png +0 -0
  63. package/public/app/assets/media-BzPDBm7e.js +1 -0
  64. package/public/app/index.html +27 -0
  65. package/public/guide.en.html +1053 -0
  66. package/public/guide.html +893 -0
  67. package/public/plugin-kit/v1/bridge.js +30 -0
  68. package/public/plugin-kit/v1/kit.css +14 -0
  69. package/public/tutorial.en.md +214 -0
  70. package/public/tutorial.md +214 -0
  71. package/scripts/backup.js +311 -0
  72. package/scripts/browser.js +41 -0
  73. package/scripts/launch.js +94 -0
  74. package/scripts/plugin.js +150 -0
  75. package/scripts/proxy-config.js +167 -0
  76. package/scripts/recover.js +26 -0
  77. package/scripts/runtime.js +25 -0
  78. package/scripts/service.js +47 -0
  79. package/scripts/setup.js +50 -0
  80. package/scripts/start-server.js +41 -0
  81. package/scripts/stop.js +36 -0
  82. package/server/app.js +96 -0
  83. package/server/channels/adapters.js +27 -0
  84. package/server/channels/contract.js +57 -0
  85. package/server/channels/hub.js +165 -0
  86. package/server/channels/index.js +25 -0
  87. package/server/channels/onebot/adapter.js +288 -0
  88. package/server/channels/onebot/index.js +336 -0
  89. package/server/channels/onebot/token.js +3 -0
  90. package/server/channels/qqbot/adapter.js +253 -0
  91. package/server/channels/qqbot/api.js +199 -0
  92. package/server/channels/qqbot/credentials.js +11 -0
  93. package/server/channels/qqbot/gateway.js +274 -0
  94. package/server/channels/qqbot/index.js +389 -0
  95. package/server/channels/segments.js +40 -0
  96. package/server/channels/session-key.js +153 -0
  97. package/server/channels/state.js +42 -0
  98. package/server/core/api.js +564 -0
  99. package/server/core/capabilities.js +208 -0
  100. package/server/core/context-builder.js +288 -0
  101. package/server/core/context-compactor.js +454 -0
  102. package/server/core/conversation-cues.js +325 -0
  103. package/server/core/conversation-manager.js +87 -0
  104. package/server/core/events.js +60 -0
  105. package/server/core/feedback.js +8 -0
  106. package/server/core/group-style.js +72 -0
  107. package/server/core/image-preprocessor.js +208 -0
  108. package/server/core/initiative-context.js +66 -0
  109. package/server/core/input-budget.js +32 -0
  110. package/server/core/local-demo.js +98 -0
  111. package/server/core/message-manager.js +118 -0
  112. package/server/core/message-scheduler.js +78 -0
  113. package/server/core/model-json.js +190 -0
  114. package/server/core/model-manager.js +1213 -0
  115. package/server/core/model-presets.js +900 -0
  116. package/server/core/name-call.js +29 -0
  117. package/server/core/net-guard.js +49 -0
  118. package/server/core/network.js +157 -0
  119. package/server/core/orchestrator.js +569 -0
  120. package/server/core/perceivers.js +91 -0
  121. package/server/core/person-name.js +22 -0
  122. package/server/core/persona-manager.js +243 -0
  123. package/server/core/reply-delivery.js +393 -0
  124. package/server/core/reply-target-resolver.js +50 -0
  125. package/server/core/repository.js +293 -0
  126. package/server/core/response-generator.js +50 -0
  127. package/server/core/response-validator.js +508 -0
  128. package/server/core/retired-prompts.js +51 -0
  129. package/server/core/sessions.js +109 -0
  130. package/server/core/speaker-names.js +92 -0
  131. package/server/core/topic-tracker.js +65 -0
  132. package/server/core/turn-processor.js +630 -0
  133. package/server/core/turn.js +236 -0
  134. package/server/core/vision-manager.js +633 -0
  135. package/server/http.js +18 -0
  136. package/server/i18n/decisions.js +206 -0
  137. package/server/i18n/errors.js +497 -0
  138. package/server/i18n/index.js +144 -0
  139. package/server/i18n/labels.js +653 -0
  140. package/server/i18n/models.js +111 -0
  141. package/server/index.js +102 -0
  142. package/server/knowledge/api.js +342 -0
  143. package/server/knowledge/embedding-profile.js +114 -0
  144. package/server/knowledge/index.js +13 -0
  145. package/server/knowledge/manager.js +386 -0
  146. package/server/knowledge/retrieval.js +93 -0
  147. package/server/knowledge/schema.js +154 -0
  148. package/server/knowledge/vector-index.js +90 -0
  149. package/server/mind/affect.js +265 -0
  150. package/server/mind/anticipations.js +507 -0
  151. package/server/mind/api.js +703 -0
  152. package/server/mind/attention.js +200 -0
  153. package/server/mind/bonds.js +558 -0
  154. package/server/mind/budget.js +152 -0
  155. package/server/mind/clock.js +83 -0
  156. package/server/mind/context-selection.js +61 -0
  157. package/server/mind/continuity.js +562 -0
  158. package/server/mind/conversation-origin.js +175 -0
  159. package/server/mind/day-planner.js +324 -0
  160. package/server/mind/days.js +210 -0
  161. package/server/mind/evidence-read.js +45 -0
  162. package/server/mind/evidence.js +148 -0
  163. package/server/mind/faces.js +138 -0
  164. package/server/mind/guard.js +60 -0
  165. package/server/mind/index.js +445 -0
  166. package/server/mind/initiative.js +333 -0
  167. package/server/mind/life/activities.js +21 -0
  168. package/server/mind/life/context.js +309 -0
  169. package/server/mind/life/diary.js +786 -0
  170. package/server/mind/life/growth.js +252 -0
  171. package/server/mind/life/index.js +1049 -0
  172. package/server/mind/life/presence.js +305 -0
  173. package/server/mind/meetings.js +1069 -0
  174. package/server/mind/memory-policy.js +48 -0
  175. package/server/mind/memory.js +888 -0
  176. package/server/mind/nature.js +262 -0
  177. package/server/mind/novelty.js +19 -0
  178. package/server/mind/observations.js +84 -0
  179. package/server/mind/own-day.js +324 -0
  180. package/server/mind/own-voice.js +318 -0
  181. package/server/mind/periods.js +118 -0
  182. package/server/mind/reading.js +120 -0
  183. package/server/mind/salience.js +201 -0
  184. package/server/mind/schema.js +562 -0
  185. package/server/mind/self.js +484 -0
  186. package/server/mind/senses.js +53 -0
  187. package/server/mind/thoughts.js +274 -0
  188. package/server/mind/time/activity-clock.js +196 -0
  189. package/server/mind/time/agenda.js +242 -0
  190. package/server/mind/time/api.js +200 -0
  191. package/server/mind/time/attention.js +34 -0
  192. package/server/mind/time/availability.js +69 -0
  193. package/server/mind/time/commitment-review.js +198 -0
  194. package/server/mind/time/delivery-links.js +130 -0
  195. package/server/mind/time/executor.js +512 -0
  196. package/server/mind/time/experiences.js +128 -0
  197. package/server/mind/time/games.js +562 -0
  198. package/server/mind/time/index.js +739 -0
  199. package/server/mind/time/intent.js +166 -0
  200. package/server/mind/time/kinds.js +171 -0
  201. package/server/mind/time/model-material.js +77 -0
  202. package/server/mind/time/plugin-activity.js +207 -0
  203. package/server/mind/time/presentation.js +51 -0
  204. package/server/mind/time/schedule.js +83 -0
  205. package/server/mind/time/schema.js +84 -0
  206. package/server/mind/time/search.js +383 -0
  207. package/server/mind/time/sharing.js +472 -0
  208. package/server/mind/time/task-links.js +311 -0
  209. package/server/mind/time/tasks.js +587 -0
  210. package/server/mind/time/works.js +432 -0
  211. package/server/mind/traits.js +191 -0
  212. package/server/mind/util.js +110 -0
  213. package/server/mind/view.js +273 -0
  214. package/server/paths.js +102 -0
  215. package/server/plugins/api.js +204 -0
  216. package/server/plugins/host.js +967 -0
  217. package/server/plugins/install.js +295 -0
  218. package/server/plugins/manifest.js +201 -0
  219. package/server/plugins/permissions.js +42 -0
  220. package/server/plugins/runner/guard.mjs +36 -0
  221. package/server/plugins/runner/worker.mjs +250 -0
  222. package/server/plugins/schema.js +91 -0
  223. package/server/plugins/zip.js +112 -0
  224. package/server/startup-lock.js +118 -0
  225. package/server/storage/archive.js +241 -0
  226. package/server/storage/backup-cleanup-worker.js +8 -0
  227. package/server/storage/backup-cleanup.js +414 -0
  228. package/server/storage/backup-lock.js +76 -0
  229. package/server/storage/backup-scheduler.js +131 -0
  230. package/server/storage/store.js +199 -0
  231. package/server/studio/display-names.js +138 -0
  232. package/server/studio/management.js +102 -0
  233. package/server/studio/readiness.js +190 -0
  234. package/server/studio/settings.js +236 -0
  235. package/server/version.js +10 -0
@@ -0,0 +1,76 @@
1
+ import {
2
+ closeSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ openSync,
6
+ readFileSync,
7
+ rmSync,
8
+ statSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import { join, resolve } from "node:path";
12
+ import { randomUUID } from "node:crypto";
13
+
14
+ const BUSY = "备份目录正在被使用,请稍后再试";
15
+
16
+ function alive(pid) {
17
+ if (!Number.isInteger(pid) || pid < 1) return false;
18
+ try {
19
+ process.kill(pid, 0);
20
+ return true;
21
+ } catch (error) {
22
+ return error.code !== "ESRCH";
23
+ }
24
+ }
25
+
26
+ export function withBackupLock(directory, run) {
27
+ const root = resolve(directory);
28
+ mkdirSync(root, { recursive: true });
29
+ const file = join(root, ".backup-operation.lock");
30
+ const token = randomUUID();
31
+ let acquired = false;
32
+ for (let attempt = 0; attempt < 2 && !acquired; attempt++) {
33
+ try {
34
+ const fd = openSync(file, "wx");
35
+ let written = false;
36
+ try {
37
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, token }));
38
+ written = true;
39
+ } finally {
40
+ closeSync(fd);
41
+ if (!written) rmSync(file, { force: true });
42
+ }
43
+ acquired = true;
44
+ } catch (error) {
45
+ if (error.code !== "EEXIST") throw error;
46
+ const stat = statSync(file);
47
+ let owner;
48
+ try {
49
+ owner = JSON.parse(readFileSync(file, "utf8"));
50
+ } catch {
51
+ // A process may still be publishing its lock. Never steal a fresh one.
52
+ }
53
+ if (
54
+ (owner && !alive(owner.pid)) ||
55
+ (!owner && Date.now() - stat.mtimeMs > 6 * 3600000)
56
+ ) {
57
+ const current = statSync(file);
58
+ if (current.ino === stat.ino && current.mtimeMs === stat.mtimeMs)
59
+ rmSync(file);
60
+ } else throw Error(BUSY);
61
+ }
62
+ }
63
+ if (!acquired) throw Error(BUSY);
64
+ try {
65
+ return run();
66
+ } finally {
67
+ if (existsSync(file)) {
68
+ try {
69
+ const owner = JSON.parse(readFileSync(file, "utf8"));
70
+ if (owner.token === token) rmSync(file);
71
+ } catch {
72
+ // Leave a lock changed by another process alone.
73
+ }
74
+ }
75
+ }
76
+ }
@@ -0,0 +1,131 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants, setPriority } from "node:os";
3
+ import { fileURLToPath } from "node:url";
4
+ import { runtimePaths } from "../paths.js";
5
+ import {
6
+ autoBackupDue,
7
+ autoBackupOptions,
8
+ backupDirectory,
9
+ listAutoBackups,
10
+ } from "../../scripts/backup.js";
11
+
12
+ const SCRIPT = fileURLToPath(
13
+ new URL("../../scripts/backup.js", import.meta.url),
14
+ );
15
+ const MINUTE = 60000;
16
+ const HOUR = 60 * MINUTE;
17
+
18
+ // Her whole continuity lives in one database file. Once a day a copy is made in
19
+ // a separate process, so a slow disk never stalls a conversation, and only the
20
+ // newest few are kept. `BACKUP_INTERVAL_HOURS=0` turns it off.
21
+ export function createBackupScheduler({
22
+ env = process.env,
23
+ directory = backupDirectory(runtimePaths(env).database, env),
24
+ now = () => Date.now(),
25
+ start = spawn,
26
+ log = console,
27
+ firstCheckDelayMs = 2 * MINUTE,
28
+ checkEveryMs = 10 * MINUTE,
29
+ } = {}) {
30
+ const options = autoBackupOptions(env);
31
+ const source = runtimePaths(env).database;
32
+ let running = null;
33
+ let failures = 0;
34
+ let lastError = null;
35
+ let nextCheck = now() + firstCheckDelayMs;
36
+ return {
37
+ enabled: options.enabled,
38
+ get running() {
39
+ return !!running;
40
+ },
41
+ // What the management page shows: whether her continuity is being kept.
42
+ status() {
43
+ let backups = [];
44
+ try {
45
+ backups = listAutoBackups(directory, { source });
46
+ } catch (error) {
47
+ lastError ||= { at: now(), message: error.message };
48
+ }
49
+ const latest = backups[0];
50
+ return {
51
+ enabled: options.enabled,
52
+ intervalHours: options.intervalMs / HOUR,
53
+ keep: options.keep,
54
+ running: !!running,
55
+ count: backups.length,
56
+ latest: latest
57
+ ? { name: latest.name, at: latest.time, bytes: latest.bytes }
58
+ : null,
59
+ lastError,
60
+ };
61
+ },
62
+ tick() {
63
+ if (!options.enabled || running || now() < nextCheck) return false;
64
+ nextCheck = now() + checkEveryMs;
65
+ let due;
66
+ try {
67
+ due = autoBackupDue(directory, {
68
+ now: now(),
69
+ intervalMs: options.intervalMs,
70
+ source,
71
+ });
72
+ } catch (error) {
73
+ log.error(`检查自动备份失败:${error.message}`);
74
+ return false;
75
+ }
76
+ if (!due) return false;
77
+ const child = start(process.execPath, [SCRIPT, "--auto"], {
78
+ env: {
79
+ ...env,
80
+ LUCKYTRI_HOME: runtimePaths(env).home,
81
+ DB_PATH: source,
82
+ BACKUP_DIR: directory,
83
+ },
84
+ stdio: ["ignore", "pipe", "pipe"],
85
+ windowsHide: true,
86
+ });
87
+ running = child;
88
+ try {
89
+ // Below normal: the conversation keeps the disk and CPU it needs.
90
+ if (child.pid)
91
+ setPriority(child.pid, constants.priority.PRIORITY_BELOW_NORMAL);
92
+ } catch {
93
+ /* Not every platform lets a process lower another's priority. */
94
+ }
95
+ let output = "";
96
+ child.stdout?.on("data", (chunk) => (output += chunk));
97
+ child.stderr?.on("data", (chunk) => (output += chunk));
98
+ const done = (code, error) => {
99
+ if (running !== child) return;
100
+ running = null;
101
+ if (error || code) {
102
+ // A failing disk must not be hammered every few minutes: wait longer
103
+ // after each failure, up to six hours.
104
+ failures++;
105
+ nextCheck = now() + Math.min(6, failures) * HOUR;
106
+ const message = (error?.message || output).trim() || `退出码 ${code}`;
107
+ lastError = { at: now(), message: message.slice(0, 300) };
108
+ log.error(`自动备份失败:${message}`);
109
+ } else {
110
+ failures = 0;
111
+ lastError = null;
112
+ log.log(output.trim() || "自动备份完成");
113
+ }
114
+ };
115
+ child.once("error", (error) => done(1, error));
116
+ child.once("exit", (code) => done(code));
117
+ return true;
118
+ },
119
+ stop() {
120
+ const child = running;
121
+ running = null;
122
+ if (child) {
123
+ try {
124
+ child.kill();
125
+ } catch {
126
+ /* Already gone. */
127
+ }
128
+ }
129
+ },
130
+ };
131
+ }
@@ -0,0 +1,199 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { mkdirSync } from "node:fs";
3
+ import { runtimePaths } from "../paths.js";
4
+ import { dirname } from "node:path";
5
+ import { summarizeGroupStyle } from "../core/group-style.js";
6
+ import { isGroupSession } from "../channels/session-key.js";
7
+ import { NATURE_DEFAULTS } from "../mind/nature.js";
8
+ import { prepareDatabaseMigration } from "./archive.js";
9
+ export function createStore(path = runtimePaths().database) {
10
+ prepareDatabaseMigration(path);
11
+ if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
12
+ const db = new DatabaseSync(path);
13
+ const legacyMessages =
14
+ db
15
+ .prepare(
16
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='messages'",
17
+ )
18
+ .get() &&
19
+ !db
20
+ .prepare("PRAGMA table_info(messages)")
21
+ .all()
22
+ .some((c) => c.name === "is_demo");
23
+ db.exec(`PRAGMA journal_mode=WAL;
24
+ PRAGMA synchronous=FULL;
25
+ PRAGMA busy_timeout=5000;
26
+ CREATE TABLE IF NOT EXISTS settings (id INTEGER PRIMARY KEY, value TEXT NOT NULL);
27
+ CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, name TEXT, kind TEXT, enabled INTEGER DEFAULT 0);
28
+ CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, event_id TEXT UNIQUE, session_id TEXT, user_id TEXT, name TEXT, text TEXT, time INTEGER, role TEXT);
29
+ CREATE TABLE IF NOT EXISTS memories (id INTEGER PRIMARY KEY, user_id TEXT, name TEXT, content TEXT, scope TEXT, source TEXT, time INTEGER);
30
+ CREATE TABLE IF NOT EXISTS decisions (id INTEGER PRIMARY KEY, session_id TEXT, emotion TEXT, reason TEXT, reply TEXT, time INTEGER);
31
+ CREATE TABLE IF NOT EXISTS relations (id INTEGER PRIMARY KEY, user_id TEXT, peer_id TEXT, label TEXT);`);
32
+ // Additive migrations preserve existing workspaces.
33
+ const migrate = (table, column, definition) => {
34
+ if (
35
+ !db
36
+ .prepare(`PRAGMA table_info(${table})`)
37
+ .all()
38
+ .some((c) => c.name === column)
39
+ )
40
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
41
+ };
42
+ migrate("sessions", "cooldown", "INTEGER");
43
+ migrate("sessions", "probability", "REAL");
44
+ migrate("sessions", "archived", "INTEGER NOT NULL DEFAULT 0");
45
+ migrate("messages", "is_demo", "INTEGER NOT NULL DEFAULT 0");
46
+ migrate("decisions", "is_demo", "INTEGER NOT NULL DEFAULT 0");
47
+ db.exec(`
48
+ CREATE TABLE IF NOT EXISTS seen_events (event_id TEXT PRIMARY KEY, time INTEGER NOT NULL);
49
+ CREATE TABLE IF NOT EXISTS send_attempts (id INTEGER PRIMARY KEY, session_id TEXT, is_demo INTEGER, time INTEGER, status TEXT);
50
+ CREATE TABLE IF NOT EXISTS memory_candidates (id INTEGER PRIMARY KEY, user_id TEXT, name TEXT, content TEXT, scope TEXT, source_text TEXT, event_id TEXT UNIQUE, status TEXT DEFAULT 'pending', time INTEGER);
51
+ CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id,is_demo,id);
52
+ CREATE INDEX IF NOT EXISTS idx_memory_user ON memories(user_id,scope);
53
+ CREATE INDEX IF NOT EXISTS idx_attempts_time ON send_attempts(is_demo,time);
54
+ CREATE INDEX IF NOT EXISTS idx_seen_time ON seen_events(time);
55
+ CREATE TABLE IF NOT EXISTS reply_feedback (decision_id INTEGER PRIMARY KEY,tag TEXT NOT NULL,time INTEGER NOT NULL);
56
+ CREATE TABLE IF NOT EXISTS model_checks (id INTEGER PRIMARY KEY,signature TEXT,ok INTEGER,latency INTEGER,time INTEGER,error TEXT);
57
+ `);
58
+ if (legacyMessages) {
59
+ // v0.1 simulator used UUID event IDs; QQ IDs contain colon-separated fields.
60
+ db.exec(`BEGIN IMMEDIATE;
61
+ UPDATE messages SET is_demo=1 WHERE role='user' AND event_id GLOB '????????-????-????-????-????????????';
62
+ UPDATE messages AS bot SET is_demo=COALESCE((SELECT is_demo FROM messages AS human WHERE human.session_id=bot.session_id AND human.role='user' AND human.id<bot.id ORDER BY human.id DESC LIMIT 1),0) WHERE bot.role='assistant';
63
+ UPDATE decisions SET is_demo=1 WHERE reason LIKE '模拟:%';
64
+ INSERT OR IGNORE INTO seen_events(event_id,time) SELECT event_id,time FROM messages WHERE event_id IS NOT NULL;
65
+ INSERT INTO send_attempts(session_id,is_demo,time,status) SELECT session_id,is_demo,time,'confirmed' FROM messages WHERE role='assistant';
66
+ COMMIT;`);
67
+ }
68
+ const defaults = {
69
+ name: "LuckyTri",
70
+ aliases: "LuckyTri,LuckyBot,Lucky",
71
+ persona: NATURE_DEFAULTS.base,
72
+ enabled: true,
73
+ demo: true,
74
+ baseUrl: "https://api.deepseek.com/v1",
75
+ model: "deepseek-chat",
76
+ apiKey: "",
77
+ memoryEnabled: true,
78
+ memoryCandidates: true,
79
+ onebotToken: "",
80
+ channel: "onebot",
81
+ qqbotAppId: "",
82
+ qqbotSecret: "",
83
+ providerPreset: "custom",
84
+ reasoningEffort: "none",
85
+ temperature: 0.85,
86
+ topP: 1,
87
+ maxTokens: 400,
88
+ };
89
+ if (!db.prepare("SELECT id FROM settings").get())
90
+ db.prepare("INSERT INTO settings VALUES (1,?)").run(
91
+ JSON.stringify(defaults),
92
+ );
93
+ else {
94
+ const existing = JSON.parse(
95
+ db.prepare("SELECT value FROM settings WHERE id=1").get().value,
96
+ );
97
+ let migrated = { ...existing };
98
+ if (
99
+ (existing.name === "小满" && existing.aliases === "小满,满满") ||
100
+ existing.name === "Unlucky" ||
101
+ existing.name === "UnLucky"
102
+ )
103
+ migrated = {
104
+ ...migrated,
105
+ name: "LuckyTri",
106
+ aliases: "LuckyTri,LuckyBot,Lucky,Unlucky,UnLucky,小满,满满",
107
+ };
108
+ else if (
109
+ existing.name === "Lucky" ||
110
+ existing.name === "LuckyBot" ||
111
+ existing.name === "LuckyTri" ||
112
+ !existing.name
113
+ )
114
+ migrated = {
115
+ ...migrated,
116
+ name: "LuckyTri",
117
+ aliases: [
118
+ "LuckyTri",
119
+ "LuckyBot",
120
+ "Lucky",
121
+ ...String(existing.aliases || "").split(","),
122
+ ]
123
+ .map((v) => v.trim())
124
+ .filter(Boolean)
125
+ .filter((v, i, all) => all.indexOf(v) === i)
126
+ .join(","),
127
+ };
128
+ const renamedPersona = String(migrated.persona || "").replace(
129
+ /\bLucky\b/g,
130
+ "LuckyTri",
131
+ );
132
+ if (renamedPersona !== migrated.persona)
133
+ migrated = { ...migrated, persona: renamedPersona };
134
+ const shippedPersona = new Set([
135
+ "可爱、乐观、情绪稳定,有一点吐槽欲。像熟悉的群友一样说话,先接住情绪,不急着给建议。",
136
+ "可爱、乐观、情绪稳定,偶尔对事情轻轻吐槽,不挖苦群友。像熟悉的群友一样说话,先接住情绪,不急着给建议。",
137
+ "温暖,有一点自己的脾气和好奇。说话像已经在过日子的人:在意是自己的选择,先接住眼前的事,也留着自己的小事。",
138
+ ]);
139
+ if (shippedPersona.has(migrated.persona))
140
+ migrated = { ...migrated, persona: NATURE_DEFAULTS.base };
141
+ if (JSON.stringify(migrated) !== JSON.stringify(existing))
142
+ db.prepare("UPDATE settings SET value=? WHERE id=1").run(
143
+ JSON.stringify(migrated),
144
+ );
145
+ }
146
+ return {
147
+ db,
148
+ revision: 0,
149
+ settings() {
150
+ return {
151
+ ...defaults,
152
+ ...JSON.parse(
153
+ db.prepare("SELECT value FROM settings WHERE id=1").get().value,
154
+ ),
155
+ };
156
+ },
157
+ save(value) {
158
+ db.prepare("UPDATE settings SET value=? WHERE id=1").run(
159
+ JSON.stringify({ ...this.settings(), ...value }),
160
+ );
161
+ this.revision++;
162
+ },
163
+ context(id, limit = 30, demo = null) {
164
+ return db
165
+ .prepare(
166
+ "SELECT * FROM (SELECT * FROM messages WHERE session_id=? AND (? IS NULL OR is_demo=?) ORDER BY id DESC LIMIT ?) ORDER BY id",
167
+ )
168
+ .all(id, demo, demo, limit);
169
+ },
170
+ groupStyle(id, demo = 0) {
171
+ if (!isGroupSession(id)) return null;
172
+ return summarizeGroupStyle(this.context(id, 200, demo));
173
+ },
174
+ maintenance(now = Date.now()) {
175
+ db.prepare("DELETE FROM seen_events WHERE time<?").run(
176
+ now - 7 * 86400000,
177
+ );
178
+ db.prepare("DELETE FROM send_attempts WHERE time<?").run(now - 86400000);
179
+ db.prepare(
180
+ "DELETE FROM decisions WHERE id NOT IN (SELECT id FROM decisions ORDER BY id DESC LIMIT 10000)",
181
+ ).run();
182
+ db.prepare(
183
+ "DELETE FROM reply_feedback WHERE decision_id NOT IN (SELECT id FROM decisions)",
184
+ ).run();
185
+ },
186
+ log(id, emotion, reason, reply = "", demo = 0) {
187
+ db.prepare(
188
+ "INSERT INTO decisions(session_id,emotion,reason,reply,time,is_demo) VALUES (?,?,?,?,?,?)",
189
+ ).run(
190
+ id,
191
+ String(emotion).slice(0, 30),
192
+ String(reason).slice(0, 300),
193
+ reply,
194
+ Date.now(),
195
+ demo,
196
+ );
197
+ },
198
+ };
199
+ }
@@ -0,0 +1,138 @@
1
+ import { readableName } from "../core/speaker-names.js";
2
+ import { requestedName } from "../core/person-name.js";
3
+ import { parseSessionKey } from "../channels/session-key.js";
4
+
5
+ const cached = new WeakMap();
6
+ function personLabel(value, id) {
7
+ if (
8
+ /^(?:onebot:|group:|private:|(?:群聊|私聊)\s*\d)/.test(String(value || ""))
9
+ )
10
+ return "";
11
+ return readableName(value, id);
12
+ }
13
+
14
+ export function saveAccountNames(db, people, now = Date.now()) {
15
+ const old = db
16
+ .prepare("SELECT value FROM core_config WHERE id='qq-account-names'")
17
+ .get();
18
+ const names = old ? JSON.parse(old.value) : {};
19
+ let changed = 0;
20
+ for (const person of people) {
21
+ const id = String(person?.user_id || "");
22
+ const name = readableName(person?.nickname, id);
23
+ if (!id || !name || names[id]?.name === name) continue;
24
+ names[id] = { name, time: now };
25
+ changed++;
26
+ }
27
+ if (changed)
28
+ db.prepare(
29
+ "INSERT INTO core_config(id,value) VALUES ('qq-account-names',?) ON CONFLICT(id) DO UPDATE SET value=excluded.value,version=version+1",
30
+ ).run(JSON.stringify(names));
31
+ return changed;
32
+ }
33
+
34
+ // Management display only. Private preferred names never enter a group prompt.
35
+ export function displayNames(db, before = Date.now()) {
36
+ const mark = db
37
+ .prepare(
38
+ "SELECT total_changes() changes, (SELECT data_version FROM pragma_data_version) external",
39
+ )
40
+ .get();
41
+ const key = `${mark.changes}:${mark.external}`;
42
+ let facts = cached.get(db);
43
+ if (facts?.key !== key) {
44
+ const known = db
45
+ .prepare("SELECT user_id,name,last_seen FROM mind_people")
46
+ .all();
47
+ const saved = db
48
+ .prepare("SELECT value FROM core_config WHERE id='qq-account-names'")
49
+ .get();
50
+ const accounts = saved ? JSON.parse(saved.value) : {};
51
+ const events = db
52
+ .prepare(
53
+ "SELECT seq,time,json_extract(payload,'$.userId') userId,json_extract(payload,'$.accountName') accountName,json_extract(payload,'$.name') name FROM core_events WHERE role='user' AND COALESCE(json_extract(payload,'$.simulated'),0)=0 AND seq NOT IN (SELECT seq FROM mind_unlived) ORDER BY seq DESC",
54
+ )
55
+ .all();
56
+ const sourceEvent = db.prepare(
57
+ "SELECT time,payload FROM core_events WHERE seq=? AND role='user' AND COALESCE(json_extract(payload,'$.simulated'),0)=0 AND seq NOT IN (SELECT seq FROM mind_unlived)",
58
+ );
59
+ const preferences = [];
60
+ for (const row of db
61
+ .prepare(
62
+ "SELECT subject,content,sources,created,updated,expires FROM core_memories WHERE status='confirmed' ORDER BY updated DESC,rowid DESC",
63
+ )
64
+ .all()) {
65
+ if (!/叫|称呼|名字|昵称/.test(row.content)) continue;
66
+ for (const source of JSON.parse(row.sources || "[]")) {
67
+ const seq = Number(
68
+ typeof source === "object"
69
+ ? source.id
70
+ : String(source).replace(/^m:/, ""),
71
+ );
72
+ const event = sourceEvent.get(seq);
73
+ const message = event ? JSON.parse(event.payload) : null;
74
+ if (!message || String(message.userId) !== row.subject) continue;
75
+ const name = requestedName(message.text);
76
+ if (name) {
77
+ preferences.push({ ...row, name, time: event.time, seq });
78
+ break;
79
+ }
80
+ }
81
+ }
82
+ preferences.sort((a, b) => b.time - a.time || b.seq - a.seq);
83
+ facts = { key, known, accounts, events, preferences };
84
+ cached.set(db, facts);
85
+ }
86
+ const names = new Map(
87
+ facts.known.map((row) => [row.user_id, personLabel(row.name, row.user_id)]),
88
+ );
89
+ const seen = new Set();
90
+ for (const row of facts.events) {
91
+ const id = String(row.userId || "");
92
+ if (row.time > before || seen.has(id)) continue;
93
+ const name = readableName(row.accountName, id);
94
+ if (name && (!facts.accounts[id] || row.time >= facts.accounts[id].time)) {
95
+ names.set(id, name);
96
+ seen.add(id);
97
+ } else if (!names.get(id)) {
98
+ const fallback = personLabel(row.name, id);
99
+ if (fallback) names.set(id, fallback);
100
+ }
101
+ }
102
+ for (const [id, row] of Object.entries(facts.accounts))
103
+ if (row.time <= before && !seen.has(id)) names.set(id, row.name);
104
+ const preferred = new Set();
105
+ for (const row of facts.preferences) {
106
+ if (
107
+ row.created > before ||
108
+ row.time > before ||
109
+ (row.expires && row.expires <= before) ||
110
+ preferred.has(row.subject)
111
+ )
112
+ continue;
113
+ names.set(row.subject, row.name);
114
+ preferred.add(row.subject);
115
+ }
116
+ return names;
117
+ }
118
+
119
+ export function displayPerson(person, names) {
120
+ return {
121
+ ...person,
122
+ name:
123
+ names.get(person.userId) ||
124
+ personLabel(person.name, person.userId) ||
125
+ "未命名的人",
126
+ };
127
+ }
128
+
129
+ export function displaySession(session, names) {
130
+ try {
131
+ const parsed = parseSessionKey(session.id);
132
+ if (parsed.kind === "private" && names.get(parsed.nativeId))
133
+ return { ...session, name: names.get(parsed.nativeId) };
134
+ } catch {
135
+ /* Older custom sessions retain their saved label. */
136
+ }
137
+ return session;
138
+ }
@@ -0,0 +1,102 @@
1
+ import { recordModelCheck, savedConnectionSettings } from "./readiness.js";
2
+ import { FEEDBACK_LABELS } from "../core/feedback.js";
3
+
4
+ function connectionSettings(store, modelId = "") {
5
+ const selected = savedConnectionSettings(store, modelId);
6
+ if (!selected) return null;
7
+ return {
8
+ ...selected,
9
+ profile: {
10
+ ...selected.profile,
11
+ apiKey: selected.profile.apiKey || "",
12
+ maxOutputTokens: Math.min(selected.profile.maxOutputTokens || 256, 256),
13
+ timeoutMs: Math.min(selected.profile.timeoutMs || 25000, 25000),
14
+ },
15
+ };
16
+ }
17
+
18
+ export function mountManagement(app, store, chatSystem) {
19
+ const db = store.db;
20
+ app.post("/api/decisions/:id/feedback", (req, res) => {
21
+ const { tag } = req.body;
22
+ if (
23
+ typeof tag !== "string" ||
24
+ (tag !== "" && !Object.hasOwn(FEEDBACK_LABELS, tag))
25
+ )
26
+ return res.status(400).json({ error: "反馈类型无效" });
27
+ const decision = db
28
+ .prepare("SELECT id FROM decisions WHERE id=? AND reply!=''")
29
+ .get(req.params.id);
30
+ if (!decision)
31
+ return res.status(404).json({ error: "只能评价已发送的回复" });
32
+ if (tag === "")
33
+ db.prepare("DELETE FROM reply_feedback WHERE decision_id=?").run(
34
+ decision.id,
35
+ );
36
+ else
37
+ db.prepare(
38
+ "INSERT INTO reply_feedback(decision_id,tag,time) VALUES (?,?,?) ON CONFLICT(decision_id) DO UPDATE SET tag=excluded.tag,time=excluded.time",
39
+ ).run(decision.id, tag, Date.now());
40
+ store.revision++;
41
+ res.json({ ok: true });
42
+ });
43
+ let testing = false;
44
+ app.post("/api/model/test", async (req, res) => {
45
+ const modelId = req.body?.modelId;
46
+ if (
47
+ modelId !== undefined &&
48
+ (typeof modelId !== "string" || !modelId.trim() || modelId.length > 200)
49
+ )
50
+ return res.status(400).json({ error: "模型 ID 无效" });
51
+ const selected = connectionSettings(store, modelId?.trim() || "");
52
+ if (!selected)
53
+ return res.status(404).json({ error: "找不到这个已保存的模型" });
54
+ if (testing) return res.status(429).json({ error: "连接测试正在进行" });
55
+ testing = true;
56
+ const started = Date.now();
57
+ const { settings, profile, isDefault } = selected;
58
+ try {
59
+ if (!(profile.apiKey || process.env.LLM_API_KEY))
60
+ throw Error("请先配置模型 API Key");
61
+ const result = await chatSystem.models.call(
62
+ profile,
63
+ "test",
64
+ '连通性测试。只输出 JSON 对象 {"ok":true}。',
65
+ { sessionId: "model-connection-test", prompt: "测试连接" },
66
+ { calls: [] },
67
+ );
68
+ if (result.ok !== true) {
69
+ if (isDefault)
70
+ recordModelCheck(
71
+ store,
72
+ settings,
73
+ false,
74
+ Date.now() - started,
75
+ "接口已响应,但 JSON 输出不符合预期",
76
+ );
77
+ return res
78
+ .status(422)
79
+ .json({ error: "接口已响应,但 JSON 输出不符合预期" });
80
+ }
81
+ if (isDefault)
82
+ recordModelCheck(store, settings, true, Date.now() - started);
83
+ return res.json({
84
+ ok: true,
85
+ latency: Date.now() - started,
86
+ model: profile.model,
87
+ profileId: profile.id,
88
+ });
89
+ } catch (error) {
90
+ const message = /timeout|abort/i.test(error.name)
91
+ ? "连接超时,请检查 API 地址或网络"
92
+ : error instanceof TypeError
93
+ ? "无法连接模型服务,请检查地址或网络"
94
+ : error.message;
95
+ if (isDefault)
96
+ recordModelCheck(store, settings, false, Date.now() - started, message);
97
+ res.status(502).json({ error: message });
98
+ } finally {
99
+ testing = false;
100
+ }
101
+ });
102
+ }