luckytri 1.0.6 → 1.0.8

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