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,83 @@
1
+ import { localClock } from "../core/conversation-cues.js";
2
+
3
+ export const JUST_NOW = 5 * 60000;
4
+
5
+ export function elapsedLabel(time, now, zone = "Asia/Shanghai") {
6
+ const age = Math.max(0, now - time);
7
+ if (age < JUST_NOW) return "刚才";
8
+ const day = localClock(time, zone).local.slice(0, 10);
9
+ const today = localClock(now, zone).local.slice(0, 10);
10
+ if (day === today) return "今天早些时候";
11
+ if (day === localClock(now - 86400000, zone).local.slice(0, 10))
12
+ return "昨天";
13
+ return age < 7 * 86400000 ? "好几天前" : "很久以前";
14
+ }
15
+
16
+ // Coarse distance in time, the way a person would say it.
17
+ export function agoLabel(ms) {
18
+ const days = Math.floor(Math.max(0, ms) / 86400000);
19
+ if (days < 1) return "今天";
20
+ if (days < 2) return "昨天";
21
+ if (days < 7) return `${days} 天前`;
22
+ if (days < 30) return `${Math.floor(days / 7)} 周前`;
23
+ if (days < 365) return `${Math.floor(days / 30)} 个月前`;
24
+ return `${Math.floor(days / 365)} 年前`;
25
+ }
26
+
27
+ export function topicWeight(
28
+ time,
29
+ now,
30
+ { importance = 0, mentions = 1, open = false } = {},
31
+ ) {
32
+ const halfLife = (open ? 48 : 6) * 3600000 * (1 + Math.min(1, importance));
33
+ return Math.min(
34
+ 1,
35
+ Math.pow(0.5, Math.max(0, now - time) / halfLife) *
36
+ (1 + Math.min(3, mentions - 1) * 0.1),
37
+ );
38
+ }
39
+
40
+ export function timePhase(lastTime, now) {
41
+ if (!lastTime)
42
+ return {
43
+ key: "unfamiliar",
44
+ label: "还未相遇",
45
+ description: "还没有真实聊天,时间暂时没有可以延续的落点。",
46
+ };
47
+ const age = Math.max(0, now - lastTime);
48
+ if (age < 30 * 60000)
49
+ return {
50
+ key: "present",
51
+ label: "仍在对话里",
52
+ description: "刚才的语气和话题仍然清晰,适合自然接着聊。",
53
+ };
54
+ if (age < 3 * 3600000)
55
+ return {
56
+ key: "afterglow",
57
+ label: "留有余韵",
58
+ description: "聊天刚安静下来,刚才没说完的事还会留在注意里。",
59
+ };
60
+ if (age < 12 * 3600000)
61
+ return {
62
+ key: "settled",
63
+ label: "各自生活",
64
+ description: "注意力已经离开即时对话,但重要的事仍可能被想起。",
65
+ };
66
+ if (age < 2 * 86400000)
67
+ return {
68
+ key: "quiet",
69
+ label: "安静了一阵",
70
+ description: "旧话题正在降温,未完成的事情比普通闲聊更容易被想起。",
71
+ };
72
+ if (age < 7 * 86400000)
73
+ return {
74
+ key: "remembering",
75
+ label: "偶尔想起",
76
+ description: "相隔已有几天,熟悉感还在,但重新开口需要具体缘由。",
77
+ };
78
+ return {
79
+ key: "reunion",
80
+ label: "等待重逢",
81
+ description: "已经隔了很久,旧事只保留为背景,新的消息会成为新的相遇。",
82
+ };
83
+ }
@@ -0,0 +1,61 @@
1
+ import { estimateTokens } from "../core/model-manager.js";
2
+ import { interestTerms } from "./attention.js";
3
+
4
+ export const MIND_CONTEXT_TOKEN_CAP = 6000;
5
+
6
+ // One speaker must provide the cue. Shared relevance across two unrelated
7
+ // speakers is not invented by concatenating the room's words.
8
+ export function relevantContext(
9
+ rows,
10
+ { cues = [], limit, pinned = () => false } = {},
11
+ ) {
12
+ const score = (row) => {
13
+ const terms = interestTerms([row.content]);
14
+ const overlap = Math.max(
15
+ 0,
16
+ ...cues.map((cue) => [...terms].filter((term) => cue.has(term)).length),
17
+ );
18
+ return (
19
+ overlap * 4 + Number(row.salience ?? row.importance ?? row.strength ?? 0)
20
+ );
21
+ };
22
+ const fixed = rows.filter(pinned).slice(0, limit);
23
+ return [
24
+ ...fixed,
25
+ ...rows
26
+ .filter((row) => !fixed.includes(row))
27
+ .map((row, order) => ({ row, order, score: score(row) }))
28
+ .sort((a, b) => b.score - a.score || a.order - b.order)
29
+ .slice(0, limit - fixed.length)
30
+ .map((item) => item.row),
31
+ ];
32
+ }
33
+
34
+ // A shared allowance prevents each new module from independently enlarging
35
+ // the prompt. Identity, current people, and exact continuity evidence survive.
36
+ export function boundMindContext(view, cap = MIND_CONTEXT_TOKEN_CAP) {
37
+ const optional = [
38
+ [view.inner, "senses"],
39
+ [view.self, "readLately"],
40
+ [view.self, "lastDiary"],
41
+ [view.inner, "reminded"],
42
+ [view.inner, "onMind"],
43
+ [view.inner, "with"],
44
+ [view.inner, "stood"],
45
+ [view.inner, "heard"],
46
+ [view.inner, "room"],
47
+ [view.inner, "expecting"],
48
+ [view.inner, "will"],
49
+ [view.self, "threads"],
50
+ ];
51
+ for (const [owner, key] of optional) {
52
+ while (
53
+ estimateTokens({ self: view.self, inner: view.inner }) > cap &&
54
+ owner?.[key]
55
+ ) {
56
+ if (Array.isArray(owner[key]) && owner[key].length > 1) owner[key].pop();
57
+ else delete owner[key];
58
+ }
59
+ }
60
+ return view;
61
+ }
@@ -0,0 +1,562 @@
1
+ import {
2
+ parseSessionKey,
3
+ scopedSessionAliases,
4
+ } from "../channels/session-key.js";
5
+ import { lexicalTerms, overlapScore } from "../knowledge/retrieval.js";
6
+ import { interestTerms } from "./attention.js";
7
+ import { elapsedLabel } from "./clock.js";
8
+ import { secretRequest } from "./guard.js";
9
+ import { DAY, hasCredential, messageSeqs, parse, text } from "./util.js";
10
+
11
+ // A wish to remember someone is not necessarily a request about a topic.
12
+ // This cue widens the selection of existing memories; it invents none.
13
+ export function recallIntent(rows = []) {
14
+ return rows.some(
15
+ (row) =>
16
+ row.role !== "assistant" &&
17
+ /你.{0,16}(?:记得|记着|还记|认识我|认得我|认出我|了解我)|(?:我们|咱们).{0,16}(?:相处|聊过|经历|回忆)|(?:对我|关于我).{0,10}(?:印象|了解|记忆)|(?:别的|其他|其它|另一个|之前的).{0,8}(?:群|地方)|别处|以前.{0,8}(?:聊|说过)/.test(
18
+ row.text || "",
19
+ ),
20
+ );
21
+ }
22
+
23
+ function roomKey(session) {
24
+ try {
25
+ return parseSessionKey(session);
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ // Identity and actual shared encounters, rather than another room's entire
32
+ // transcript. The bond ledger survives trace pruning; quoted replies are only
33
+ // included when their recipient and successful delivery can be verified.
34
+ export class Continuity {
35
+ constructor(mind) {
36
+ this.mind = mind;
37
+ this.db = mind.db;
38
+ }
39
+ recall({ session, people = [], cue = [], now = Date.now() }) {
40
+ const current = roomKey(session);
41
+ if (!current) return null;
42
+ const requested = recallIntent(cue);
43
+ const here = new Set(scopedSessionAliases(this.db, session));
44
+ const account =
45
+ current.accountId !== "_"
46
+ ? current.accountId
47
+ : this.db
48
+ .prepare(
49
+ "SELECT account_id FROM core_events WHERE session_id=? AND time<=? AND account_id IS NOT NULL AND account_id!='' ORDER BY seq DESC LIMIT 1",
50
+ )
51
+ .get(session, now)?.account_id;
52
+ const compatible = (room) => {
53
+ const parsed = roomKey(room);
54
+ if (!parsed || parsed.channel !== current.channel) return false;
55
+ const owner =
56
+ parsed.accountId !== "_"
57
+ ? parsed.accountId
58
+ : this.db
59
+ .prepare(
60
+ "SELECT account_id FROM core_events WHERE session_id=? AND time<=? AND account_id IS NOT NULL AND account_id!='' ORDER BY seq DESC LIMIT 1",
61
+ )
62
+ .get(room, now)?.account_id;
63
+ return !(account && owner && String(account) !== String(owner));
64
+ };
65
+ const speaking = cue
66
+ .filter((r) => r && typeof r === "object" && r.role === "user")
67
+ .map((r) => String(r.userId || r.speaker || ""))
68
+ .filter(Boolean);
69
+ const ids = [
70
+ ...new Set(speaking.length ? speaking : people.map(String)),
71
+ ].slice(-3);
72
+ const persons = [];
73
+ for (const id of ids) {
74
+ const myElsewhereWords = this.#ownElsewhere(
75
+ id,
76
+ cue,
77
+ here,
78
+ compatible,
79
+ now,
80
+ );
81
+ const bonded = this.db
82
+ .prepare(
83
+ `SELECT session_id,MIN(created) first,MAX(created) last,COUNT(*) talks
84
+ FROM mind_bond_events WHERE subject_kind='person' AND subject_id=?
85
+ AND change='interaction' AND origin!='noticed' AND created<?
86
+ AND id NOT IN (SELECT target_id FROM mind_revocations WHERE target_kind='bond')
87
+ GROUP BY session_id ORDER BY last DESC`,
88
+ )
89
+ .all(id, now);
90
+ // Bond events describe how a relationship changed, and are deliberately
91
+ // limited to one interaction per hour. They cannot be the index of what
92
+ // she just said. Read the actual speaker's recent places as well.
93
+ const seen = this.db
94
+ .prepare(
95
+ `SELECT session_id,MIN(time) first,MAX(time) last
96
+ FROM core_events WHERE role='user' AND time>=? AND time<?
97
+ AND seq NOT IN (SELECT seq FROM mind_unlived)
98
+ AND COALESCE(json_extract(payload,'$.simulated'),0)=0
99
+ AND json_extract(payload,'$.userId')=?
100
+ GROUP BY session_id ORDER BY last DESC LIMIT 8`,
101
+ )
102
+ .all(now - 7 * DAY, now, id);
103
+ const byRoom = new Map(bonded.map((row) => [row.session_id, row]));
104
+ for (const row of seen) {
105
+ const old = byRoom.get(row.session_id);
106
+ byRoom.set(row.session_id, {
107
+ session_id: row.session_id,
108
+ first: Math.min(old?.first ?? row.first, row.first),
109
+ last: Math.max(old?.last ?? row.last, row.last),
110
+ talks: old?.talks ?? 0,
111
+ });
112
+ }
113
+ const rows = [...byRoom.values()].sort((a, b) => b.last - a.last);
114
+ const places = [];
115
+ const moments = [];
116
+ const recentShared = [];
117
+ const myPrivateIntentions = [];
118
+ for (const row of rows) {
119
+ if (places.length === 4) break;
120
+ if (!compatible(row.session_id)) continue;
121
+ const local = here.has(row.session_id);
122
+ const privateElsewhere =
123
+ !local &&
124
+ roomKey(row.session_id)?.kind === "private" &&
125
+ String(roomKey(row.session_id)?.nativeId) === id;
126
+ const privateCount = recentShared.length;
127
+ if (privateElsewhere) {
128
+ recentShared.push(
129
+ ...this.#privateHistory(row.session_id, id, session, cue, now),
130
+ );
131
+ myPrivateIntentions.push(
132
+ ...this.#privateIntentions(row.session_id, id, now),
133
+ );
134
+ }
135
+ const proof = this.db
136
+ .prepare(
137
+ `SELECT sources,created FROM mind_bond_events WHERE subject_kind='person'
138
+ AND subject_id=? AND session_id=? AND change='interaction'
139
+ AND origin!='noticed' AND created<?
140
+ AND id NOT IN (SELECT target_id FROM mind_revocations WHERE target_kind='bond')
141
+ ORDER BY created DESC LIMIT 12`,
142
+ )
143
+ .all(id, row.session_id, now)
144
+ .find(
145
+ (bond) =>
146
+ this.#words(
147
+ bond.sources,
148
+ id,
149
+ row.session_id,
150
+ session,
151
+ now,
152
+ bond.created,
153
+ ).length,
154
+ );
155
+ const place = {
156
+ sessionId: row.session_id,
157
+ kind: roomKey(row.session_id).kind,
158
+ name:
159
+ this.db
160
+ .prepare("SELECT name FROM sessions WHERE id=?")
161
+ .get(row.session_id)?.name || (local ? "这段私聊" : "群聊"),
162
+ current: local,
163
+ firstTalkedAt: row.first,
164
+ lastTalkedAt: row.last,
165
+ lastTalked: elapsedLabel(row.last, now, this.mind.timeZone()),
166
+ recordedTalks: row.talks,
167
+ };
168
+ // Her recent shared history exists before anyone asks her to recall it.
169
+ // The room decides what she may say aloud, not what she has lived.
170
+ const remembered =
171
+ requested || !local || !proof
172
+ ? this.#moments(id, place, session, cue, now)
173
+ : [];
174
+ if (
175
+ !proof &&
176
+ !remembered.length &&
177
+ !(privateElsewhere && recentShared.length > privateCount)
178
+ )
179
+ continue;
180
+ places.push(place);
181
+ if (requested || !local) {
182
+ if (remembered.length) moments.push(...remembered);
183
+ else if (proof)
184
+ moments.push({
185
+ place: place.sessionId,
186
+ when: elapsedLabel(proof.created, now, this.mind.timeZone()),
187
+ time: proof.created,
188
+ theySaid: this.#words(
189
+ proof.sources,
190
+ id,
191
+ row.session_id,
192
+ session,
193
+ now,
194
+ proof.created,
195
+ ),
196
+ ...(place.kind === "private" && !place.current
197
+ ? { privateOrigin: true, maySayAloud: false }
198
+ : {}),
199
+ });
200
+ }
201
+ }
202
+ if (!places.length && !myElsewhereWords.length) continue;
203
+ const selected = [];
204
+ // Other scenes cannot be crowded out by the last few private turns.
205
+ for (const place of [...places].sort(
206
+ (a, b) => Number(a.current) - Number(b.current),
207
+ )) {
208
+ const moment = moments.find((m) => m.place === place.sessionId);
209
+ if (moment) selected.push(moment);
210
+ if (selected.length === 3) break;
211
+ }
212
+ if (selected.length < 3)
213
+ selected.push(
214
+ ...moments
215
+ .filter((m) => !selected.includes(m))
216
+ .slice(0, 3 - selected.length),
217
+ );
218
+ persons.push({
219
+ id,
220
+ name: this.mind.bonds.name(id),
221
+ samePersonAcrossPlaces: true,
222
+ places: places.slice(0, 4),
223
+ ...(selected.length ? { sharedMoments: selected } : {}),
224
+ ...(recentShared.length
225
+ ? {
226
+ recentShared: recentShared
227
+ .sort((a, b) => a.time - b.time)
228
+ .slice(-24),
229
+ }
230
+ : {}),
231
+ ...(myPrivateIntentions.length
232
+ ? { myPrivateIntentions: myPrivateIntentions.slice(0, 4) }
233
+ : {}),
234
+ ...(myElsewhereWords.length ? { myElsewhereWords } : {}),
235
+ });
236
+ }
237
+ return persons.length
238
+ ? { requested, people: persons, referenceOnly: true }
239
+ : null;
240
+ }
241
+ #ownElsewhere(id, cue, here, compatible, now) {
242
+ const ownQuestion = (cue || []).filter(
243
+ (line) => String(line.userId || line.speaker || "") === id,
244
+ );
245
+ const question = ownQuestion.map((line) => line.text || "").join(" ");
246
+ // A generic "what did you promise?" belongs to this person's shared
247
+ // timeline. Search all of her own utterances only when another place is
248
+ // actually part of the question.
249
+ if (!/(?:别处|别的地方|其他群|另一个群|群里|私聊)/.test(question))
250
+ return [];
251
+ const mentionedKind = /(?:群里|其他群|另一个群)/.test(question)
252
+ ? "group"
253
+ : /私聊/.test(question)
254
+ ? "private"
255
+ : "";
256
+ const named = question.match(
257
+ /(?:喊|叫)我(?:一声)?([\p{Script=Han}a-zA-Z0-9]{2,8})/u,
258
+ )?.[1];
259
+ const query = interestTerms(
260
+ named ? [named] : ownQuestion.map((line) => line.text),
261
+ );
262
+ for (const generic of [
263
+ "群里",
264
+ "私聊",
265
+ "别处",
266
+ "别的",
267
+ "地方",
268
+ "其他",
269
+ "一个",
270
+ "说过",
271
+ "答应",
272
+ "忘了",
273
+ ])
274
+ query.delete(generic);
275
+ if (!query.size) return [];
276
+ return this.db
277
+ .prepare(
278
+ `SELECT seq,time,session_id,payload FROM core_events
279
+ WHERE role='assistant' AND time>=? AND time<?
280
+ AND seq NOT IN (SELECT seq FROM mind_unlived)
281
+ AND COALESCE(json_extract(payload,'$.simulated'),0)=0
282
+ ORDER BY time DESC LIMIT 700`,
283
+ )
284
+ .all(now - 7 * DAY, now)
285
+ .filter(
286
+ (row) =>
287
+ !here.has(row.session_id) &&
288
+ compatible(row.session_id) &&
289
+ (!mentionedKind || roomKey(row.session_id)?.kind === mentionedKind),
290
+ )
291
+ .map((row) => {
292
+ const words = parse(row.payload, {}).text || "";
293
+ return {
294
+ row,
295
+ words,
296
+ score: [...interestTerms([words])].filter((term) => query.has(term))
297
+ .length,
298
+ };
299
+ })
300
+ .filter(
301
+ ({ words, score }) =>
302
+ score > 0 && words && !hasCredential(words) && !secretRequest(words),
303
+ )
304
+ .sort((a, b) => b.score - a.score || b.row.time - a.row.time)
305
+ .slice(0, 5)
306
+ .map(({ row, words }) => {
307
+ const privateOrigin = roomKey(row.session_id)?.kind === "private";
308
+ return {
309
+ ref: `m:${row.seq}`,
310
+ place: row.session_id,
311
+ time: row.time,
312
+ when: elapsedLabel(row.time, now, this.mind.timeZone()),
313
+ text: text(words, 180),
314
+ role: "assistant",
315
+ speaker: "self",
316
+ addressedTo: "不能仅凭提问者推断当时是对谁说的",
317
+ ...(privateOrigin ? { privateOrigin: true, maySayAloud: false } : {}),
318
+ };
319
+ });
320
+ }
321
+ #privateHistory(room, id, destination, cue, now) {
322
+ const rows = this.db
323
+ .prepare(
324
+ `SELECT seq,time,role,payload FROM core_events
325
+ WHERE session_id=? AND time>=? AND time<?
326
+ AND role IN ('user','assistant')
327
+ AND seq NOT IN (SELECT seq FROM mind_unlived)
328
+ AND COALESCE(json_extract(payload,'$.simulated'),0)=0
329
+ ORDER BY seq DESC LIMIT 120`,
330
+ )
331
+ .all(room, now - 7 * DAY, now)
332
+ .reverse();
333
+ const latest = new Set(rows.slice(-20).map((row) => row.seq));
334
+ const rememberingAgreement = (cue || []).some((line) =>
335
+ /答应|约好|说好|承诺|记得|忘了|玩完|结束.*说/.test(line.text || ""),
336
+ );
337
+ const older = rememberingAgreement
338
+ ? rows
339
+ .filter(
340
+ (row) =>
341
+ !latest.has(row.seq) &&
342
+ /答应|说好|下次|以后|玩完|打完|结束.*(?:说|告诉)|记得|回你|跟你说/.test(
343
+ parse(row.payload, {}).text || "",
344
+ ),
345
+ )
346
+ .slice(-6)
347
+ : [];
348
+ let concealed = false;
349
+ return [...older, ...rows.slice(-20)]
350
+ .sort((a, b) => a.time - b.time || a.seq - b.seq)
351
+ .flatMap((row) => {
352
+ const message = parse(row.payload, {});
353
+ if (row.role === "user") {
354
+ if (String(message.userId) !== id) return [];
355
+ concealed = secretRequest(message.text);
356
+ }
357
+ if (concealed || hasCredential(message.text)) return [];
358
+ const words = text(message.text, 180);
359
+ return words
360
+ ? [
361
+ {
362
+ ref: `m:${row.seq}`,
363
+ place: room,
364
+ time: row.time,
365
+ when: elapsedLabel(row.time, now, this.mind.timeZone()),
366
+ role: row.role,
367
+ speaker: row.role === "assistant" ? "self" : id,
368
+ text: words,
369
+ privateOrigin: true,
370
+ maySayAloud: false,
371
+ },
372
+ ]
373
+ : [];
374
+ });
375
+ }
376
+ #privateIntentions(room, id, now) {
377
+ const name = this.mind.bonds.name(id) || "";
378
+ return this.db
379
+ .prepare(
380
+ `SELECT thread,created,content FROM mind_self
381
+ WHERE session_id=? AND kind='intention' AND status='active'
382
+ AND created<? AND thread NOT IN
383
+ (SELECT target_id FROM mind_revocations WHERE target_kind='self')
384
+ ORDER BY created DESC LIMIT 24`,
385
+ )
386
+ .all(room, now)
387
+ .filter(
388
+ (row) =>
389
+ !hasCredential(row.content) &&
390
+ !secretRequest(row.content) &&
391
+ ((name && row.content.includes(name)) ||
392
+ /答应|约好|承诺|告诉(?:他|你)|回(?:他|你)|联系|找(?:他|你)|喊(?:他|你)|称呼/.test(
393
+ row.content,
394
+ )),
395
+ )
396
+ .slice(0, 4)
397
+ .map((row) => ({
398
+ ref: `s:${row.thread}`,
399
+ time: row.created,
400
+ content: text(row.content, 150),
401
+ privateOrigin: true,
402
+ maySayAloud: false,
403
+ }));
404
+ }
405
+ #words(sources, id, room, destination, now, happened = now) {
406
+ const seqs = messageSeqs(parse(sources, []));
407
+ if (!seqs.length) return [];
408
+ const rows = this.db
409
+ .prepare(
410
+ `SELECT seq,time,payload FROM core_events WHERE seq IN (${seqs.map(() => "?").join(",")})
411
+ AND session_id=? AND time<? AND time<=? AND role='user'
412
+ AND seq NOT IN (SELECT seq FROM mind_unlived) ORDER BY seq`,
413
+ )
414
+ .all(...seqs, room, now, happened);
415
+ return rows
416
+ .flatMap((row) => {
417
+ const p = parse(row.payload, {});
418
+ if (
419
+ String(p.userId) !== id ||
420
+ p.simulated ||
421
+ hasCredential(p.text) ||
422
+ secretRequest(p.text)
423
+ )
424
+ return [];
425
+ const privateToGroup =
426
+ roomKey(room)?.kind === "private" &&
427
+ roomKey(destination)?.kind === "group";
428
+ if (
429
+ !privateToGroup &&
430
+ (!this.mind.meetings.stays(
431
+ { sources: [`m:${row.seq}`] },
432
+ destination,
433
+ ) ||
434
+ !this.mind.meetings.sayable(p.text, destination))
435
+ )
436
+ return [];
437
+ const said = text(p.text, 180);
438
+ return said
439
+ ? [{ ref: `m:${row.seq}`, time: row.time, text: said }]
440
+ : [];
441
+ })
442
+ .slice(-2);
443
+ }
444
+ #moments(id, place, destination, cue, now) {
445
+ const rows = this.db
446
+ .prepare(
447
+ `SELECT m.*,c.trace_id FROM mind_meetings m
448
+ LEFT JOIN mind_choices c ON c.session_id=m.session_id AND c.created=m.created
449
+ WHERE m.session_id=? AND m.created<? AND m.choice!='silent'
450
+ AND m.id IN (SELECT meeting_id FROM mind_meeting_people WHERE user_id=?)
451
+ AND m.id NOT IN (SELECT target_id FROM mind_revocations WHERE target_kind='meeting')
452
+ ${place.current ? "" : "AND m.discretion!='secret'"}
453
+ ORDER BY m.created DESC LIMIT 40`,
454
+ )
455
+ .all(place.sessionId, now, id);
456
+ const query = lexicalTerms(
457
+ cue
458
+ .filter((r) => String(r.userId || r.speaker) === id)
459
+ .map((r) => r.text || "")
460
+ .join(" "),
461
+ );
462
+ const candidates = [];
463
+ const privateToGroup =
464
+ place.kind === "private" && roomKey(destination)?.kind === "group";
465
+ const safe = (line) =>
466
+ !hasCredential(line) &&
467
+ !secretRequest(line) &&
468
+ (privateToGroup || this.mind.meetings.sayable(line, destination));
469
+ for (const row of rows) {
470
+ const exchange = parse(row.exchange, null);
471
+ if (exchange?.they?.length && exchange.iSaid?.length) {
472
+ const theySaid = exchange.they
473
+ .filter((m) => m.speaker === id && m.time < now && safe(m.text))
474
+ .map((m) => ({ ref: m.ref, time: m.time, text: text(m.text, 180) }));
475
+ const iSaid = exchange.iSaid.filter((line) => safe(line));
476
+ if (recallIntent(theySaid.map((m) => ({ role: "user", text: m.text }))))
477
+ continue;
478
+ if (
479
+ theySaid.length &&
480
+ iSaid.length &&
481
+ (privateToGroup ||
482
+ this.mind.meetings.stays({ sources: [`g:${row.id}`] }, destination))
483
+ ) {
484
+ candidates.push({
485
+ place: place.sessionId,
486
+ when: elapsedLabel(row.created, now, this.mind.timeZone()),
487
+ time: row.created,
488
+ theySaid: theySaid.slice(-2),
489
+ iSaid: iSaid.map((line) => text(line, 180)).slice(0, 3),
490
+ ...(privateToGroup
491
+ ? { privateOrigin: true, maySayAloud: false }
492
+ : {}),
493
+ score: overlapScore(
494
+ [...theySaid.map((m) => m.text), ...iSaid].join(" "),
495
+ query,
496
+ ),
497
+ });
498
+ }
499
+ continue;
500
+ }
501
+ const words = this.#words(
502
+ row.sources,
503
+ id,
504
+ place.sessionId,
505
+ destination,
506
+ now,
507
+ row.created,
508
+ );
509
+ if (!words.length || words.every((w) => w.text.length < 4)) continue;
510
+ if (recallIntent(words.map((m) => ({ role: "user", text: m.text }))))
511
+ continue;
512
+ const trace = row.trace_id
513
+ ? this.db
514
+ .prepare(
515
+ "SELECT json_extract(data,'$.decision.targetMessageIds') targets FROM core_traces WHERE id=?",
516
+ )
517
+ .get(row.trace_id)
518
+ : null;
519
+ const targets = parse(trace?.targets, []);
520
+ const seqs = words.map((w) => Number(w.ref.slice(2)));
521
+ const delivered = row.trace_id
522
+ ? this.db
523
+ .prepare(
524
+ "SELECT text,platform_id,time FROM core_outbox WHERE trace_id=? AND status='confirmed' AND time<? ORDER BY position",
525
+ )
526
+ .all(row.trace_id, now)
527
+ : [];
528
+ if (!delivered.length) continue;
529
+ const related = targets.length
530
+ ? targets.some((seq) => seqs.includes(Number(seq)))
531
+ : delivered.some((reply) => {
532
+ const event = this.db
533
+ .prepare(
534
+ "SELECT payload FROM core_events WHERE session_id=? AND platform_id=? AND role='assistant' LIMIT 1",
535
+ )
536
+ .get(place.sessionId, reply.platform_id);
537
+ return parse(event?.payload, {}).replyTargetIds?.some((seq) =>
538
+ seqs.includes(seq),
539
+ );
540
+ });
541
+ if (!related) continue;
542
+ const myWords = delivered
543
+ .filter((r) => safe(r.text))
544
+ .map((r) => text(r.text, 180));
545
+ if (!myWords.length) continue;
546
+ candidates.push({
547
+ place: place.sessionId,
548
+ when: elapsedLabel(row.created, now, this.mind.timeZone()),
549
+ time: row.created,
550
+ theySaid: words,
551
+ iSaid: myWords.slice(0, 3),
552
+ ...(privateToGroup ? { privateOrigin: true, maySayAloud: false } : {}),
553
+ score: overlapScore(
554
+ [...words.map((w) => w.text), ...myWords].join(" "),
555
+ query,
556
+ ),
557
+ });
558
+ }
559
+ candidates.sort((a, b) => b.score - a.score || b.time - a.time);
560
+ return candidates.slice(0, 2).map(({ score: _score, ...moment }) => moment);
561
+ }
562
+ }