luckytri 1.0.0 → 1.0.2

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 (139) hide show
  1. package/.github/SECURITY.md +4 -4
  2. package/README.en.md +252 -250
  3. package/README.md +252 -250
  4. package/bin/luckytri.js +5 -1
  5. package/docs/en/CHANGELOG.md +8 -0
  6. package/docs/en/connect.md +18 -18
  7. package/docs/en/guide.md +202 -216
  8. package/docs/en/npm-release.md +25 -25
  9. package/docs/zh/CHANGELOG.md +8 -0
  10. package/docs/zh/connect.md +17 -17
  11. package/docs/zh/guide.md +202 -216
  12. package/docs/zh/npm-release.md +33 -33
  13. package/package.json +110 -108
  14. package/plugins/sdk/index.d.ts +155 -155
  15. package/plugins/sdk/testing.js +58 -58
  16. package/plugins/weather/index.js +82 -82
  17. package/plugins/weather/luckytri-plugin.json +29 -29
  18. package/public/app/assets/ChatsPage-BhlJHseG.js +3 -0
  19. package/public/app/assets/Empty-DP6WMGHi.js +2 -0
  20. package/public/app/assets/Field-CtbdqaiB.js +1 -0
  21. package/public/app/assets/HeartPage-32BeTPn2.js +1 -0
  22. package/public/app/assets/LifePage-CxSm0XKI.js +1 -0
  23. package/public/app/assets/MemoryPage-BeKBcPCY.js +1 -0
  24. package/public/app/assets/NaturePage-NEPYl2HS.js +3 -0
  25. package/public/app/assets/PeoplePage-DxtpekwM.js +1 -0
  26. package/public/app/assets/PluginsPage-CVVQwEBI.css +1 -0
  27. package/public/app/assets/PluginsPage-DksEZbUU.js +2 -0
  28. package/public/app/assets/{SystemPage-CAMPoYqM.css → SystemPage-BkRu0Rvx.css} +1 -1
  29. package/public/app/assets/SystemPage-BvzJlHuY.js +1 -0
  30. package/public/app/assets/TimePage-7-awH5XL.js +3 -0
  31. package/public/app/assets/index-4rItIkD-.js +4 -0
  32. package/public/app/assets/{index-YDz1ree1.css → index-DY4e15Kh.css} +1 -1
  33. package/public/app/assets/{knowledge-DG0e0uKw.js → knowledge-C6_HvoyB.js} +1 -1
  34. package/public/app/assets/media-SMfTT-yc.js +1 -0
  35. package/public/app/index.html +3 -3
  36. package/public/guide.en.html +72 -99
  37. package/public/guide.html +44 -86
  38. package/public/tutorial.en.md +25 -39
  39. package/public/tutorial.md +25 -39
  40. package/scripts/backup.js +311 -311
  41. package/scripts/browser.js +41 -41
  42. package/scripts/import-data.js +128 -0
  43. package/scripts/launch.js +101 -94
  44. package/scripts/plugin.js +150 -150
  45. package/scripts/reset-password.js +22 -0
  46. package/scripts/runtime.js +25 -25
  47. package/scripts/service.js +56 -47
  48. package/scripts/setup.js +50 -50
  49. package/scripts/start-server.js +41 -41
  50. package/scripts/stop.js +36 -36
  51. package/server/app.js +112 -96
  52. package/server/auth.js +217 -0
  53. package/server/channels/contract.js +57 -57
  54. package/server/channels/hub.js +165 -165
  55. package/server/channels/index.js +28 -25
  56. package/server/channels/onebot/index.js +335 -336
  57. package/server/channels/onebot/token.js +22 -3
  58. package/server/core/capabilities.js +208 -208
  59. package/server/core/events.js +64 -60
  60. package/server/core/image-preprocessor.js +208 -208
  61. package/server/core/model-manager.js +1213 -1213
  62. package/server/core/net-guard.js +49 -49
  63. package/server/core/orchestrator.js +569 -569
  64. package/server/core/perceivers.js +91 -91
  65. package/server/core/persona-manager.js +243 -243
  66. package/server/core/repository.js +293 -293
  67. package/server/core/response-validator.js +508 -508
  68. package/server/core/turn-processor.js +630 -630
  69. package/server/core/turn.js +236 -236
  70. package/server/core/vision-manager.js +633 -633
  71. package/server/i18n/errors.js +548 -497
  72. package/server/i18n/labels.js +649 -653
  73. package/server/index.js +151 -102
  74. package/server/knowledge/manager.js +386 -386
  75. package/server/knowledge/schema.js +12 -8
  76. package/server/local-access.js +32 -0
  77. package/server/mind/anticipations.js +507 -507
  78. package/server/mind/api.js +703 -703
  79. package/server/mind/budget.js +152 -152
  80. package/server/mind/context-selection.js +61 -61
  81. package/server/mind/day-planner.js +324 -324
  82. package/server/mind/evidence.js +148 -148
  83. package/server/mind/index.js +445 -445
  84. package/server/mind/life/diary.js +786 -786
  85. package/server/mind/life/index.js +1049 -1049
  86. package/server/mind/observations.js +84 -84
  87. package/server/mind/own-day.js +324 -324
  88. package/server/mind/own-voice.js +318 -318
  89. package/server/mind/senses.js +53 -53
  90. package/server/mind/time/activity-clock.js +196 -196
  91. package/server/mind/time/availability.js +69 -69
  92. package/server/mind/time/commitment-review.js +198 -198
  93. package/server/mind/time/executor.js +512 -512
  94. package/server/mind/time/experiences.js +128 -128
  95. package/server/mind/time/games.js +562 -562
  96. package/server/mind/time/index.js +739 -739
  97. package/server/mind/time/intent.js +166 -166
  98. package/server/mind/time/kinds.js +171 -171
  99. package/server/mind/time/plugin-activity.js +207 -207
  100. package/server/mind/time/tasks.js +587 -587
  101. package/server/mind/util.js +110 -110
  102. package/server/mind/view.js +273 -273
  103. package/server/paths.js +102 -102
  104. package/server/plugins/api.js +204 -204
  105. package/server/plugins/host.js +967 -967
  106. package/server/plugins/install.js +295 -295
  107. package/server/plugins/manifest.js +201 -201
  108. package/server/plugins/permissions.js +42 -42
  109. package/server/plugins/runner/guard.mjs +36 -36
  110. package/server/plugins/runner/worker.mjs +250 -250
  111. package/server/plugins/schema.js +91 -91
  112. package/server/plugins/zip.js +112 -112
  113. package/server/startup-lock.js +118 -118
  114. package/server/storage/archive.js +242 -241
  115. package/server/storage/backup-cleanup-worker.js +8 -8
  116. package/server/storage/backup-cleanup.js +415 -414
  117. package/server/storage/backup-lock.js +76 -76
  118. package/server/storage/backup-scheduler.js +131 -131
  119. package/server/storage/data-package.js +298 -0
  120. package/server/storage/data-transfer-api.js +50 -0
  121. package/server/storage/data-transfer-worker.js +18 -0
  122. package/server/storage/data-transfer.js +415 -0
  123. package/server/storage/store.js +202 -199
  124. package/server/studio/readiness.js +181 -190
  125. package/server/studio/settings.js +236 -236
  126. package/public/app/assets/ChatsPage-C-FcRapR.js +0 -3
  127. package/public/app/assets/Empty-CpP5kQHH.js +0 -2
  128. package/public/app/assets/Field-D4gY-INU.js +0 -1
  129. package/public/app/assets/HeartPage-CPy_thQd.js +0 -1
  130. package/public/app/assets/LifePage-CxWvwmSf.js +0 -1
  131. package/public/app/assets/MemoryPage-DC4rhQ68.js +0 -1
  132. package/public/app/assets/NaturePage-IvYw04Zq.js +0 -3
  133. package/public/app/assets/PeoplePage-Cqefm9-q.js +0 -1
  134. package/public/app/assets/PluginsPage-DKSaKvXb.js +0 -2
  135. package/public/app/assets/PluginsPage-HyBe5D8w.css +0 -1
  136. package/public/app/assets/SystemPage-CJmtJkrK.js +0 -1
  137. package/public/app/assets/TimePage-Cw44inM4.js +0 -3
  138. package/public/app/assets/index-BheRW-1t.js +0 -4
  139. package/public/app/assets/media-BzPDBm7e.js +0 -1
