luckytri 1.0.4 → 1.0.6

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 (156) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +2 -0
  3. package/README.md +2 -0
  4. package/docs/en/CHANGELOG.md +20 -13
  5. package/docs/en/guide.md +7 -5
  6. package/docs/en/her-life.md +2 -2
  7. package/docs/en/webui.md +1 -1
  8. package/docs/zh/CHANGELOG.md +20 -13
  9. package/docs/zh/guide.md +7 -5
  10. package/docs/zh/her-life.md +2 -2
  11. package/docs/zh/webui.md +1 -1
  12. package/package.json +2 -1
  13. package/public/app/assets/ChatsPage-CFMVozoG.css +1 -0
  14. package/public/app/assets/{ChatsPage-CshdtTzV.js → ChatsPage-DCYMkJ91.js} +2 -2
  15. package/public/app/assets/{Empty-C7yzOBzy.js → Empty-CLyZkxR5.js} +1 -1
  16. package/public/app/assets/{Empty-DmUB2-Bk.css → Empty-DIobYG3x.css} +1 -1
  17. package/public/app/assets/{Field-BjFv4Rfn.js → Field-BpaRwLI_.js} +1 -1
  18. package/public/app/assets/{HeartPage-eqo6ru16.js → HeartPage-BIOMTiwr.js} +1 -1
  19. package/public/app/assets/HeartPage-C-2jvgzF.css +1 -0
  20. package/public/app/assets/{LifePage-CN8GE5NK.js → LifePage-BCgM4JkR.js} +1 -1
  21. package/public/app/assets/LifePage-CG1OHbRK.css +1 -0
  22. package/public/app/assets/MemoryPage-C_Bu4rfb.css +1 -0
  23. package/public/app/assets/{MemoryPage-CCpMN4Wg.js → MemoryPage-vShvRqMt.js} +1 -1
  24. package/public/app/assets/NaturePage-CPZlImT0.css +1 -0
  25. package/public/app/assets/{NaturePage-C0JqdBTR.js → NaturePage-Cy9ptr4G.js} +2 -2
  26. package/public/app/assets/PeoplePage-3RRUITDz.css +1 -0
  27. package/public/app/assets/{PeoplePage-BXGBbO4u.js → PeoplePage-CUZekB2E.js} +1 -1
  28. package/public/app/assets/{PluginsPage-Dksp5AV5.js → PluginsPage-1RM4rmJP.js} +1 -1
  29. package/public/app/assets/{SystemPage-BenIyTvk.css → SystemPage-BI2CB5Ig.css} +1 -1
  30. package/public/app/assets/{SystemPage-Cd7aa8eE.js → SystemPage-BeT5TmIV.js} +1 -1
  31. package/public/app/assets/TimePage-C-guwPk2.css +1 -0
  32. package/public/app/assets/{TimePage-Bs_zImb4.js → TimePage-taTmPMM8.js} +2 -2
  33. package/public/app/assets/{index-BHZcHUMh.css → index-DY5AM0Hz.css} +1 -1
  34. package/public/app/assets/{index-CyRtYxP3.js → index-DdYwC5ZU.js} +3 -3
  35. package/public/app/assets/{knowledge-BJOIyuJo.js → knowledge-DJmfu2KN.js} +1 -1
  36. package/public/app/assets/{media-Bwtx8blz.js → media-BEtnE0Gv.js} +1 -1
  37. package/public/app/assets/{mind-DtTVrW6Z.js → mind-Dtiw0-QK.js} +1 -1
  38. package/public/app/index.html +6 -5
  39. package/public/guide.en.html +11 -3
  40. package/public/guide.html +6 -3
  41. package/public/tutorial.en.md +2 -0
  42. package/public/tutorial.md +2 -0
  43. package/scripts/import-data.js +128 -128
  44. package/scripts/proxy-config.js +167 -167
  45. package/scripts/service-supervisor.js +50 -0
  46. package/scripts/start-server.js +71 -16
  47. package/scripts/update-instance.js +201 -201
  48. package/server/channels/adapters.js +27 -27
  49. package/server/channels/onebot/adapter.js +288 -288
  50. package/server/channels/qqbot/adapter.js +253 -253
  51. package/server/channels/qqbot/api.js +199 -199
  52. package/server/channels/qqbot/credentials.js +11 -11
  53. package/server/channels/qqbot/gateway.js +274 -274
  54. package/server/channels/qqbot/index.js +389 -389
  55. package/server/channels/segments.js +40 -40
  56. package/server/channels/session-key.js +153 -153
  57. package/server/channels/state.js +42 -42
  58. package/server/core/api.js +564 -564
  59. package/server/core/context-builder.js +288 -288
  60. package/server/core/context-compactor.js +454 -454
  61. package/server/core/conversation-cues.js +325 -325
  62. package/server/core/conversation-manager.js +87 -87
  63. package/server/core/feedback.js +8 -8
  64. package/server/core/group-style.js +72 -72
  65. package/server/core/initiative-context.js +66 -66
  66. package/server/core/input-budget.js +32 -32
  67. package/server/core/local-demo.js +98 -98
  68. package/server/core/message-manager.js +118 -118
  69. package/server/core/message-scheduler.js +78 -78
  70. package/server/core/model-json.js +190 -190
  71. package/server/core/model-presets.js +900 -900
  72. package/server/core/name-call.js +29 -29
  73. package/server/core/network.js +157 -157
  74. package/server/core/person-name.js +22 -22
  75. package/server/core/persona-manager.js +2 -1
  76. package/server/core/reply-delivery.js +404 -403
  77. package/server/core/reply-target-resolver.js +50 -50
  78. package/server/core/response-generator.js +50 -50
  79. package/server/core/response-validator.js +14 -2
  80. package/server/core/retired-prompts.js +51 -51
  81. package/server/core/sessions.js +109 -109
  82. package/server/core/speaker-names.js +92 -92
  83. package/server/core/topic-tracker.js +65 -65
  84. package/server/http.js +18 -18
  85. package/server/i18n/decisions.js +209 -206
  86. package/server/i18n/errors.js +4 -0
  87. package/server/i18n/index.js +144 -144
  88. package/server/i18n/models.js +111 -111
  89. package/server/knowledge/api.js +342 -342
  90. package/server/knowledge/embedding-profile.js +114 -114
  91. package/server/knowledge/index.js +13 -13
  92. package/server/knowledge/retrieval.js +93 -93
  93. package/server/knowledge/schema.js +158 -158
  94. package/server/knowledge/vector-index.js +90 -90
  95. package/server/mind/affect.js +265 -265
  96. package/server/mind/attention.js +200 -200
  97. package/server/mind/bonds.js +565 -565
  98. package/server/mind/clock.js +83 -83
  99. package/server/mind/continuity.js +562 -562
  100. package/server/mind/conversation-origin.js +175 -175
  101. package/server/mind/days.js +210 -210
  102. package/server/mind/evidence-read.js +45 -45
  103. package/server/mind/faces.js +373 -373
  104. package/server/mind/guard.js +60 -60
  105. package/server/mind/initiative.js +338 -338
  106. package/server/mind/life/activities.js +21 -21
  107. package/server/mind/life/context.js +330 -323
  108. package/server/mind/life/diary.js +20 -0
  109. package/server/mind/life/growth.js +261 -254
  110. package/server/mind/life/index.js +10 -2
  111. package/server/mind/life/presence.js +305 -305
  112. package/server/mind/meetings.js +1069 -1069
  113. package/server/mind/memory-policy.js +48 -48
  114. package/server/mind/memory.js +888 -888
  115. package/server/mind/nature.js +358 -358
  116. package/server/mind/novelty.js +19 -19
  117. package/server/mind/periods.js +118 -118
  118. package/server/mind/reading.js +120 -120
  119. package/server/mind/relationship-context.js +71 -0
  120. package/server/mind/relationships.js +390 -279
  121. package/server/mind/salience.js +201 -201
  122. package/server/mind/schema.js +567 -567
  123. package/server/mind/self.js +484 -484
  124. package/server/mind/thoughts.js +274 -274
  125. package/server/mind/time/agenda.js +242 -242
  126. package/server/mind/time/api.js +200 -200
  127. package/server/mind/time/attention.js +34 -34
  128. package/server/mind/time/delivery-links.js +130 -130
  129. package/server/mind/time/model-material.js +77 -77
  130. package/server/mind/time/presentation.js +51 -51
  131. package/server/mind/time/schedule.js +83 -83
  132. package/server/mind/time/schema.js +84 -84
  133. package/server/mind/time/search.js +383 -383
  134. package/server/mind/time/sharing.js +472 -472
  135. package/server/mind/time/task-links.js +311 -311
  136. package/server/mind/time/works.js +432 -432
  137. package/server/mind/traits.js +191 -191
  138. package/server/mind/view.js +9 -1
  139. package/server/runtime/installation.js +116 -116
  140. package/server/runtime/update-execution.js +2 -1
  141. package/server/runtime/update-manager.js +140 -140
  142. package/server/storage/data-package.js +298 -298
  143. package/server/storage/data-transfer-api.js +50 -50
  144. package/server/storage/data-transfer-worker.js +18 -18
  145. package/server/storage/data-transfer.js +416 -416
  146. package/server/studio/display-names.js +139 -139
  147. package/server/studio/management.js +102 -102
  148. package/server/studio/updates.js +144 -144
  149. package/server/version.js +10 -10
  150. package/public/app/assets/ChatsPage-DfyPCS9N.css +0 -1
  151. package/public/app/assets/HeartPage-Bft9wZp5.css +0 -1
  152. package/public/app/assets/LifePage-BUi5euBF.css +0 -1
  153. package/public/app/assets/MemoryPage-cZvXfkXb.css +0 -1
  154. package/public/app/assets/NaturePage-CHkpb5NK.css +0 -1
  155. package/public/app/assets/PeoplePage-BTU0H1pM.css +0 -1
  156. package/public/app/assets/TimePage-BOms_n4I.css +0 -1
@@ -1,139 +1,139 @@
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
- person.relationship?.name ||
124
- names.get(person.userId) ||
125
- personLabel(person.name, person.userId) ||
126
- "未命名的人",
127
- };
128
- }
129
-
130
- export function displaySession(session, names) {
131
- try {
132
- const parsed = parseSessionKey(session.id);
133
- if (parsed.kind === "private" && names.get(parsed.nativeId))
134
- return { ...session, name: names.get(parsed.nativeId) };
135
- } catch {
136
- /* Older custom sessions retain their saved label. */
137
- }
138
- return session;
139
- }
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
+ person.relationship?.name ||
124
+ names.get(person.userId) ||
125
+ personLabel(person.name, person.userId) ||
126
+ "未命名的人",
127
+ };
128
+ }
129
+
130
+ export function displaySession(session, names) {
131
+ try {
132
+ const parsed = parseSessionKey(session.id);
133
+ if (parsed.kind === "private" && names.get(parsed.nativeId))
134
+ return { ...session, name: names.get(parsed.nativeId) };
135
+ } catch {
136
+ /* Older custom sessions retain their saved label. */
137
+ }
138
+ return session;
139
+ }
@@ -1,102 +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
- }
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
+ }