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,562 +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
- }
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
+ }