@@ -1,703 +1,703 @@
1
- import { wrap } from "../http.js";
2
- import { mountTime } from "./time/api.js";
3
- import { localClock } from "../core/conversation-cues.js";
4
- import { agoLabel, elapsedLabel, JUST_NOW } from "./clock.js";
5
- import { diffSnapshots } from "./index.js";
6
- import { SELF_KINDS } from "./self.js";
7
- import { THOUGHT_KINDS } from "./thoughts.js";
8
- import { dayKey, parse, text } from "./util.js";
9
- import {
10
- displayNames,
11
- displayPerson,
12
- displaySession,
13
- } from "../studio/display-names.js";
14
-
15
- const RUN_ACTIVITY = {
16
- activity: "solitude",
17
- solitude: "solitude",
18
- expression: "solitude",
19
- daily: "diary",
20
- weekly: "review",
21
- night: "night",
22
- };
23
-
24
- function sessionNames(db, now) {
25
- const people = displayNames(db, now);
26
- return new Map(
27
- db
28
- .prepare("SELECT id,name FROM sessions")
29
- .all()
30
- .map((s) => [s.id, displaySession(s, people).name]),
31
- );
32
- }
33
-
34
- function displayAhead(db, rows, now) {
35
- const names = displayNames(db, now);
36
- return rows.map((row) => ({
37
- ...row,
38
- name: names.get(String(row.subject || "")) || row.name,
39
- }));
40
- }
41
-
42
- // What TA is doing this moment: a background run, a conversation being
43
- // read, words just sent, or sleep.
44
- function activityOf({ db, life, now, affect, words, names }) {
45
- if (life.busy) {
46
- const run = db
47
- .prepare(
48
- "SELECT kind,started FROM mind_runs WHERE status='running' ORDER BY started DESC LIMIT 1",
49
- )
50
- .get();
51
- if (run)
52
- return { kind: RUN_ACTIVITY[run.kind] || "busy", since: run.started };
53
- }
54
- const thinking = db
55
- .prepare(
56
- "SELECT session_id,time FROM core_traces WHERE status='running' AND mode IN ('live','demo') ORDER BY time DESC LIMIT 1",
57
- )
58
- .get();
59
- if (thinking)
60
- return {
61
- kind: "thinking",
62
- since: thinking.time,
63
- session: thinking.session_id,
64
- sessionName: names.get(thinking.session_id) || thinking.session_id,
65
- };
66
- if (words && now - words.time < 30000)
67
- return {
68
- kind: "speaking",
69
- since: words.time,
70
- session: words.session,
71
- sessionName: words.sessionName,
72
- };
73
- if (affect.phase === "asleep") return { kind: "asleep" };
74
- return { kind: "idle" };
75
- }
76
-
77
- export function mountMind(app, chat, life) {
78
- const { mind } = chat;
79
- mountTime(app, life);
80
- // A small, cheap picture of TA for the studio: asked for on every change.
81
- app.get(
82
- "/api/mind/presence",
83
- wrap((req, res) => {
84
- const now = life.now();
85
- const db = chat.repo.db;
86
- const nature = mind.nature.current(now);
87
- const affect = mind.affect.state(now, { nature });
88
- const names = sessionNames(db, now);
89
- const demo = Number(!!chat.store.settings().demo);
90
- const saidRows = db
91
- .prepare(
92
- "SELECT session_id,time,payload FROM core_events WHERE role='assistant' AND COALESCE(json_extract(payload,'$.simulated'),0)=? ORDER BY seq DESC LIMIT 20",
93
- )
94
- .all(demo);
95
- const recentWords = saidRows
96
- .map((said) => ({
97
- text: text(parse(said.payload, {}).text, 120),
98
- session: said.session_id,
99
- sessionName: names.get(said.session_id) || said.session_id,
100
- time: said.time,
101
- }))
102
- .filter((item) => item.text.trim())
103
- .slice(0, 3);
104
- const words = recentWords[0] || null;
105
- const thought = mind.thoughts.latest(now);
106
- res.json({
107
- name: nature.name,
108
- nature: { rhythm: nature.rhythm },
109
- busy: Boolean(life.busy),
110
- reason: life.eligible(now),
111
- now,
112
- clock: localClock(now, mind.timeZone()),
113
- affect: {
114
- mood: affect.mood,
115
- cause: affect.cause,
116
- valence: affect.valence,
117
- arousal: affect.arousal,
118
- energy: affect.energy,
119
- energyLabel: affect.energyLabel,
120
- phase: affect.phase,
121
- phaseLabel: affect.phaseLabel,
122
- lately: affect.lately,
123
- baseline: affect.baseline,
124
- },
125
- activity: activityOf({ db, life, now, affect, words, names }),
126
- currentLife: mind.time.view({ now }),
127
- lastWords: words,
128
- recentWords,
129
- thought: thought
130
- ? {
131
- content: thought.content,
132
- when: elapsedLabel(thought.created, now, mind.timeZone()),
133
- }
134
- : null,
135
- expecting: displayAhead(
136
- db,
137
- mind.anticipations.list({ now, limit: 100 }),
138
- now,
139
- )
140
- .filter(
141
- (a) =>
142
- a.state === "pending" &&
143
- String(a.content || "").trim() &&
144
- a.occurrence >= now - 86400000 &&
145
- a.occurrence <= now + 7 * 86400000,
146
- )
147
- .slice(0, 5)
148
- .map((a) => ({
149
- id: a.id,
150
- kind: a.kind,
151
- name: a.name,
152
- content: a.content,
153
- when: a.when,
154
- })),
155
- dayOfLife: mind.days.dayOfLife(now),
156
- will: (() => {
157
- const living = life.livingForView(now);
158
- if (!living) return null;
159
- const trace = living.thread
160
- ? mind.meetings.trace(living.thread, {
161
- before: now,
162
- inclusive: true,
163
- })
164
- : null;
165
- return {
166
- ...(living.content ? { content: living.content } : {}),
167
- ...(trace?.touched
168
- ? { touched: trace.touched, lastSpoke: trace.lastSpoke }
169
- : {}),
170
- ...(living.also ? { also: living.also } : {}),
171
- };
172
- })(),
173
- meaning: (() => {
174
- const row = mind.meetings.latest({ before: now });
175
- if (!row) return null;
176
- return {
177
- text: text(row.appraisal, 80),
178
- when: elapsedLabel(row.created, now, mind.timeZone()),
179
- recent: now - row.created < JUST_NOW,
180
- spoke: row.choice !== "silent",
181
- };
182
- })(),
183
- });
184
- }),
185
- );
186
- // Everything that happened in TA's day so far, newest first.
187
- app.get(
188
- "/api/mind/today",
189
- wrap((req, res) => {
190
- const now = life.now();
191
- const start = life.dayStart(now);
192
- const db = chat.repo.db;
193
- const names = sessionNames(db, now);
194
- const where = (session) => ({
195
- session,
196
- sessionName: names.get(session) || session,
197
- });
198
- const items = [];
199
- for (const c of db
200
- .prepare(
201
- "SELECT * FROM mind_choices WHERE created>=? AND created<=? ORDER BY created DESC LIMIT 80",
202
- )
203
- .all(start, now))
204
- items.push({
205
- type: "choice",
206
- time: c.created,
207
- choice: c.choice,
208
- reason: c.reason,
209
- appraisal: c.appraisal,
210
- occasion: c.occasion,
211
- ...where(c.session_id),
212
- });
213
- for (const a of db
214
- .prepare(
215
- "SELECT * FROM mind_affect WHERE created>=? AND created<=? ORDER BY created DESC LIMIT 60",
216
- )
217
- .all(start, now))
218
- items.push({
219
- type: "feeling",
220
- time: a.created,
221
- feeling: a.feeling,
222
- cause: a.cause,
223
- valence: a.valence,
224
- intensity: a.intensity,
225
- origin: a.origin,
226
- });
227
- for (const r of db
228
- .prepare(
229
- "SELECT * FROM mind_runs WHERE started>=? AND started<=? AND NOT (kind='activity' AND status IN ('reading','engaged')) ORDER BY started DESC LIMIT 30",
230
- )
231
- .all(start, now))
232
- items.push({
233
- type: "run",
234
- time: r.started,
235
- kind: r.kind,
236
- status: r.status,
237
- reason: r.reason,
238
- });
239
- for (const t of db
240
- .prepare(
241
- "SELECT session_id,time,json_extract(data,'$.reason') reason FROM core_traces WHERE status='glanced' AND time>=? AND time<=? ORDER BY time DESC LIMIT 40",
242
- )
243
- .all(start, now))
244
- items.push({
245
- type: "glance",
246
- time: t.time,
247
- reason: t.reason,
248
- ...where(t.session_id),
249
- });
250
- for (const a of db
251
- .prepare(
252
- "SELECT * FROM mind_anticipations WHERE closed_at>=? AND closed_at<=? AND status IN ('done','missed','let_go') ORDER BY closed_at DESC LIMIT 20",
253
- )
254
- .all(start, now))
255
- items.push({
256
- type: "ahead",
257
- time: a.closed_at,
258
- status: a.status,
259
- content: a.content,
260
- note: a.closed_note,
261
- });
262
- items.sort((a, b) => b.time - a.time);
263
- res.json({ day: life.lifeDay(now), start, items: items.slice(0, 150) });
264
- }),
265
- );
266
- // One person as TA knows them: the feeling, where it came from, what TA
267
- // remembers about them and what TA is waiting for with them.
268
- app.get(
269
- "/api/mind/people/:id",
270
- wrap((req, res) => {
271
- const now = life.now();
272
- const id = String(req.params.id);
273
- const person = mind.bonds.person(id, now);
274
- if (!person) {
275
- const error = Error("TA 还不认识这个人");
276
- error.status = 404;
277
- throw error;
278
- }
279
- const db = chat.repo.db;
280
- const names = sessionNames(db, now);
281
- res.json({
282
- person: {
283
- ...displayPerson(person, displayNames(db, now)),
284
- places: person.sessions.map((s) => ({
285
- id: s,
286
- name: names.get(s) || s,
287
- })),
288
- },
289
- changes: mind.bonds.changes("person", id, 60),
290
- memories: db
291
- .prepare(
292
- "SELECT id,session_id,content,type,confidence,importance,status,discretion,locked,created,superseded_by FROM core_memories WHERE subject=? AND status IN ('confirmed','superseded') ORDER BY CASE status WHEN 'confirmed' THEN 0 ELSE 1 END, created DESC LIMIT 80",
293
- )
294
- .all(id)
295
- .map((m) => ({
296
- ...m,
297
- sessionName: names.get(m.session_id) || m.session_id,
298
- when: agoLabel(now - m.created),
299
- })),
300
- anticipations: displayAhead(
301
- db,
302
- mind.anticipations.list({ now, limit: 300 }),
303
- now,
304
- )
305
- .filter((a) => String(a.subject) === id)
306
- .slice(0, 30),
307
- meetings: mind.meetings.withPerson(id, { before: now }).map((m) => ({
308
- ...m,
309
- sessionName: names.get(m.sessionId) || m.sessionId,
310
- })),
311
- });
312
- }),
313
- );
314
- app.get(
315
- "/api/mind",
316
- wrap((req, res) => {
317
- const now = life.now();
318
- const nature = mind.nature.current(now);
319
- const names = sessionNames(chat.repo.db, now);
320
- res.json({
321
- clock: localClock(now, mind.timeZone()),
322
- affect: mind.affect.state(now, { nature }),
323
- moods: mind.affect.history({ limit: 24 }),
324
- choices: mind.choices({ limit: 30 }).map((c) => ({
325
- ...c,
326
- sessionName: names.get(c.session_id) || c.session_id,
327
- })),
328
- attention: chat.repo.db
329
- .prepare("SELECT * FROM mind_attention")
330
- .all()
331
- .filter((a) => names.has(a.session_id))
332
- .map((a) => ({
333
- session: a.session_id,
334
- name: names.get(a.session_id),
335
- lookedAt: a.looked_at,
336
- unread: mind.unread(a.session_id, { now }).length,
337
- })),
338
- nature: {
339
- name: nature.name,
340
- rhythm: nature.rhythm,
341
- version: nature.version,
342
- },
343
- life: life.settings(),
344
- budget: mind.budget.report(now),
345
- reason: life.eligible(now),
346
- busy: life.busy,
347
- dayOfLife: mind.days.dayOfLife(now),
348
- // The week ahead as she sees it, wherever each thing was said.
349
- expecting: displayAhead(
350
- chat.repo.db,
351
- mind.anticipations.list({ now, limit: 100 }),
352
- now,
353
- )
354
- .filter(
355
- (a) =>
356
- a.state === "pending" &&
357
- a.occurrence >= now - 86400000 &&
358
- a.occurrence <= now + 7 * 86400000,
359
- )
360
- .slice(0, 8),
361
- counts: {
362
- self: mind.self.active({ before: now, now, limit: 500 }).length,
363
- faded: mind.self.dormant({ before: now, now }).length,
364
- people: chat.repo.db
365
- .prepare("SELECT COUNT(*) n FROM mind_people")
366
- .get().n,
367
- thoughts: chat.repo.db
368
- .prepare("SELECT COUNT(*) n FROM mind_thoughts WHERE hidden=0")
369
- .get().n,
370
- diaries: chat.repo.db
371
- .prepare("SELECT COUNT(DISTINCT day) n FROM mind_diary")
372
- .get().n,
373
- chapters: life.chapters().length,
374
- reviews: chat.repo.db
375
- .prepare("SELECT COUNT(*) n FROM mind_periods WHERE level='week'")
376
- .get().n,
377
- anticipations: chat.repo.db
378
- .prepare(
379
- "SELECT COUNT(*) n FROM mind_anticipations WHERE status='pending'",
380
- )
381
- .get().n,
382
- },
383
- kinds: { self: SELF_KINDS, thoughts: THOUGHT_KINDS },
384
- });
385
- }),
386
- );
387
- // A page asks only for the projections it renders. The dock shares presence;
388
- // weather and notes don't need unread messages, task history or self counts.
389
- app.get(
390
- "/api/mind/mood",
391
- wrap((req, res) => {
392
- const now = life.now(),
393
- nature = mind.nature.current(now);
394
- res.json({
395
- clock: localClock(now, mind.timeZone()),
396
- affect: mind.affect.state(now, { nature }),
397
- moods: mind.affect.history({ limit: 24 }),
398
- kinds: { thoughts: THOUGHT_KINDS },
399
- });
400
- }),
401
- );
402
- app.get(
403
- "/api/mind/thoughts",
404
- wrap((req, res) => {
405
- const q = String(req.query.q || "").slice(0, 200),
406
- before = Number(req.query.before) || Number.MAX_SAFE_INTEGER;
407
- res.json(mind.thoughts.list({ before, q, limit: 30 }));
408
- }),
409
- );
410
- app.get(
411
- "/api/mind/self",
412
- wrap((req, res) => {
413
- const now = life.now();
414
- const weighed = new Map(
415
- mind.self.annotated({ now }).map((t) => [t.thread, t]),
416
- );
417
- res.json({
418
- threads: mind.self
419
- .latest()
420
- .map((t) => {
421
- const w = weighed.get(t.thread);
422
- return {
423
- ...t,
424
- versions: mind.self.history(t.thread).length,
425
- salience: w?.salience ?? null,
426
- core: !!w?.core,
427
- faded: !!w?.faded,
428
- fading: !!w && !w.core && !w.faded && w.salience < 0.2,
429
- };
430
- })
431
- .sort(
432
- (a, b) =>
433
- (b.salience ?? -1) - (a.salience ?? -1) ||
434
- b.strength - a.strength ||
435
- b.created - a.created,
436
- ),
437
- revoked: mind.revocations().filter((r) => r.target_kind === "self"),
438
- kinds: SELF_KINDS,
439
- });
440
- }),
441
- );
442
- app.get(
443
- "/api/mind/self/:thread",
444
- wrap((req, res) => res.json(mind.self.history(req.params.thread))),
445
- );
446
- app.get(
447
- "/api/mind/bonds",
448
- wrap((req, res) => {
449
- const sessions = chat.repo.db
450
- .prepare("SELECT id,name,kind FROM sessions WHERE archived=0")
451
- .all();
452
- const names = displayNames(chat.repo.db, life.now());
453
- res.json({
454
- people: mind.bonds
455
- .people({ limit: 200 })
456
- .map((person) => displayPerson(person, names)),
457
- groups: sessions.map((s) => ({
458
- session: s.id,
459
- name: displaySession(s, names).name,
460
- kind: s.kind,
461
- bond: mind.bonds.group(s.id),
462
- face: mind.faces.current(s.id),
463
- })),
464
- });
465
- }),
466
- );
467
- app.get(
468
- "/api/mind/bonds/:kind/:id",
469
- wrap((req, res) => {
470
- if (!["person", "group"].includes(req.params.kind))
471
- throw Error("类型无效");
472
- res.json(mind.bonds.changes(req.params.kind, req.params.id));
473
- }),
474
- );
475
- app.get(
476
- "/api/mind/faces/:session",
477
- wrap((req, res) => res.json(mind.faces.history(req.params.session))),
478
- );
479
- app.get(
480
- "/api/mind/life",
481
- wrap((req, res) => {
482
- const q = String(req.query.q || "").slice(0, 200);
483
- const before = Number(req.query.before) || Number.MAX_SAFE_INTEGER;
484
- const now = life.now();
485
- res.json({
486
- diaries: life.diaries({ limit: 30 }).map((d) => ({
487
- ...d,
488
- actions: mind.time.lived({
489
- since: life.dayStart(d.created),
490
- before: d.created,
491
- }),
492
- })),
493
- creations: life.activities.list({ before: now }),
494
- chapters: life.chapters().map((c) => ({
495
- ...c,
496
- versions: life.chapterVersions(c.chapter).length,
497
- })),
498
- reviews: mind.periods.reviews({ limit: 12 }),
499
- story: mind.periods.story(),
500
- storyVersions: mind.periods.storyVersions().length,
501
- anticipations: displayAhead(
502
- chat.repo.db,
503
- mind.anticipations.list({ now, limit: 60 }),
504
- now,
505
- ),
506
- dayOfLife: mind.days.dayOfLife(now),
507
- snapshots: chat.repo.db
508
- .prepare(
509
- "SELECT day,created FROM mind_snapshots ORDER BY day DESC LIMIT 60",
510
- )
511
- .all(),
512
- thoughts: mind.thoughts.list({ before, q, limit: 30 }),
513
- readings: mind.reading.recent({ limit: 30 }),
514
- unread: mind.reading.unreadCount(),
515
- runs: life.runs(60),
516
- });
517
- }),
518
- );
519
- app.get(
520
- "/api/mind/story",
521
- wrap((req, res) => res.json(mind.periods.storyVersions())),
522
- );
523
- app.get(
524
- "/api/mind/chapters/:number",
525
- wrap((req, res) =>
526
- res.json(life.chapterVersions(Number(req.params.number))),
527
- ),
528
- );
529
- app.get(
530
- "/api/mind/day/:day",
531
- wrap((req, res) => {
532
- const day = String(req.params.day);
533
- if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw Error("日期无效");
534
- const snapshot = mind.snapshotOf(day);
535
- const previous = chat.repo.db
536
- .prepare(
537
- "SELECT day FROM mind_snapshots WHERE day<? ORDER BY day DESC LIMIT 1",
538
- )
539
- .get(day)?.day;
540
- const yesterday = previous ? mind.snapshotOf(previous) : null;
541
- const present = (snap) => {
542
- if (!snap) return null;
543
- return { ...snap, livingFor: mind.livedThen(snap) };
544
- };
545
- res.json({
546
- day,
547
- diary:
548
- life.diaries({ before: day, limit: 1 }).find((d) => d.day === day) ||
549
- null,
550
- snapshot: present(snapshot),
551
- yesterday: present(yesterday),
552
- change: diffSnapshots(yesterday, snapshot),
553
- });
554
- }),
555
- );
556
- app.get(
557
- "/api/mind/nature",
558
- wrap((req, res) =>
559
- res.json({
560
- nature: mind.nature.current(),
561
- versions: mind.nature.versions(),
562
- livedTraits: mind.traits.current(),
563
- traitHistory: mind.traits.history(30),
564
- livedPersona: mind.traits.persona()?.content || "",
565
- personaHistory: mind.traits.personaHistory(15),
566
- }),
567
- ),
568
- );
569
- app.put(
570
- "/api/mind/nature",
571
- wrap((req, res) => {
572
- const { note, ...value } = req.body || {};
573
- res.json(mind.nature.save(value, note || "在天性页修改"));
574
- }),
575
- );
576
- app.put(
577
- "/api/mind/settings",
578
- wrap((req, res) => {
579
- const { life: lifeSettings, budget } = req.body || {};
580
- if (lifeSettings !== undefined) life.save(lifeSettings);
581
- if (budget !== undefined) mind.budget.save(budget);
582
- res.json({ life: life.settings(), budget: mind.budget.settings() });
583
- }),
584
- );
585
- app.post(
586
- "/api/mind/reflect",
587
- wrap(async (req, res) => {
588
- if (life.busy) throw Error("TA 正在想别的事");
589
- const reason = life.eligible();
590
- if (reason && !/太近|新经历|没有新的|独处未开启|安静/.test(reason))
591
- throw Error(reason);
592
- res.json(await life.reflect());
593
- }),
594
- );
595
- app.post(
596
- "/api/mind/evolve",
597
- wrap(async (req, res) =>
598
- res.json(await life.evolve({ force: req.body?.force === true })),
599
- ),
600
- );
601
- app.post(
602
- "/api/mind/review",
603
- wrap(async (req, res) => {
604
- if (life.busy) throw Error("TA 正在想别的事");
605
- const now = life.now();
606
- res.json(
607
- await life.review({
608
- day: life.lifeDay(now),
609
- start: life.dayStart(now),
610
- end: now,
611
- }),
612
- );
613
- }),
614
- );
615
- app.post(
616
- "/api/mind/revoke",
617
- wrap((req, res) => {
618
- const { kind, id, reason } = req.body || {};
619
- if (typeof kind !== "string" || typeof id !== "string" || !id)
620
- throw Error("请选择要撤销的内容");
621
- mind.revoke(kind, id, reason || "");
622
- res.json({ ok: true });
623
- }),
624
- );
625
- app.patch(
626
- "/api/mind/thoughts/:id",
627
- wrap((req, res) => {
628
- mind.thoughts.update(req.params.id, req.body || {});
629
- chat.store.revision++;
630
- res.json({ ok: true });
631
- }),
632
- );
633
- app.delete(
634
- "/api/mind/thoughts/:id",
635
- wrap((req, res) => {
636
- mind.thoughts.remove(req.params.id);
637
- chat.store.revision++;
638
- res.json({ ok: true });
639
- }),
640
- );
641
- let previewing = false;
642
- app.post(
643
- "/api/mind/preview",
644
- wrap(async (req, res) => {
645
- const { text, history = [], nature, viewSession = "" } = req.body || {};
646
- if (
647
- typeof text !== "string" ||
648
- !text.trim() ||
649
- text.length > 1000 ||
650
- !Array.isArray(history) ||
651
- history.length > 12 ||
652
- history.some(
653
- (x) =>
654
- !x ||
655
- !["user", "assistant"].includes(x.role) ||
656
- typeof x.text !== "string" ||
657
- x.text.length > 1000,
658
- ) ||
659
- (nature !== undefined &&
660
- (typeof nature !== "object" || Array.isArray(nature))) ||
661
- typeof viewSession !== "string" ||
662
- (viewSession &&
663
- !chat.repo.db
664
- .prepare("SELECT 1 FROM sessions WHERE id=?")
665
- .get(viewSession))
666
- )
667
- throw Error("请输入 1–1000 字的试聊内容");
668
- if (previewing) {
669
- const error = Error("正在试聊,请稍等");
670
- error.status = 429;
671
- throw error;
672
- }
673
- previewing = true;
674
- const started = Date.now();
675
- try {
676
- const trace = await chat.preview({
677
- text: text.trim(),
678
- history,
679
- nature: nature || null,
680
- viewSession,
681
- });
682
- if (trace.status === "error") throw Error(trace.error || "试聊失败");
683
- const bubbles =
684
- trace.status === "previewed" ? trace.response?.bubbles || [] : [];
685
- res.json({
686
- status: trace.status,
687
- choice:
688
- trace.decision?.choice || (bubbles.length ? "speak" : "silent"),
689
- bubbles,
690
- reply: bubbles.join("\n"),
691
- appraisal: trace.decision?.appraisal || "",
692
- reason: trace.reason || "",
693
- mood: trace.affect?.mood || "",
694
- mode: trace.calls?.length ? "model" : "sample",
695
- latency: Date.now() - started,
696
- day: dayKey(Date.now(), mind.timeZone()),
697
- });
698
- } finally {
699
- previewing = false;
700
- }
701
- }),
702
- );
703
- }
1
+ import { wrap } from "../http.js";
2
+ import { mountTime } from "./time/api.js";
3
+ import { localClock } from "../core/conversation-cues.js";
4
+ import { agoLabel, elapsedLabel, JUST_NOW } from "./clock.js";
5
+ import { diffSnapshots } from "./index.js";
6
+ import { SELF_KINDS } from "./self.js";
7
+ import { THOUGHT_KINDS } from "./thoughts.js";
8
+ import { dayKey, parse, text } from "./util.js";
9
+ import {
10
+ displayNames,
11
+ displayPerson,
12
+ displaySession,
13
+ } from "../studio/display-names.js";
14
+
15
+ const RUN_ACTIVITY = {
16
+ activity: "solitude",
17
+ solitude: "solitude",
18
+ expression: "solitude",
19
+ daily: "diary",
20
+ weekly: "review",
21
+ night: "night",
22
+ };
23
+
24
+ function sessionNames(db, now) {
25
+ const people = displayNames(db, now);
26
+ return new Map(
27
+ db
28
+ .prepare("SELECT id,name FROM sessions")
29
+ .all()
30
+ .map((s) => [s.id, displaySession(s, people).name]),
31
+ );
32
+ }
33
+
34
+ function displayAhead(db, rows, now) {
35
+ const names = displayNames(db, now);
36
+ return rows.map((row) => ({
37
+ ...row,
38
+ name: names.get(String(row.subject || "")) || row.name,
39
+ }));
40
+ }
41
+
42
+ // What TA is doing this moment: a background run, a conversation being
43
+ // read, words just sent, or sleep.
44
+ function activityOf({ db, life, now, affect, words, names }) {
45
+ if (life.busy) {
46
+ const run = db
47
+ .prepare(
48
+ "SELECT kind,started FROM mind_runs WHERE status='running' ORDER BY started DESC LIMIT 1",
49
+ )
50
+ .get();
51
+ if (run)
52
+ return { kind: RUN_ACTIVITY[run.kind] || "busy", since: run.started };
53
+ }
54
+ const thinking = db
55
+ .prepare(
56
+ "SELECT session_id,time FROM core_traces WHERE status='running' AND mode IN ('live','demo') ORDER BY time DESC LIMIT 1",
57
+ )
58
+ .get();
59
+ if (thinking)
60
+ return {
61
+ kind: "thinking",
62
+ since: thinking.time,
63
+ session: thinking.session_id,
64
+ sessionName: names.get(thinking.session_id) || thinking.session_id,
65
+ };
66
+ if (words && now - words.time < 30000)
67
+ return {
68
+ kind: "speaking",
69
+ since: words.time,
70
+ session: words.session,
71
+ sessionName: words.sessionName,
72
+ };
73
+ if (affect.phase === "asleep") return { kind: "asleep" };
74
+ return { kind: "idle" };
75
+ }
76
+
77
+ export function mountMind(app, chat, life) {
78
+ const { mind } = chat;
79
+ mountTime(app, life);
80
+ // A small, cheap picture of TA for the studio: asked for on every change.
81
+ app.get(
82
+ "/api/mind/presence",
83
+ wrap((req, res) => {
84
+ const now = life.now();
85
+ const db = chat.repo.db;
86
+ const nature = mind.nature.current(now);
87
+ const affect = mind.affect.state(now, { nature });
88
+ const names = sessionNames(db, now);
89
+ const demo = Number(!!chat.store.settings().demo);
90
+ const saidRows = db
91
+ .prepare(
92
+ "SELECT session_id,time,payload FROM core_events WHERE role='assistant' AND COALESCE(json_extract(payload,'$.simulated'),0)=? ORDER BY seq DESC LIMIT 20",
93
+ )
94
+ .all(demo);
95
+ const recentWords = saidRows
96
+ .map((said) => ({
97
+ text: text(parse(said.payload, {}).text, 120),
98
+ session: said.session_id,
99
+ sessionName: names.get(said.session_id) || said.session_id,
100
+ time: said.time,
101
+ }))
102
+ .filter((item) => item.text.trim())
103
+ .slice(0, 3);
104
+ const words = recentWords[0] || null;
105
+ const thought = mind.thoughts.latest(now);
106
+ res.json({
107
+ name: nature.name,
108
+ nature: { rhythm: nature.rhythm },
109
+ busy: Boolean(life.busy),
110
+ reason: life.eligible(now),
111
+ now,
112
+ clock: localClock(now, mind.timeZone()),
113
+ affect: {
114
+ mood: affect.mood,
115
+ cause: affect.cause,
116
+ valence: affect.valence,
117
+ arousal: affect.arousal,
118
+ energy: affect.energy,
119
+ energyLabel: affect.energyLabel,
120
+ phase: affect.phase,
121
+ phaseLabel: affect.phaseLabel,
122
+ lately: affect.lately,
123
+ baseline: affect.baseline,
124
+ },
125
+ activity: activityOf({ db, life, now, affect, words, names }),
126
+ currentLife: mind.time.view({ now }),
127
+ lastWords: words,
128
+ recentWords,
129
+ thought: thought
130
+ ? {
131
+ content: thought.content,
132
+ when: elapsedLabel(thought.created, now, mind.timeZone()),
133
+ }
134
+ : null,
135
+ expecting: displayAhead(
136
+ db,
137
+ mind.anticipations.list({ now, limit: 100 }),
138
+ now,
139
+ )
140
+ .filter(
141
+ (a) =>
142
+ a.state === "pending" &&
143
+ String(a.content || "").trim() &&
144
+ a.occurrence >= now - 86400000 &&
145
+ a.occurrence <= now + 7 * 86400000,
146
+ )
147
+ .slice(0, 5)
148
+ .map((a) => ({
149
+ id: a.id,
150
+ kind: a.kind,
151
+ name: a.name,
152
+ content: a.content,
153
+ when: a.when,
154
+ })),
155
+ dayOfLife: mind.days.dayOfLife(now),
156
+ will: (() => {
157
+ const living = life.livingForView(now);
158
+ if (!living) return null;
159
+ const trace = living.thread
160
+ ? mind.meetings.trace(living.thread, {
161
+ before: now,
162
+ inclusive: true,
163
+ })
164
+ : null;
165
+ return {
166
+ ...(living.content ? { content: living.content } : {}),
167
+ ...(trace?.touched
168
+ ? { touched: trace.touched, lastSpoke: trace.lastSpoke }
169
+ : {}),
170
+ ...(living.also ? { also: living.also } : {}),
171
+ };
172
+ })(),
173
+ meaning: (() => {
174
+ const row = mind.meetings.latest({ before: now });
175
+ if (!row) return null;
176
+ return {
177
+ text: text(row.appraisal, 80),
178
+ when: elapsedLabel(row.created, now, mind.timeZone()),
179
+ recent: now - row.created < JUST_NOW,
180
+ spoke: row.choice !== "silent",
181
+ };
182
+ })(),
183
+ });
184
+ }),
185
+ );
186
+ // Everything that happened in TA's day so far, newest first.
187
+ app.get(
188
+ "/api/mind/today",
189
+ wrap((req, res) => {
190
+ const now = life.now();
191
+ const start = life.dayStart(now);
192
+ const db = chat.repo.db;
193
+ const names = sessionNames(db, now);
194
+ const where = (session) => ({
195
+ session,
196
+ sessionName: names.get(session) || session,
197
+ });
198
+ const items = [];
199
+ for (const c of db
200
+ .prepare(
201
+ "SELECT * FROM mind_choices WHERE created>=? AND created<=? ORDER BY created DESC LIMIT 80",
202
+ )
203
+ .all(start, now))
204
+ items.push({
205
+ type: "choice",
206
+ time: c.created,
207
+ choice: c.choice,
208
+ reason: c.reason,
209
+ appraisal: c.appraisal,
210
+ occasion: c.occasion,
211
+ ...where(c.session_id),
212
+ });
213
+ for (const a of db
214
+ .prepare(
215
+ "SELECT * FROM mind_affect WHERE created>=? AND created<=? ORDER BY created DESC LIMIT 60",
216
+ )
217
+ .all(start, now))
218
+ items.push({
219
+ type: "feeling",
220
+ time: a.created,
221
+ feeling: a.feeling,
222
+ cause: a.cause,
223
+ valence: a.valence,
224
+ intensity: a.intensity,
225
+ origin: a.origin,
226
+ });
227
+ for (const r of db
228
+ .prepare(
229
+ "SELECT * FROM mind_runs WHERE started>=? AND started<=? AND NOT (kind='activity' AND status IN ('reading','engaged')) ORDER BY started DESC LIMIT 30",
230
+ )
231
+ .all(start, now))
232
+ items.push({
233
+ type: "run",
234
+ time: r.started,
235
+ kind: r.kind,
236
+ status: r.status,
237
+ reason: r.reason,
238
+ });
239
+ for (const t of db
240
+ .prepare(
241
+ "SELECT session_id,time,json_extract(data,'$.reason') reason FROM core_traces WHERE status='glanced' AND time>=? AND time<=? ORDER BY time DESC LIMIT 40",
242
+ )
243
+ .all(start, now))
244
+ items.push({
245
+ type: "glance",
246
+ time: t.time,
247
+ reason: t.reason,
248
+ ...where(t.session_id),
249
+ });
250
+ for (const a of db
251
+ .prepare(
252
+ "SELECT * FROM mind_anticipations WHERE closed_at>=? AND closed_at<=? AND status IN ('done','missed','let_go') ORDER BY closed_at DESC LIMIT 20",
253
+ )
254
+ .all(start, now))
255
+ items.push({
256
+ type: "ahead",
257
+ time: a.closed_at,
258
+ status: a.status,
259
+ content: a.content,
260
+ note: a.closed_note,
261
+ });
262
+ items.sort((a, b) => b.time - a.time);
263
+ res.json({ day: life.lifeDay(now), start, items: items.slice(0, 150) });
264
+ }),
265
+ );
266
+ // One person as TA knows them: the feeling, where it came from, what TA
267
+ // remembers about them and what TA is waiting for with them.
268
+ app.get(
269
+ "/api/mind/people/:id",
270
+ wrap((req, res) => {
271
+ const now = life.now();
272
+ const id = String(req.params.id);
273
+ const person = mind.bonds.person(id, now);
274
+ if (!person) {
275
+ const error = Error("TA 还不认识这个人");
276
+ error.status = 404;
277
+ throw error;
278
+ }
279
+ const db = chat.repo.db;
280
+ const names = sessionNames(db, now);
281
+ res.json({
282
+ person: {
283
+ ...displayPerson(person, displayNames(db, now)),
284
+ places: person.sessions.map((s) => ({
285
+ id: s,
286
+ name: names.get(s) || s,
287
+ })),
288
+ },
289
+ changes: mind.bonds.changes("person", id, 60),
290
+ memories: db
291
+ .prepare(
292
+ "SELECT id,session_id,content,type,confidence,importance,status,discretion,locked,created,superseded_by FROM core_memories WHERE subject=? AND status IN ('confirmed','superseded') ORDER BY CASE status WHEN 'confirmed' THEN 0 ELSE 1 END, created DESC LIMIT 80",
293
+ )
294
+ .all(id)
295
+ .map((m) => ({
296
+ ...m,
297
+ sessionName: names.get(m.session_id) || m.session_id,
298
+ when: agoLabel(now - m.created),
299
+ })),
300
+ anticipations: displayAhead(
301
+ db,
302
+ mind.anticipations.list({ now, limit: 300 }),
303
+ now,
304
+ )
305
+ .filter((a) => String(a.subject) === id)
306
+ .slice(0, 30),
307
+ meetings: mind.meetings.withPerson(id, { before: now }).map((m) => ({
308
+ ...m,
309
+ sessionName: names.get(m.sessionId) || m.sessionId,
310
+ })),
311
+ });
312
+ }),
313
+ );
314
+ app.get(
315
+ "/api/mind",
316
+ wrap((req, res) => {
317
+ const now = life.now();
318
+ const nature = mind.nature.current(now);
319
+ const names = sessionNames(chat.repo.db, now);
320
+ res.json({
321
+ clock: localClock(now, mind.timeZone()),
322
+ affect: mind.affect.state(now, { nature }),
323
+ moods: mind.affect.history({ limit: 24 }),
324
+ choices: mind.choices({ limit: 30 }).map((c) => ({
325
+ ...c,
326
+ sessionName: names.get(c.session_id) || c.session_id,
327
+ })),
328
+ attention: chat.repo.db
329
+ .prepare("SELECT * FROM mind_attention")
330
+ .all()
331
+ .filter((a) => names.has(a.session_id))
332
+ .map((a) => ({
333
+ session: a.session_id,
334
+ name: names.get(a.session_id),
335
+ lookedAt: a.looked_at,
336
+ unread: mind.unread(a.session_id, { now }).length,
337
+ })),
338
+ nature: {
339
+ name: nature.name,
340
+ rhythm: nature.rhythm,
341
+ version: nature.version,
342
+ },
343
+ life: life.settings(),
344
+ budget: mind.budget.report(now),
345
+ reason: life.eligible(now),
346
+ busy: life.busy,
347
+ dayOfLife: mind.days.dayOfLife(now),
348
+ // The week ahead as she sees it, wherever each thing was said.
349
+ expecting: displayAhead(
350
+ chat.repo.db,
351
+ mind.anticipations.list({ now, limit: 100 }),
352
+ now,
353
+ )
354
+ .filter(
355
+ (a) =>
356
+ a.state === "pending" &&
357
+ a.occurrence >= now - 86400000 &&
358
+ a.occurrence <= now + 7 * 86400000,
359
+ )
360
+ .slice(0, 8),
361
+ counts: {
362
+ self: mind.self.active({ before: now, now, limit: 500 }).length,
363
+ faded: mind.self.dormant({ before: now, now }).length,
364
+ people: chat.repo.db
365
+ .prepare("SELECT COUNT(*) n FROM mind_people")
366
+ .get().n,
367
+ thoughts: chat.repo.db
368
+ .prepare("SELECT COUNT(*) n FROM mind_thoughts WHERE hidden=0")
369
+ .get().n,
370
+ diaries: chat.repo.db
371
+ .prepare("SELECT COUNT(DISTINCT day) n FROM mind_diary")
372
+ .get().n,
373
+ chapters: life.chapters().length,
374
+ reviews: chat.repo.db
375
+ .prepare("SELECT COUNT(*) n FROM mind_periods WHERE level='week'")
376
+ .get().n,
377
+ anticipations: chat.repo.db
378
+ .prepare(
379
+ "SELECT COUNT(*) n FROM mind_anticipations WHERE status='pending'",
380
+ )
381
+ .get().n,
382
+ },
383
+ kinds: { self: SELF_KINDS, thoughts: THOUGHT_KINDS },
384
+ });
385
+ }),
386
+ );
387
+ // A page asks only for the projections it renders. The dock shares presence;
388
+ // weather and notes don't need unread messages, task history or self counts.
389
+ app.get(
390
+ "/api/mind/mood",
391
+ wrap((req, res) => {
392
+ const now = life.now(),
393
+ nature = mind.nature.current(now);
394
+ res.json({
395
+ clock: localClock(now, mind.timeZone()),
396
+ affect: mind.affect.state(now, { nature }),
397
+ moods: mind.affect.history({ limit: 24 }),
398
+ kinds: { thoughts: THOUGHT_KINDS },
399
+ });
400
+ }),
401
+ );
402
+ app.get(
403
+ "/api/mind/thoughts",
404
+ wrap((req, res) => {
405
+ const q = String(req.query.q || "").slice(0, 200),
406
+ before = Number(req.query.before) || Number.MAX_SAFE_INTEGER;
407
+ res.json(mind.thoughts.list({ before, q, limit: 30 }));
408
+ }),
409
+ );
410
+ app.get(
411
+ "/api/mind/self",
412
+ wrap((req, res) => {
413
+ const now = life.now();
414
+ const weighed = new Map(
415
+ mind.self.annotated({ now }).map((t) => [t.thread, t]),
416
+ );
417
+ res.json({
418
+ threads: mind.self
419
+ .latest()
420
+ .map((t) => {
421
+ const w = weighed.get(t.thread);
422
+ return {
423
+ ...t,
424
+ versions: mind.self.history(t.thread).length,
425
+ salience: w?.salience ?? null,
426
+ core: !!w?.core,
427
+ faded: !!w?.faded,
428
+ fading: !!w && !w.core && !w.faded && w.salience < 0.2,
429
+ };
430
+ })
431
+ .sort(
432
+ (a, b) =>
433
+ (b.salience ?? -1) - (a.salience ?? -1) ||
434
+ b.strength - a.strength ||
435
+ b.created - a.created,
436
+ ),
437
+ revoked: mind.revocations().filter((r) => r.target_kind === "self"),
438
+ kinds: SELF_KINDS,
439
+ });
440
+ }),
441
+ );
442
+ app.get(
443
+ "/api/mind/self/:thread",
444
+ wrap((req, res) => res.json(mind.self.history(req.params.thread))),
445
+ );
446
+ app.get(
447
+ "/api/mind/bonds",
448
+ wrap((req, res) => {
449
+ const sessions = chat.repo.db
450
+ .prepare("SELECT id,name,kind FROM sessions WHERE archived=0")
451
+ .all();
452
+ const names = displayNames(chat.repo.db, life.now());
453
+ res.json({
454
+ people: mind.bonds
455
+ .people({ limit: 200 })
456
+ .map((person) => displayPerson(person, names)),
457
+ groups: sessions.map((s) => ({
458
+ session: s.id,
459
+ name: displaySession(s, names).name,
460
+ kind: s.kind,
461
+ bond: mind.bonds.group(s.id),
462
+ face: mind.faces.current(s.id),
463
+ })),
464
+ });
465
+ }),
466
+ );
467
+ app.get(
468
+ "/api/mind/bonds/:kind/:id",
469
+ wrap((req, res) => {
470
+ if (!["person", "group"].includes(req.params.kind))
471
+ throw Error("类型无效");
472
+ res.json(mind.bonds.changes(req.params.kind, req.params.id));
473
+ }),
474
+ );
475
+ app.get(
476
+ "/api/mind/faces/:session",
477
+ wrap((req, res) => res.json(mind.faces.history(req.params.session))),
478
+ );
479
+ app.get(
480
+ "/api/mind/life",
481
+ wrap((req, res) => {
482
+ const q = String(req.query.q || "").slice(0, 200);
483
+ const before = Number(req.query.before) || Number.MAX_SAFE_INTEGER;
484
+ const now = life.now();
485
+ res.json({
486
+ diaries: life.diaries({ limit: 30 }).map((d) => ({
487
+ ...d,
488
+ actions: mind.time.lived({
489
+ since: life.dayStart(d.created),
490
+ before: d.created,
491
+ }),
492
+ })),
493
+ creations: life.activities.list({ before: now }),
494
+ chapters: life.chapters().map((c) => ({
495
+ ...c,
496
+ versions: life.chapterVersions(c.chapter).length,
497
+ })),
498
+ reviews: mind.periods.reviews({ limit: 12 }),
499
+ story: mind.periods.story(),
500
+ storyVersions: mind.periods.storyVersions().length,
501
+ anticipations: displayAhead(
502
+ chat.repo.db,
503
+ mind.anticipations.list({ now, limit: 60 }),
504
+ now,
505
+ ),
506
+ dayOfLife: mind.days.dayOfLife(now),
507
+ snapshots: chat.repo.db
508
+ .prepare(
509
+ "SELECT day,created FROM mind_snapshots ORDER BY day DESC LIMIT 60",
510
+ )
511
+ .all(),
512
+ thoughts: mind.thoughts.list({ before, q, limit: 30 }),
513
+ readings: mind.reading.recent({ limit: 30 }),
514
+ unread: mind.reading.unreadCount(),
515
+ runs: life.runs(60),
516
+ });
517
+ }),
518
+ );
519
+ app.get(
520
+ "/api/mind/story",
521
+ wrap((req, res) => res.json(mind.periods.storyVersions())),
522
+ );
523
+ app.get(
524
+ "/api/mind/chapters/:number",
525
+ wrap((req, res) =>
526
+ res.json(life.chapterVersions(Number(req.params.number))),
527
+ ),
528
+ );
529
+ app.get(
530
+ "/api/mind/day/:day",
531
+ wrap((req, res) => {
532
+ const day = String(req.params.day);
533
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw Error("日期无效");
534
+ const snapshot = mind.snapshotOf(day);
535
+ const previous = chat.repo.db
536
+ .prepare(
537
+ "SELECT day FROM mind_snapshots WHERE day<? ORDER BY day DESC LIMIT 1",
538
+ )
539
+ .get(day)?.day;
540
+ const yesterday = previous ? mind.snapshotOf(previous) : null;
541
+ const present = (snap) => {
542
+ if (!snap) return null;
543
+ return { ...snap, livingFor: mind.livedThen(snap) };
544
+ };
545
+ res.json({
546
+ day,
547
+ diary:
548
+ life.diaries({ before: day, limit: 1 }).find((d) => d.day === day) ||
549
+ null,
550
+ snapshot: present(snapshot),
551
+ yesterday: present(yesterday),
552
+ change: diffSnapshots(yesterday, snapshot),
553
+ });
554
+ }),
555
+ );
556
+ app.get(
557
+ "/api/mind/nature",
558
+ wrap((req, res) =>
559
+ res.json({
560
+ nature: mind.nature.current(),
561
+ versions: mind.nature.versions(),
562
+ livedTraits: mind.traits.current(),
563
+ traitHistory: mind.traits.history(30),
564
+ livedPersona: mind.traits.persona()?.content || "",
565
+ personaHistory: mind.traits.personaHistory(15),
566
+ }),
567
+ ),
568
+ );
569
+ app.put(
570
+ "/api/mind/nature",
571
+ wrap((req, res) => {
572
+ const { note, ...value } = req.body || {};
573
+ res.json(mind.nature.save(value, note || "在天性页修改"));
574
+ }),
575
+ );
576
+ app.put(
577
+ "/api/mind/settings",
578
+ wrap((req, res) => {
579
+ const { life: lifeSettings, budget } = req.body || {};
580
+ if (lifeSettings !== undefined) life.save(lifeSettings);
581
+ if (budget !== undefined) mind.budget.save(budget);
582
+ res.json({ life: life.settings(), budget: mind.budget.settings() });
583
+ }),
584
+ );
585
+ app.post(
586
+ "/api/mind/reflect",
587
+ wrap(async (req, res) => {
588
+ if (life.busy) throw Error("TA 正在想别的事");
589
+ const reason = life.eligible();
590
+ if (reason && !/太近|新经历|没有新的|独处未开启|安静/.test(reason))
591
+ throw Error(reason);
592
+ res.json(await life.reflect());
593
+ }),
594
+ );
595
+ app.post(
596
+ "/api/mind/evolve",
597
+ wrap(async (req, res) =>
598
+ res.json(await life.evolve({ force: req.body?.force === true })),
599
+ ),
600
+ );
601
+ app.post(
602
+ "/api/mind/review",
603
+ wrap(async (req, res) => {
604
+ if (life.busy) throw Error("TA 正在想别的事");
605
+ const now = life.now();
606
+ res.json(
607
+ await life.review({
608
+ day: life.lifeDay(now),
609
+ start: life.dayStart(now),
610
+ end: now,
611
+ }),
612
+ );
613
+ }),
614
+ );
615
+ app.post(
616
+ "/api/mind/revoke",
617
+ wrap((req, res) => {
618
+ const { kind, id, reason } = req.body || {};
619
+ if (typeof kind !== "string" || typeof id !== "string" || !id)
620
+ throw Error("请选择要撤销的内容");
621
+ mind.revoke(kind, id, reason || "");
622
+ res.json({ ok: true });
623
+ }),
624
+ );
625
+ app.patch(
626
+ "/api/mind/thoughts/:id",
627
+ wrap((req, res) => {
628
+ mind.thoughts.update(req.params.id, req.body || {});
629
+ chat.store.revision++;
630
+ res.json({ ok: true });
631
+ }),
632
+ );
633
+ app.delete(
634
+ "/api/mind/thoughts/:id",
635
+ wrap((req, res) => {
636
+ mind.thoughts.remove(req.params.id);
637
+ chat.store.revision++;
638
+ res.json({ ok: true });
639
+ }),
640
+ );
641
+ let previewing = false;
642
+ app.post(
643
+ "/api/mind/preview",
644
+ wrap(async (req, res) => {
645
+ const { text, history = [], nature, viewSession = "" } = req.body || {};
646
+ if (
647
+ typeof text !== "string" ||
648
+ !text.trim() ||
649
+ text.length > 1000 ||
650
+ !Array.isArray(history) ||
651
+ history.length > 12 ||
652
+ history.some(
653
+ (x) =>
654
+ !x ||
655
+ !["user", "assistant"].includes(x.role) ||
656
+ typeof x.text !== "string" ||
657
+ x.text.length > 1000,
658
+ ) ||
659
+ (nature !== undefined &&
660
+ (typeof nature !== "object" || Array.isArray(nature))) ||
661
+ typeof viewSession !== "string" ||
662
+ (viewSession &&
663
+ !chat.repo.db
664
+ .prepare("SELECT 1 FROM sessions WHERE id=?")
665
+ .get(viewSession))
666
+ )
667
+ throw Error("请输入 1–1000 字的试聊内容");
668
+ if (previewing) {
669
+ const error = Error("正在试聊,请稍等");
670
+ error.status = 429;
671
+ throw error;
672
+ }
673
+ previewing = true;
674
+ const started = Date.now();
675
+ try {
676
+ const trace = await chat.preview({
677
+ text: text.trim(),
678
+ history,
679
+ nature: nature || null,
680
+ viewSession,
681
+ });
682
+ if (trace.status === "error") throw Error(trace.error || "试聊失败");
683
+ const bubbles =
684
+ trace.status === "previewed" ? trace.response?.bubbles || [] : [];
685
+ res.json({
686
+ status: trace.status,
687
+ choice:
688
+ trace.decision?.choice || (bubbles.length ? "speak" : "silent"),
689
+ bubbles,
690
+ reply: bubbles.join("\n"),
691
+ appraisal: trace.decision?.appraisal || "",
692
+ reason: trace.reason || "",
693
+ mood: trace.affect?.mood || "",
694
+ mode: trace.calls?.length ? "model" : "sample",
695
+ latency: Date.now() - started,
696
+ day: dayKey(Date.now(), mind.timeZone()),
697
+ });
698
+ } finally {
699
+ previewing = false;
700
+ }
701
+ }),
702
+ );
703
+ }