luckytri 1.0.1 → 1.0.3

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 (63) hide show
  1. package/docs/en/CHANGELOG.md +13 -0
  2. package/docs/en/guide.md +16 -0
  3. package/docs/en/her-life.md +2 -0
  4. package/docs/en/webui.md +2 -0
  5. package/docs/zh/CHANGELOG.md +13 -0
  6. package/docs/zh/guide.md +17 -1
  7. package/docs/zh/her-life.md +4 -2
  8. package/docs/zh/webui.md +2 -0
  9. package/package.json +110 -109
  10. package/public/app/assets/ChatsPage-B83Evc79.js +3 -0
  11. package/public/app/assets/{Empty-SkA8PyMo.js → Empty-ddEfu0w8.js} +1 -1
  12. package/public/app/assets/{Field-BjLhi8pL.js → Field-mIhV5YBA.js} +1 -1
  13. package/public/app/assets/HeartPage-BGEn24rc.js +1 -0
  14. package/public/app/assets/LifePage-BleqPj4O.js +1 -0
  15. package/public/app/assets/MemoryPage-BM3-0_lF.js +1 -0
  16. package/public/app/assets/{NaturePage-CTXHCE2D.css → NaturePage-CHkpb5NK.css} +1 -1
  17. package/public/app/assets/NaturePage-CxxMnQIc.js +3 -0
  18. package/public/app/assets/PeoplePage-D12cvuy7.js +1 -0
  19. package/public/app/assets/{PeoplePage-BmUxkrOU.css → PeoplePage-DDDHESQp.css} +1 -1
  20. package/public/app/assets/{PluginsPage-BhVm1SUi.js → PluginsPage-DE_-Q3ra.js} +1 -1
  21. package/public/app/assets/SystemPage-BWQKEQRU.js +1 -0
  22. package/public/app/assets/{SystemPage-5yYqyUgR.css → SystemPage-Be1a6UDP.css} +1 -1
  23. package/public/app/assets/TimePage-Dzt8t8kL.js +3 -0
  24. package/public/app/assets/index-oLIXWxsn.js +4 -0
  25. package/public/app/assets/{knowledge-DNDLyN9m.js → knowledge-Dvtmpd45.js} +1 -1
  26. package/public/app/assets/{media-CKVAvML2.js → media-keE52cIX.js} +1 -1
  27. package/public/app/assets/mind-DYRfFMwh.js +1 -0
  28. package/public/app/index.html +3 -3
  29. package/public/guide.en.html +57 -3
  30. package/public/guide.html +36 -4
  31. package/public/tutorial.en.md +16 -0
  32. package/public/tutorial.md +17 -1
  33. package/scripts/import-data.js +128 -0
  34. package/server/app.js +6 -1
  35. package/server/core/persona-manager.js +20 -5
  36. package/server/i18n/errors.js +49 -2
  37. package/server/index.js +46 -2
  38. package/server/knowledge/schema.js +12 -8
  39. package/server/mind/api.js +1 -0
  40. package/server/mind/faces.js +257 -22
  41. package/server/mind/life/context.js +9 -6
  42. package/server/mind/life/growth.js +4 -3
  43. package/server/mind/nature.js +77 -2
  44. package/server/mind/schema.js +3 -0
  45. package/server/mind/view.js +3 -0
  46. package/server/storage/archive.js +5 -4
  47. package/server/storage/backup-cleanup.js +1 -0
  48. package/server/storage/data-package.js +298 -0
  49. package/server/storage/data-transfer-api.js +50 -0
  50. package/server/storage/data-transfer-worker.js +18 -0
  51. package/server/storage/data-transfer.js +415 -0
  52. package/server/storage/store.js +5 -2
  53. package/server/studio/updates.js +133 -0
  54. package/public/app/assets/ChatsPage-B9Odvzfz.js +0 -3
  55. package/public/app/assets/HeartPage-CscKqMsr.js +0 -1
  56. package/public/app/assets/LifePage-BHCmBHlH.js +0 -1
  57. package/public/app/assets/MemoryPage-Bhs2xa1k.js +0 -1
  58. package/public/app/assets/NaturePage-CaPIar_5.js +0 -3
  59. package/public/app/assets/PeoplePage-CuwSSVeX.js +0 -1
  60. package/public/app/assets/SystemPage-Chm5fiGP.js +0 -1
  61. package/public/app/assets/TimePage-BUm4eUzB.js +0 -3
  62. package/public/app/assets/formatters-ZmW_xFHw.js +0 -1
  63. package/public/app/assets/index-BIAdfObg.js +0 -4
@@ -0,0 +1,415 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { randomUUID } from "node:crypto";
3
+ import {
4
+ createReadStream,
5
+ createWriteStream,
6
+ existsSync,
7
+ mkdirSync,
8
+ readFileSync,
9
+ writeFileSync,
10
+ readdirSync,
11
+ lstatSync,
12
+ rmSync,
13
+ renameSync,
14
+ } from "node:fs";
15
+ import { join, resolve, relative, isAbsolute } from "node:path";
16
+ import { pipeline } from "node:stream/promises";
17
+ import { Transform } from "node:stream";
18
+ import { runtimePaths } from "../paths.js";
19
+ import { packageHeader } from "./data-package.js";
20
+ import { DatabaseSync } from "node:sqlite";
21
+
22
+ const ID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
23
+ const TTL = 3600000;
24
+ export const IMPORT_FAILURE =
25
+ "导入未完成,原数据已保留。请重新上传或查看运行日志。";
26
+ export const IMPORT_START_FAILURE =
27
+ "导入启动未完成,未替换运行数据。请重新启动实例。";
28
+ export const IMPORT_RESTART_FAILURE =
29
+ "数据已导入,但自动重启未完成。请手动重新启动实例。";
30
+ export const transferRoot = () => join(runtimePaths().data, "transfers");
31
+ export function readTransferJob(root, id) {
32
+ if (!ID.test(String(id))) throw Error("数据任务不存在");
33
+ const job = JSON.parse(readFileSync(join(root, id, "job.json"), "utf8"));
34
+ if (job.id !== id) throw Error("数据任务不存在");
35
+ return job;
36
+ }
37
+ export function writeTransferJob(root, job) {
38
+ if (!ID.test(job.id)) throw Error("数据任务不存在");
39
+ const temporary = join(root, job.id, `.job-${randomUUID()}.partial`);
40
+ try {
41
+ writeFileSync(temporary, JSON.stringify(job), {
42
+ mode: 0o600,
43
+ flush: true,
44
+ flag: "wx",
45
+ });
46
+ renameSync(temporary, join(root, job.id, "job.json"));
47
+ } finally {
48
+ rmSync(temporary, { force: true });
49
+ }
50
+ }
51
+ function work(payload) {
52
+ return new Promise((resolve, reject) => {
53
+ const worker = new Worker(
54
+ new URL("./data-transfer-worker.js", import.meta.url),
55
+ { workerData: payload, stdout: true, stderr: true },
56
+ );
57
+ // Staging migrations must not interleave their console output with the
58
+ // service or a test runner's protocol. Results travel through parentPort.
59
+ worker.stdout.resume();
60
+ worker.stderr.resume();
61
+ worker.once("message", ({ result, error }) =>
62
+ error ? reject(Error(error)) : resolve(result),
63
+ );
64
+ worker.once("error", reject);
65
+ worker.once("exit", (code) => {
66
+ if (code) reject(Error("数据处理失败"));
67
+ });
68
+ });
69
+ }
70
+ export function createDataTransfer({
71
+ source = runtimePaths().database,
72
+ backups = runtimePaths().backups,
73
+ directory = transferRoot(),
74
+ backup,
75
+ cleanup,
76
+ onApply,
77
+ run = work,
78
+ now = Date.now,
79
+ maxUploadBytes,
80
+ } = {}) {
81
+ const root = resolve(directory);
82
+ mkdirSync(root, { recursive: true, mode: 0o700 });
83
+ let active = false;
84
+ const maxBytes =
85
+ maxUploadBytes ??
86
+ Math.floor(
87
+ Math.min(
88
+ 100,
89
+ Math.max(1, Number(process.env.DATA_TRANSFER_MAX_GB) || 10),
90
+ ) * 1073741824,
91
+ );
92
+ const get = (id) => {
93
+ try {
94
+ return readTransferJob(root, id);
95
+ } catch {
96
+ throw Error("数据任务不存在");
97
+ }
98
+ };
99
+ const save = (job) => {
100
+ writeTransferJob(root, job);
101
+ return job;
102
+ };
103
+ const publicJob = (job) => {
104
+ const { manifest, ownerPid, ...rest } = job;
105
+ return rest;
106
+ };
107
+ const check = () => {
108
+ if (active || backup?.running || cleanup?.running)
109
+ throw Error("数据处理或备份正在进行,请稍后再试");
110
+ if (source === ":memory:") throw Error("当前实例不支持文件导入导出");
111
+ };
112
+ const prune = () => {
113
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
114
+ if (!entry.isDirectory() || !ID.test(entry.name)) continue;
115
+ const path = join(root, entry.name);
116
+ const part = relative(root, resolve(path));
117
+ if (
118
+ !part ||
119
+ part.startsWith("..") ||
120
+ isAbsolute(part) ||
121
+ lstatSync(path).isSymbolicLink()
122
+ )
123
+ continue;
124
+ try {
125
+ const job = get(entry.name);
126
+ if (
127
+ now() - (job.applied || job.readyAt || job.created) > TTL &&
128
+ !["processing", "uploading", "queued"].includes(job.status)
129
+ )
130
+ rmSync(path, { recursive: true, force: true });
131
+ } catch {
132
+ /* Ignore incomplete metadata while a job is publishing it. */
133
+ }
134
+ }
135
+ };
136
+ const clearMigrationCopies = (job) => {
137
+ const dir = join(root, job.id, "backups");
138
+ const part = relative(root, resolve(dir));
139
+ if (
140
+ part &&
141
+ !part.startsWith("..") &&
142
+ !isAbsolute(part) &&
143
+ existsSync(dir) &&
144
+ lstatSync(dir).isDirectory() &&
145
+ !lstatSync(dir).isSymbolicLink()
146
+ )
147
+ try {
148
+ rmSync(dir, { recursive: true, force: true });
149
+ } catch {
150
+ return false;
151
+ }
152
+ return true;
153
+ };
154
+ const clearFiles = (job) => {
155
+ let cleared = true;
156
+ for (const file of [
157
+ "upload",
158
+ "data.db",
159
+ "data.db.json",
160
+ "data.db-wal",
161
+ "data.db-shm",
162
+ ])
163
+ try {
164
+ rmSync(join(root, job.id, file), { force: true });
165
+ } catch {
166
+ cleared = false;
167
+ }
168
+ return clearMigrationCopies(job) && cleared;
169
+ };
170
+ const create = (kind, name = "") => {
171
+ prune();
172
+ // Keep at most one unused file of each kind, rather than accumulating
173
+ // multi-GiB previews every time the user picks another file.
174
+ for (const id of readdirSync(root).filter((id) => ID.test(id))) {
175
+ const previous = get(id);
176
+ if (previous.kind === kind && previous.status === "ready") {
177
+ if (!clearFiles(previous))
178
+ throw Error("临时数据文件正在使用,请稍后再试");
179
+ save({ ...previous, status: "expired" });
180
+ }
181
+ }
182
+ const id = randomUUID();
183
+ mkdirSync(join(root, id), { mode: 0o700 });
184
+ return save({
185
+ id,
186
+ kind,
187
+ name,
188
+ created: now(),
189
+ ownerPid: process.pid,
190
+ status: kind === "export" ? "processing" : "uploading",
191
+ });
192
+ };
193
+ const processJob = async (job) => {
194
+ try {
195
+ const result = await run({
196
+ kind: job.kind,
197
+ source,
198
+ backups,
199
+ target: join(root, job.id, "data.db"),
200
+ upload: join(root, job.id, "upload"),
201
+ });
202
+ rmSync(join(root, job.id, "upload"), { force: true });
203
+ clearMigrationCopies(job);
204
+ save({ ...job, status: "ready", readyAt: now(), ...result });
205
+ } catch (error) {
206
+ clearFiles(job);
207
+ try {
208
+ save({
209
+ ...job,
210
+ status: "error",
211
+ error: error.message || "数据处理失败",
212
+ });
213
+ } catch {
214
+ console.error("数据任务状态保存失败");
215
+ }
216
+ } finally {
217
+ active = false;
218
+ }
219
+ };
220
+ const alive = (pid) => {
221
+ if (!Number.isInteger(pid) || pid <= 0) return false;
222
+ try {
223
+ process.kill(pid, 0);
224
+ return true;
225
+ } catch (error) {
226
+ return error.code !== "ESRCH";
227
+ }
228
+ };
229
+ for (const id of readdirSync(root).filter((id) => ID.test(id))) {
230
+ try {
231
+ const job = get(id);
232
+ if (
233
+ job.kind === "import" &&
234
+ job.status === "queued" &&
235
+ source !== ":memory:" &&
236
+ existsSync(source)
237
+ ) {
238
+ const db = new DatabaseSync(source, { readOnly: true });
239
+ let marker;
240
+ try {
241
+ marker = JSON.parse(
242
+ db.prepare("SELECT value FROM settings WHERE id=1").get().value,
243
+ ).dataImportId;
244
+ } finally {
245
+ db.close();
246
+ }
247
+ if (marker === id) {
248
+ save({ ...job, status: "done", applied: now() });
249
+ continue;
250
+ }
251
+ }
252
+ if (
253
+ ["processing", "uploading", "queued"].includes(job.status) &&
254
+ !alive(job.ownerPid)
255
+ ) {
256
+ clearFiles(job);
257
+ save({
258
+ ...job,
259
+ status: "error",
260
+ readyAt: now(),
261
+ error: "数据处理被中断,请重新操作",
262
+ });
263
+ }
264
+ } catch {}
265
+ }
266
+ return {
267
+ get busy() {
268
+ return active;
269
+ },
270
+ info() {
271
+ prune();
272
+ const imports = readdirSync(root)
273
+ .filter((id) => ID.test(id))
274
+ .map((id) => {
275
+ try {
276
+ return get(id);
277
+ } catch {
278
+ return null;
279
+ }
280
+ })
281
+ .filter(
282
+ (job) =>
283
+ job?.kind === "import" && ["done", "error"].includes(job.status),
284
+ );
285
+ imports.sort((a, b) => b.created - a.created);
286
+ return {
287
+ available: source !== ":memory:",
288
+ maxBytes,
289
+ busy: active,
290
+ lastImport: imports[0] ? publicJob(imports[0]) : null,
291
+ };
292
+ },
293
+ job(id) {
294
+ return publicJob(get(id));
295
+ },
296
+ export() {
297
+ check();
298
+ active = true;
299
+ let job;
300
+ try {
301
+ job = create("export");
302
+ } catch (error) {
303
+ active = false;
304
+ throw error;
305
+ }
306
+ void processJob(job);
307
+ return publicJob(job);
308
+ },
309
+ async upload(stream, { bytes = 0, name = "" } = {}) {
310
+ check();
311
+ if (bytes > maxBytes) throw Error("数据文件超过导入大小限制");
312
+ active = true;
313
+ let job;
314
+ try {
315
+ job = create(
316
+ "import",
317
+ String(name).replace(/[\\/]/g, "_").slice(0, 180),
318
+ );
319
+ } catch (error) {
320
+ active = false;
321
+ throw error;
322
+ }
323
+ let total = 0;
324
+ const limit = new Transform({
325
+ transform(chunk, _encoding, done) {
326
+ total += chunk.length;
327
+ done(
328
+ total > maxBytes ? Error("数据文件超过导入大小限制") : null,
329
+ chunk,
330
+ );
331
+ },
332
+ });
333
+ try {
334
+ await pipeline(
335
+ stream,
336
+ limit,
337
+ createWriteStream(join(root, job.id, "upload"), {
338
+ flags: "wx",
339
+ mode: 0o600,
340
+ }),
341
+ );
342
+ if (!total) throw Error("数据文件为空");
343
+ save({ ...job, status: "processing" });
344
+ void processJob(job);
345
+ return publicJob({ ...job, status: "processing" });
346
+ } catch (error) {
347
+ active = false;
348
+ rmSync(join(root, job.id, "upload"), { force: true });
349
+ save({
350
+ ...job,
351
+ status: "error",
352
+ error: error.code === "ENOSPC" ? "磁盘空间不足" : "数据上传失败",
353
+ });
354
+ throw Error("数据上传失败");
355
+ }
356
+ },
357
+ async download(id, res) {
358
+ if (active) throw Error("数据处理或备份正在进行,请稍后再试");
359
+ const job = get(id);
360
+ if (
361
+ job.kind !== "export" ||
362
+ job.status !== "ready" ||
363
+ now() - (job.readyAt || job.created) > TTL
364
+ )
365
+ throw Error("导出文件尚未就绪或已过期");
366
+ const header = packageHeader(job.manifest);
367
+ res.setHeader("Content-Type", "application/octet-stream");
368
+ res.setHeader(
369
+ "Content-Disposition",
370
+ `attachment; filename="luckytri-data-${new Date(job.created).toISOString().slice(0, 10)}.luckytri"`,
371
+ );
372
+ res.setHeader("Content-Length", header.length + job.bytes);
373
+ active = true;
374
+ try {
375
+ res.write(header);
376
+ await pipeline(createReadStream(join(root, id, "data.db")), res);
377
+ clearFiles(job);
378
+ save({ ...job, status: "done" });
379
+ } finally {
380
+ active = false;
381
+ }
382
+ },
383
+ async apply(id) {
384
+ check();
385
+ const job = get(id);
386
+ if (!onApply) throw Error("当前实例不支持自动导入,请使用恢复命令");
387
+ if (
388
+ job.kind !== "import" ||
389
+ job.status !== "ready" ||
390
+ now() - (job.readyAt || job.created) > TTL
391
+ )
392
+ throw Error("导入数据尚未就绪或已过期");
393
+ active = true;
394
+ save({ ...job, status: "queued" });
395
+ try {
396
+ const owner = await onApply(id);
397
+ if (Number.isInteger(owner) && owner > 0)
398
+ save({ ...job, status: "queued", ownerPid: owner });
399
+ } catch (error) {
400
+ active = false;
401
+ save(job);
402
+ throw error;
403
+ }
404
+ return { queued: true, id };
405
+ },
406
+ discard(id) {
407
+ const job = get(id);
408
+ if (["processing", "uploading", "queued"].includes(job.status))
409
+ throw Error("数据处理正在进行,请稍后再试");
410
+ if (!clearFiles(job)) throw Error("临时数据文件正在使用,请稍后再试");
411
+ save({ ...job, status: "expired" });
412
+ return { ok: true };
413
+ },
414
+ };
415
+ }
@@ -6,8 +6,11 @@ import { summarizeGroupStyle } from "../core/group-style.js";
6
6
  import { isGroupSession } from "../channels/session-key.js";
7
7
  import { NATURE_DEFAULTS } from "../mind/nature.js";
8
8
  import { prepareDatabaseMigration } from "./archive.js";
9
- export function createStore(path = runtimePaths().database) {
10
- prepareDatabaseMigration(path);
9
+ export function createStore(
10
+ path = runtimePaths().database,
11
+ { quietMigration = false } = {},
12
+ ) {
13
+ prepareDatabaseMigration(path, { quiet: quietMigration });
11
14
  if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
12
15
  const db = new DatabaseSync(path);
13
16
  const legacyMessages =
@@ -0,0 +1,133 @@
1
+ import { SOURCE_CHECKOUT } from "../paths.js";
2
+ import { USER_AGENT, VERSION } from "../version.js";
3
+
4
+ const REGISTRY = "https://registry.npmjs.org/luckytri/latest";
5
+ const SEMVER =
6
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
7
+ function parts(value) {
8
+ const m =
9
+ typeof value === "string" && value.length <= 100 && value.match(SEMVER);
10
+ if (!m || m.slice(1, 4).some((n) => !Number.isSafeInteger(Number(n))))
11
+ return null;
12
+ if (m[4]?.split(".").some((part) => /^0\d+$/.test(part))) return null;
13
+ return { numbers: m.slice(1, 4).map(Number), pre: m[4]?.split(".") || [] };
14
+ }
15
+ export function compareVersions(a, b) {
16
+ const left = parts(a),
17
+ right = parts(b);
18
+ if (!left || !right) throw Error("版本信息无效");
19
+ for (let i = 0; i < 3; i++)
20
+ if (left.numbers[i] !== right.numbers[i])
21
+ return Math.sign(left.numbers[i] - right.numbers[i]);
22
+ if (!left.pre.length || !right.pre.length)
23
+ return Math.sign(Number(!left.pre.length) - Number(!right.pre.length));
24
+ for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i++) {
25
+ const x = left.pre[i],
26
+ y = right.pre[i];
27
+ if (x === y) continue;
28
+ if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
29
+ const xn = /^\d+$/.test(x),
30
+ yn = /^\d+$/.test(y);
31
+ if (xn && yn) return BigInt(x) < BigInt(y) ? -1 : 1;
32
+ if (xn !== yn) return xn ? -1 : 1;
33
+ return x < y ? -1 : 1;
34
+ }
35
+ return 0;
36
+ }
37
+
38
+ // A manual, bounded metadata read. It never installs code, runs commands or
39
+ // sends instance data, model keys or npm login credentials to the registry.
40
+ export class UpdateChecker {
41
+ constructor({
42
+ fetch: fetcher = globalThis.fetch,
43
+ now = Date.now,
44
+ current = VERSION,
45
+ source = SOURCE_CHECKOUT,
46
+ timeout = 10000,
47
+ } = {}) {
48
+ this.fetch = fetcher;
49
+ this.now = now;
50
+ this.current = current;
51
+ this.source = source;
52
+ this.timeout = timeout;
53
+ this.latest = null;
54
+ this.checkedAt = null;
55
+ this.lastAttempt = null;
56
+ this.error = "";
57
+ this.pending = null;
58
+ }
59
+ status() {
60
+ return {
61
+ current: this.current,
62
+ latest: this.latest,
63
+ checkedAt: this.checkedAt,
64
+ error: this.error,
65
+ status: this.error
66
+ ? "unavailable"
67
+ : !this.latest
68
+ ? "unchecked"
69
+ : compareVersions(this.latest, this.current) > 0
70
+ ? "available"
71
+ : compareVersions(this.latest, this.current) === 0
72
+ ? "current"
73
+ : "ahead",
74
+ installation: this.source ? "source" : "npm",
75
+ npmUrl: "https://www.npmjs.com/package/luckytri",
76
+ releaseUrl: "https://github.com/TodayYueC/LuckyTri/releases",
77
+ };
78
+ }
79
+ check() {
80
+ if (this.pending) return this.pending;
81
+ const now = this.now();
82
+ const elapsed =
83
+ this.lastAttempt == null ? Infinity : now - this.lastAttempt;
84
+ if (elapsed >= 0 && elapsed < (this.error ? 15000 : 300000))
85
+ return Promise.resolve({ ...this.status(), cached: true });
86
+ this.lastAttempt = now;
87
+ this.pending = this.read().finally(() => {
88
+ this.pending = null;
89
+ });
90
+ return this.pending;
91
+ }
92
+ async read() {
93
+ let response;
94
+ try {
95
+ response = await this.fetch(REGISTRY, {
96
+ headers: { Accept: "application/json", "User-Agent": USER_AGENT },
97
+ redirect: "error",
98
+ signal: AbortSignal.timeout(this.timeout),
99
+ });
100
+ if (!response.ok) throw Error(`HTTP ${response.status}`);
101
+ if (Number(response.headers.get("content-length")) > 65536)
102
+ throw Error("版本信息过大");
103
+ const chunks = [];
104
+ let bytes = 0;
105
+ for await (const chunk of response.body) {
106
+ bytes += chunk.length;
107
+ if (bytes > 65536) throw Error("版本信息过大");
108
+ chunks.push(Buffer.from(chunk));
109
+ }
110
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
111
+ if (data.name !== "luckytri" || !parts(data.version))
112
+ throw Error("版本信息无效");
113
+ this.latest = data.version;
114
+ this.checkedAt = this.now();
115
+ this.error = "";
116
+ } catch {
117
+ try {
118
+ await response?.body?.cancel();
119
+ } catch {
120
+ /* Already consumed or cancelled. */
121
+ }
122
+ this.error = "暂时无法连接 npm 或读取版本信息,请稍后重试。";
123
+ }
124
+ return { ...this.status(), cached: false };
125
+ }
126
+ }
127
+
128
+ export function mountUpdates(app, checker) {
129
+ app.get("/api/system/update", (_req, res) => res.json(checker.status()));
130
+ app.post("/api/system/update/check", async (_req, res) =>
131
+ res.json(await checker.check()),
132
+ );
133
+ }
@@ -1,3 +0,0 @@
1
- import{$ as e,Ct as t,E as n,Et as r,H as i,I as a,J as o,M as s,P as c,Tt as l,U as u,V as d,W as f,X as p,Y as m,Z as h,a as g,ct as _,dt as v,et as y,f as b,gt as x,ht as S,it as C,j as w,lt as T,m as E,n as D,nt as O,o as k,q as A,rt as j,s as M,t as N,ut as P,v as F,vt as I,wt as L,xt as R,yt as z,z as B}from"./Empty-SkA8PyMo.js";import{t as V}from"./formatters-ZmW_xFHw.js";import{F as ee,c as H,f as te,h as U,j as W,m as G,n as K,o as ne,p as q,u as J}from"./index-BIAdfObg.js";import{t as re}from"./media-CKVAvML2.js";import{t as Y}from"./Field-BjLhi8pL.js";async function ie(e,t){let n=new URLSearchParams({session:e});return t!==void 0&&n.set(`after`,String(t)),E(`/core/events?`+n.toString())}async function ae(e,t={}){let n=new URLSearchParams({session:e});return t.limit&&n.set(`limit`,String(t.limit)),t.compact&&n.set(`compact`,`1`),E(`/core/traces?`+n.toString())}async function X(e){return E(`/core/traces/`+e)}async function oe(e){return E(`/simulate`,`POST`,e)}async function se(e,t){return E(`/decisions/`+e+`/feedback`,`POST`,{tag:t})}async function Z(e){return E(`/core/replay`,`POST`,e)}async function ce(e){return E(`/core/sessions`,`POST`,e)}async function le(e,t){return E(`/core/sessions/`+encodeURIComponent(e),`PATCH`,{enabled:t})}async function ue(e,t){return E(`/core/sessions/`+encodeURIComponent(e)+`/archive`,`PATCH`,{archived:t})}async function de(e){return E(`/core/sessions/`+encodeURIComponent(e),`DELETE`,{})}async function fe(e,t){return E(`/core/sessions/`+encodeURIComponent(e),`PUT`,t)}async function pe(e){return E(`/core/sessions/`+encodeURIComponent(e)+`/summaries`)}async function me(e){return E(`/core/sessions/`+encodeURIComponent(e)+`/context`,`DELETE`,{})}var he={class:`session-list`},ge={class:`list-head`},Q=[`placeholder`,`aria-label`],_e={class:`rows scroll-pane`},ve=[`data-pick`,`aria-current`,`onClick`],ye={class:`who`},be=[`aria-label`],xe=[`title`],Se=[`checked`,`aria-label`,`onChange`],Ce={key:0,class:`muted empty-line`},we={key:1,class:`archive-list`},Te={class:`row`},Ee=[`data-restore-session`,`onClick`],De=[`data-delete-session`,`onClick`],Oe=D(O({__name:`SessionList`,props:{sessions:{},selected:{},unread:{}},emits:[`select`,`add`,`toggle`,`restore`,`remove`],setup(n,{emit:i}){let s=n,c=i,u=R(``),m=A(()=>s.sessions.filter(e=>!e.archived&&`${e.name} ${e.id}`.toLowerCase().includes(u.value.toLowerCase()))),g=A(()=>s.sessions.filter(e=>e.archived));return(i,s)=>(P(),h(`div`,he,[o(`div`,ge,[o(`h2`,null,[e(r(t(a)(`会话`))+` `,1),o(`small`,null,r(m.value.length),1)]),o(`button`,{class:`small primary`,onClick:s[0]||=e=>c(`add`)},r(t(a)(`+ 添加会话`)),1)]),z(o(`input`,{"onUpdate:modelValue":s[1]||=e=>u.value=e,type:`search`,placeholder:t(a)(`搜索名称或号码`),"aria-label":t(a)(`搜索会话`)},null,8,Q),[[d,u.value]]),o(`div`,_e,[(P(!0),h(f,null,v(m.value,e=>(P(),h(`div`,{key:e.id,class:L([`session-row`,{selected:e.id===n.selected,paused:!e.enabled}])},[o(`button`,{class:`row-main`,"data-pick":e.id,"aria-current":e.id===n.selected?`true`:void 0,onClick:t=>c(`select`,e.id)},[o(`span`,{class:`badge`,style:l({"--hue":t(te)(e.id)})},r(e.kind===`private`?t(a)(`私`):t(a)(`群`)),5),o(`span`,ye,[o(`b`,null,r(t(U)(e)),1),o(`small`,null,r(e.enabled?t(a)(`参与中`):t(a)(`已暂停`)),1)]),n.unread[e.id]?(P(),h(`span`,{key:0,class:`unread`,"aria-label":t(a)(`{v} 条没细看`,{v:n.unread[e.id]})},r(n.unread[e.id]),9,be)):p(``,!0)],8,ve),o(`label`,{class:`mini-switch`,title:e.enabled?t(a)(`暂停参与`):t(a)(`开启参与`)},[o(`input`,{type:`checkbox`,checked:e.enabled,"aria-label":t(a)(`参与:{v}`,{v:t(U)(e)}),onChange:t=>c(`toggle`,e)},null,40,Se)],8,xe)],2))),128)),m.value.length?p(``,!0):(P(),h(`p`,Ce,r(t(a)(`暂无匹配的会话。`)),1)),g.value.length?(P(),h(`details`,we,[o(`summary`,null,r(t(a)(`已归档 · {length}`,{length:g.value.length})),1),(P(!0),h(f,null,v(g.value,e=>(P(),h(`article`,{key:e.id},[o(`b`,null,r(t(U)(e)),1),o(`div`,Te,[o(`button`,{class:`small`,"data-restore-session":e.id,onClick:t=>c(`restore`,e.id)},r(t(a)(`恢复`)),9,Ee),o(`button`,{class:`small danger`,"data-delete-session":e.id,onClick:t=>c(`remove`,e.id)},r(t(a)(`永久删除`)),9,De)])]))),128))])):p(``,!0)])]))}}),[[`__scopeId`,`data-v-9b8dcbac`]]),ke={class:`muted`},Ae={key:0,class:`notice`,role:`status`},je=[`pattern`,`inputmode`],Me=[`disabled`],Ne=O({__name:`AddSession`,props:{open:{type:Boolean},channel:{},ready:{type:Boolean}},emits:[`close`,`add`],setup(e,{emit:n}){let i=e,s=R(`group`),c=n,l=A(()=>i.channel===`qqbot`),d=A(()=>l.value?`[0-9A-Za-z_\\-]{8,64}`:`\\d{4,20}`);function f(e){let t=e.target;c(`add`,{...Object.fromEntries(new FormData(t)),channel:i.channel})}return(n,i)=>(P(),m(ne,{open:e.open,title:t(a)(`添加群聊 / 私聊`),eyebrow:t(a)(`NEW PLACE`),width:`440px`,onClose:i[1]||=e=>c(`close`)},{default:I(()=>[o(`form`,{id:`addSession`,class:`stack`,onSubmit:u(f,[`prevent`])},[o(`p`,ke,r(t(a)(`添加之后再决定要不要让 TA 参与;开不开口仍由 TA 自己决定。`)),1),l.value&&!e.ready?(P(),h(`p`,Ae,r(t(a)(`请先在「连接 QQ」里填写机器人的 AppID`)),1)):p(``,!0),y(Y,{label:t(a)(`类型`)},{default:I(()=>[y(H,{modelValue:s.value,"onUpdate:modelValue":i[0]||=e=>s.value=e,name:`kind`,"aria-label":t(a)(`类型`),options:[{value:`group`,label:t(a)(`群聊`)},{value:`private`,label:t(a)(`私聊`)}]},null,8,[`modelValue`,`aria-label`,`options`])]),_:1},8,[`label`]),y(Y,{label:l.value?t(a)(`群 openid / 用户 openid`):t(a)(`群号 / QQ 号`),hint:l.value?t(a)(`8–64 位字母、数字、下划线或短横线。官方平台的会话通常会在有人 @ 她或私聊她时自动出现,这里只用于提前登记。`):t(a)(`4–20 位数字`)},{default:I(()=>[o(`input`,{name:`id`,required:``,pattern:d.value,inputmode:l.value?`text`:`numeric`,autocomplete:`off`},null,8,je)]),_:1},8,[`label`,`hint`]),y(Y,{label:t(a)(`显示名称`)},{default:I(()=>[...i[2]||=[o(`input`,{name:`name`,required:``,maxlength:`100`,autocomplete:`off`},null,-1)]]),_:1},8,[`label`]),o(`button`,{class:`primary`,disabled:l.value&&!e.ready},r(t(a)(`添加会话`)),9,Me)],32)]),_:1},8,[`open`,`title`,`eyebrow`]))}}),Pe={class:`transcript`},Fe={class:`t-head`},Ie=[`aria-label`,`title`],Le={class:`t-title`},Re={id:`liveStatus`,class:`faint`},ze={class:`t-tools`},Be=[`disabled`],Ve={id:`liveMessages`,class:`chat-messages scroll-pane`},He={key:0,class:`day-label`},Ue=[`data-status`],We={key:0},Ge={class:`body`},Ke={class:`message-meta`},qe={key:0,class:`chip`,"data-tone":`warn`},Je={class:`text`},Ye=[`aria-expanded`,`onClick`],Xe={key:0,class:`why`},Ze={key:0,class:`muted`},Qe={key:0},$e={key:1},et={key:2,class:`fb`},tt={class:`composer-note`},nt={class:`chip`,"data-tone":`warn`},rt={class:`faint`},it={class:`composer-row`},at={class:`uid`},ot={class:`sr-only`},st=[`title`],ct=[`placeholder`,`onKeydown`],lt={class:`check mention`},ut=[`disabled`],dt={key:1,class:`composer off`},ft={class:`faint`},pt=D(O({__name:`Transcript`,props:{session:{},sessionId:{},events:{},traces:{},decisions:{},status:{},demo:{type:Boolean},compact:{type:Boolean},sending:{type:Boolean}},emits:[`simulate`,`feedback`,`openList`,`openReplay`],setup(n,{expose:g,emit:_}){let b=n,x=_,S=c({glanced:w(`TA 扫了一眼`),silent:w(`TA 看了,没出声`),deferred:w(`TA 睡着了,醒来再看`)}),T=R(`10001`),E=R(``),D=R(!0),O=R(),k=R({}),j=()=>V(s(),{month:`long`,day:`numeric`,weekday:`short`}),F=A(()=>{let e=b.events.map(e=>({type:`message`,key:`m`+e.seq,time:e.time,event:e})),t=b.events[0]?.time??2**53-1;for(let n of b.traces)S[n.status]&&n.time>=t&&e.push({type:`divider`,key:`t`+n.id,time:n.time,status:n.status,reasons:[n.reason].filter(Boolean),count:1});e.sort((e,t)=>e.time-t.time);let n=[],r=``;for(let t of e){let e=j().format(t.time);e!==r&&(r=e,n.push({type:`day`,key:`d`+t.time,time:t.time,label:e}));let i=n[n.length-1];if(t.type===`divider`&&i?.type===`divider`&&i.status===t.status){i.count+=1,t.reasons[0]&&!i.reasons.includes(t.reasons[0])&&i.reasons.push(t.reasons[0]);continue}n.push(t)}return n});function I(e){let t=String(e.payload.text||``);return b.decisions.filter(n=>n.session_id===e.session_id&&n.reply&&n.reply.includes(t)&&Math.abs(n.time-e.time)<6e5).sort((t,n)=>Math.abs(t.time-e.time)-Math.abs(n.time-e.time))[0]}function ee(e){return b.traces.filter(t=>t.status===`sent`&&t.time<=e.time+1e3).sort((e,t)=>t.time-e.time)[0]}async function U(e){if(k.value[e.seq]){let{[e.seq]:t,...n}=k.value;k.value=n;return}k.value={...k.value,[e.seq]:{loading:!0,detail:null}};let t=ee(e),n=null;try{n=t?await X(t.id):null}catch{n=null}k.value[e.seq]&&(k.value={...k.value,[e.seq]:{loading:!1,detail:n}})}async function W(){await C(),O.value?.focus()}function G(){E.value.trim()&&!b.sending&&(x(`simulate`,{userId:T.value,text:E.value,mentioned:D.value}),E.value=``)}return g({focusComposer:W}),(s,c)=>(P(),h(`section`,Pe,[o(`header`,Fe,[n.compact?(P(),h(`button`,{key:0,class:`icon-button`,"aria-label":t(a)(`全部会话`),title:t(a)(`全部会话`),onClick:c[0]||=e=>x(`openList`)},` ☰ `,8,Ie)):p(``,!0),n.session?(P(),h(`span`,{key:1,class:`badge`,style:l({"--hue":t(te)(n.session.id)})},r(n.session.kind===`private`?t(a)(`私`):t(a)(`群`)),5)):p(``,!0),o(`div`,Le,[o(`h2`,null,r(n.session?.name||t(a)(`选择一段对话`)),1),o(`span`,Re,r(n.status),1)]),o(`div`,ze,[o(`button`,{class:`small sim-button`,disabled:!n.sessionId,onClick:W},r(t(a)(`模拟消息`)),9,Be),o(`button`,{class:`small`,onClick:c[1]||=e=>x(`openReplay`)},r(t(a)(`回到那一刻`)),1)])]),o(`div`,Ve,[(P(!0),h(f,null,v(F.value,n=>(P(),h(f,{key:n.key},[n.type===`day`?(P(),h(`div`,He,[o(`span`,null,r(n.label),1)])):n.type===`divider`?(P(),h(`div`,{key:1,class:`divider`,"data-status":n.status},[o(`span`,null,r(t(S)[n.status])+r(n.count>1?` × ${n.count}`:``),1),n.reasons.length?(P(),h(`small`,We,r(n.reasons.slice(0,2).join(`;`)),1)):p(``,!0)],8,Ue)):(P(),h(`article`,{key:2,class:L([`message`,{bot:n.event.role===`assistant`,simulated:n.event.payload.simulated}])},[n.event.role===`assistant`?p(``,!0):(P(),h(`span`,{key:0,class:`avatar`,style:l({"--hue":t(te)(String(n.event.payload.userId||n.event.payload.name))}),"aria-hidden":`true`},r(t(q)(n.event.payload.name)),5)),o(`div`,Ge,[o(`div`,Ke,[o(`b`,null,r(n.event.payload.name),1),o(`time`,null,r(t(J)(n.event.time)),1),n.event.payload.simulated?(P(),h(`span`,qe,r(t(a)(`模拟`)),1)):p(``,!0)]),o(`p`,Je,r(n.event.payload.text),1),n.event.role===`assistant`?(P(),h(f,{key:0},[o(`button`,{class:`text-button why-toggle`,"aria-expanded":!!k.value[n.event.seq],onClick:e=>U(n.event)},r(k.value[n.event.seq]?t(a)(`收起`):t(a)(`为什么这么说`)),9,Ye),k.value[n.event.seq]?(P(),h(`div`,Xe,[k.value[n.event.seq].loading?(P(),h(`p`,Ze,r(t(a)(`正在翻当时的记录…`)),1)):(P(),h(f,{key:1},[k.value[n.event.seq].detail?.data?.decision?.appraisal?(P(),h(`p`,Qe,[o(`b`,null,r(t(a)(`TA 当时的理解:`)),1),e(r(k.value[n.event.seq].detail.data.decision.appraisal),1)])):p(``,!0),o(`p`,null,[o(`b`,null,r(t(a)(`理由:`)),1),e(r(k.value[n.event.seq].detail?.data?.reason||k.value[n.event.seq].detail?.data?.decision?.reason||I(n.event)?.reason||t(a)(`没有留下理由。`)),1)]),k.value[n.event.seq].detail?.data?.snapshot?.knowledge?.length?(P(),h(`p`,$e,[o(`b`,null,r(t(a)(`引用的资料:`)),1),e(r(k.value[n.event.seq].detail.data.snapshot.knowledge.map(e=>e.title).join(`、`)),1)])):p(``,!0),I(n.event)?(P(),h(`label`,et,[e(r(t(a)(`这句怎么样?`))+` `,1),y(H,{"model-value":I(n.event).feedback||``,"aria-label":t(a)(`这句怎么样?`),options:[{value:``,label:t(a)(`选择评价`)},...Object.entries(t(M).health.feedbackLabels||{}).map(([e,t])=>({value:e,label:String(t)}))],"onUpdate:modelValue":e=>x(`feedback`,I(n.event).id,e)},null,8,[`model-value`,`aria-label`,`options`,`onUpdate:modelValue`])])):p(``,!0)],64))])):p(``,!0)],64)):p(``,!0)])],2))],64))),128)),n.events.length?p(``,!0):(P(),m(N,{key:0,title:n.sessionId?t(a)(`等待新的消息`):t(a)(`选择一段对话`),text:t(a)(`群聊与私聊消息会在这里实时出现;TA 扫一眼、没出声也会留下一条分隔线。`)},null,8,[`title`,`text`]))]),n.demo?(P(),h(`form`,{key:0,id:`simulate`,class:`composer`,onSubmit:u(G,[`prevent`])},[o(`div`,tt,[o(`span`,nt,r(t(a)(`模拟消息`)),1),o(`span`,rt,r(t(a)(`作为一条模拟消息走完整流程,写进模拟会话;不会发到 QQ,也不进入真实记忆。`)),1)]),o(`div`,it,[o(`label`,at,[o(`span`,ot,r(t(a)(`体验用户 ID`)),1),z(o(`input`,{"onUpdate:modelValue":c[2]||=e=>T.value=e,name:`userId`,pattern:`\\d{4,20}`,required:``,title:t(a)(`体验用户 ID`)},null,8,st),[[d,T.value]])]),z(o(`textarea`,{ref_key:`composer`,ref:O,"onUpdate:modelValue":c[3]||=e=>E.value=e,name:`text`,rows:`1`,placeholder:t(a)(`以这位群友的身份说一句…`),required:``,onKeydown:i(u(G,[`exact`,`prevent`]),[`enter`])},null,40,ct),[[d,E.value]]),o(`label`,lt,[z(o(`input`,{"onUpdate:modelValue":c[4]||=e=>D.value=e,type:`checkbox`},null,512),[[B,D.value]]),e(r(t(a)(`视为 @`)),1)]),o(`button`,{class:`primary`,disabled:n.sending||!n.sessionId},r(n.sending?t(a)(`TA 在想…`):t(a)(`发送模拟消息`)),9,ut)])],32)):(P(),h(`div`,dt,[o(`span`,ft,r(t(a)(`真实模式下不能模拟消息。想看看 TA 会怎么回,可以「和 TA 聊聊」——那是试聊,什么都不写入。`)),1),o(`button`,{class:`small`,onClick:c[5]||=e=>t(M).chatOpen=!0},r(t(a)(`和 TA 聊聊`)),1)]))]))}}),[[`__scopeId`,`data-v-849aeb0f`]]),mt={class:`panel`},ht={key:0,class:`panel-body`},gt={key:1,class:`panel-body scroll-pane`},_t={class:`here`},vt={class:`facts`},yt={class:`eyebrow`},bt={key:1,class:`muted`},xt={key:2,class:`faint`},St={class:`eyebrow`},Ct={class:`faint`},wt={class:`row actions`},Tt=[`data-toggle`],Et=[`data-archive`],Dt=[`open`],Ot=[`data-session`],kt={class:`faint`},At=[`value`],jt={class:`faint`},Mt={class:`check`},Nt={class:`advanced-policy`},Pt={class:`stack tight`},Ft={class:`check`},It={class:`check`},Lt={class:`check`},Rt={class:`save-bar`},zt={class:`primary`,type:`submit`},Bt={class:`faint`},Vt={class:`fold summary-list`},Ht={key:0,class:`muted`},Ut={class:`faint`},Wt={key:0},Gt={key:2,class:`panel-body feedback-pane`},Kt={class:`faint`},qt={id:`feedbackList`,class:`scroll-pane`},Jt={class:`faint`},Yt={class:`reply-excerpt`},Xt={key:0,class:`muted`},Zt={class:`pagination`},Qt=[`disabled`],$t=[`disabled`],$=6,en=D(O({__name:`SessionPanel`,props:j({session:{},group:{},summaries:{},decisions:{}},{settingsOpen:{type:Boolean,default:!1},settingsOpenModifiers:{},tab:{default:`here`},tabModifiers:{}}),emits:j([`toggle`,`archive`,`clear`,`save`,`feedback`],[`update:settingsOpen`,`update:tab`]),setup(n,{emit:i}){let s=n,l=S(n,`settingsOpen`),m=S(n,`tab`),g=i,_=c([w(`近期细摘要`),w(`中期摘要`),w(`较早摘要`),w(`远期摘要`)]),b=R(0),C=A(()=>s.decisions.filter(e=>e.session_id===s.session?.id&&e.reply)),T=A(()=>Math.max(1,Math.ceil(C.value.length/$))),E=R(!1),D=R({});x(()=>s.session?.policy,e=>{D.value={...e||{}}},{immediate:!0,deep:!0}),x(()=>s.session?.id,()=>{b.value=0,E.value=!1});function O(e){let t=e?.face;return t?[t.role,t.tone,t.content].filter(Boolean).join(`
2
-
3
- `):``}function k(e){let t=e.target,n=Object.fromEntries(new FormData(t));for(let e of[`aggregateMs`,`maxWaitMs`,`contextMessages`,`maxReply`])n[e]=Number(n[e]);for(let e of[`memory`,`selectiveVision`,`deepCheck`,`compaction`])n[e]=t.elements.namedItem(e).checked;g(`save`,n)}return(i,s)=>(P(),h(`section`,mt,[y(K,{modelValue:m.value,"onUpdate:modelValue":s[0]||=e=>m.value=e,label:t(a)(`这个会话`),items:[{key:`here`,label:t(a)(`这个会话`)},{key:`feedback`,label:t(a)(`反馈`)}]},null,8,[`modelValue`,`label`,`items`]),n.session?m.value===`here`?(P(),h(`div`,gt,[o(`div`,_t,[o(`div`,vt,[o(`div`,null,[o(`span`,yt,r(t(a)(`TA 在这里的样子`)),1),O(n.group)?(P(),h(f,{key:0},[o(`p`,{class:L([`face-body`,E.value?`open`:`clamp`])},r(O(n.group)),3),O(n.group).length>96?(P(),h(`button`,{key:0,type:`button`,class:`text-button`,onClick:s[1]||=e=>E.value=!E.value},r(E.value?t(a)(`收起`):t(a)(`展开完整内容`)),1)):p(``,!0)],64)):(P(),h(`p`,bt,r(t(a)(`还没有形成在这里的样子。`)),1)),n.group?.face?.aspiration?(P(),h(`small`,xt,r(t(a)(`想成为:{aspiration}`,{aspiration:n.group.face.aspiration})),1)):p(``,!0)]),o(`div`,null,[o(`span`,St,r(n.session.kind===`private`?t(a)(`这段私聊给 TA 的感觉`):t(a)(`这个群给 TA 的感觉`)),1),o(`p`,null,r(n.group?.bond?.feel||t(a)(`刚来这里不久`)),1)])]),o(`p`,Ct,r(t(a)(`在这里开不开口由 TA 自己决定:没有参与概率和冷却。TA 对这里每个人的感觉在「人际」里看。`)),1),o(`div`,wt,[o(`button`,{id:`toggleSession`,"data-toggle":n.session.id,class:L({primary:!n.session.enabled}),onClick:s[2]||=e=>g(`toggle`,n.session)},r(n.session.enabled?t(a)(`暂停参与`):t(a)(`开启参与`)),11,Tt),o(`button`,{"data-archive":n.session.id,onClick:s[3]||=e=>g(`archive`,n.session.id)},r(t(a)(`归档`)),9,Et),o(`button`,{id:`clearLiveContext`,onClick:s[4]||=e=>g(`clear`)},r(t(a)(`清空上下文`)),1)]),o(`details`,{class:`fold session-settings`,open:l.value,onToggle:s[19]||=e=>l.value=e.target.open},[o(`summary`,null,r(t(a)(`会话设置`)),1),(P(),h(`form`,{key:n.session.id,"data-session":n.session.id,class:`stack tight`,onSubmit:u(k,[`prevent`]),onInput:s[17]||=e=>t(M).dirty=!0,onChange:s[18]||=e=>t(M).dirty=!0},[o(`p`,kt,r(t(a)(`所有会话和独处都用模型库里的默认模型;其余已启用的模型按列表顺序做备用。她在这个聊天窗里用什么样子,由她自己从经历里决定。`)),1),o(`label`,null,[e(r(t(a)(`会话名称`))+` `,1),o(`input`,{name:`name`,maxlength:`100`,autocomplete:`off`,value:n.session.name},null,8,At),o(`small`,jt,r(t(a)(`官方机器人平台不提供群名称,可以在这里自己起一个`)),1)]),o(`label`,Mt,[z(o(`input`,{name:`selectiveVision`,type:`checkbox`,"onUpdate:modelValue":s[5]||=e=>D.value.selectiveVision=e,onInput:s[6]||=u(()=>{},[`stop`])},null,544),[[B,D.value.selectiveVision]]),e(r(t(a)(`节能看图:只在被 @ 或明确要求时,看这一条和附近的图`)),1)]),o(`details`,Nt,[o(`summary`,null,r(t(a)(`高级策略`)),1),o(`div`,Pt,[o(`label`,null,[e(r(t(a)(`聚合窗口 ms`)),1),z(o(`input`,{name:`aggregateMs`,type:`number`,"onUpdate:modelValue":s[7]||=e=>D.value.aggregateMs=e},null,512),[[d,D.value.aggregateMs,void 0,{number:!0}]])]),o(`label`,null,[e(r(t(a)(`最长等待 ms`)),1),z(o(`input`,{name:`maxWaitMs`,type:`number`,"onUpdate:modelValue":s[8]||=e=>D.value.maxWaitMs=e},null,512),[[d,D.value.maxWaitMs,void 0,{number:!0}]])]),o(`label`,null,[e(r(t(a)(`近期原文条数(10–500)`)),1),z(o(`input`,{name:`contextMessages`,type:`number`,min:`10`,max:`500`,"onUpdate:modelValue":s[9]||=e=>D.value.contextMessages=e},null,512),[[d,D.value.contextMessages,void 0,{number:!0}]])]),o(`label`,null,[e(r(t(a)(`一轮总字数`)),1),z(o(`input`,{name:`maxReply`,type:`number`,"onUpdate:modelValue":s[10]||=e=>D.value.maxReply=e},null,512),[[d,D.value.maxReply,void 0,{number:!0}]])]),o(`label`,Ft,[z(o(`input`,{name:`compaction`,type:`checkbox`,"onUpdate:modelValue":s[11]||=e=>D.value.compaction=e,onInput:s[12]||=u(()=>{},[`stop`])},null,544),[[B,D.value.compaction]]),e(r(t(a)(`上下文压缩:更早的聊天定期整理成分层摘要,越近越详细`)),1)]),o(`label`,It,[z(o(`input`,{name:`memory`,type:`checkbox`,"onUpdate:modelValue":s[13]||=e=>D.value.memory=e,onInput:s[14]||=u(()=>{},[`stop`])},null,544),[[B,D.value.memory]]),e(r(t(a)(`长期记忆`)),1)]),o(`label`,Lt,[z(o(`input`,{name:`deepCheck`,type:`checkbox`,"onUpdate:modelValue":s[15]||=e=>D.value.deepCheck=e,onInput:s[16]||=u(()=>{},[`stop`])},null,544),[[B,D.value.deepCheck]]),e(r(t(a)(`倾诉、纠正和危机时额外复审一次回复`)),1)])])]),o(`div`,Rt,[o(`button`,zt,r(t(a)(`保存会话设置`)),1),o(`small`,Bt,r(t(M).dirty?t(a)(`有未保存的修改`):t(a)(`保存后下一轮生效`)),1)])],40,Ot))],40,Dt),o(`details`,Vt,[o(`summary`,null,r(t(a)(`语境摘要 · {length} 段`,{length:n.summaries.length})),1),n.summaries.length?p(``,!0):(P(),h(`p`,Ht,r(t(a)(`还没有摘要。聊天超过近期原文条数后,更早的内容会自动整理到这里。`)),1)),(P(!0),h(f,null,v(n.summaries,e=>(P(),h(`article`,{key:e.id,class:`summary`},[o(`header`,null,[o(`b`,null,r(t(_)[e.level]||t(a)(`摘要`)),1),o(`small`,Ut,r(t(a)(`{period} · {messages} 条消息`,{period:e.period,messages:e.messages})),1)]),o(`p`,null,r(e.summary),1),e.keyPoints?.length?(P(),h(`ul`,Wt,[(P(!0),h(f,null,v(e.keyPoints,(e,n)=>(P(),h(`li`,{key:n},r(e.open?t(a)(`未完:`):``)+r(e.text),1))),128))])):p(``,!0)]))),128))])])])):(P(),h(`div`,Gt,[o(`p`,Kt,r(t(a)(`针对具体回复评价口吻;这是 TA 在这个会话里听到的话,不会改写天性。`)),1),o(`div`,qt,[(P(!0),h(f,null,v(C.value.slice(b.value*$,b.value*$+$),n=>(P(),h(`article`,{key:n.id,class:`feedback-item`},[o(`time`,Jt,r(t(J)(n.time)),1),o(`p`,Yt,r(n.reply),1),o(`label`,null,[e(r(t(a)(`这句回复怎么样?`))+` `,1),y(H,{"data-feedback":n.id,"model-value":n.feedback||``,"aria-label":t(a)(`这句回复怎么样?`),options:[{value:``,label:t(a)(`选择评价`)},...Object.entries(t(M).health.feedbackLabels||{}).map(([e,t])=>({value:e,label:String(t)}))],"onUpdate:modelValue":e=>g(`feedback`,n.id,e)},null,8,[`data-feedback`,`model-value`,`aria-label`,`options`,`onUpdate:modelValue`])])]))),128)),C.value.length?p(``,!0):(P(),h(`p`,Xt,r(t(a)(`还没有可以评价的回复。`)),1))]),o(`div`,Zt,[o(`button`,{class:`small`,disabled:b.value===0,onClick:s[20]||=e=>b.value--},`←`,8,Qt),o(`span`,null,r(b.value+1)+` / `+r(T.value),1),o(`button`,{class:`small`,disabled:b.value+1>=T.value,onClick:s[21]||=e=>b.value++},` → `,8,$t)])])):(P(),h(`div`,ht,[y(N,{title:t(a)(`还没有选中会话`),text:t(a)(`从左边选一个群聊或私聊。`)},null,8,[`title`,`text`])]))]))}}),[[`__scopeId`,`data-v-96fbad3d`]]),tn={class:`replay`},nn={class:`col source`},rn={class:`col-head`},an={id:`events`,class:`scroll-pane`},on={key:0},sn={key:1,class:`muted`},cn=[`disabled`],ln={class:`faint`},un={class:`col`},dn={class:`col-head`},fn={id:`traces`,class:`scroll-pane`},pn=[`data-trace`,`onClick`],mn=[`data-tone`],hn={key:0,class:`muted`},gn={class:`col`},_n={class:`col-head`},vn={class:`scroll-pane inspect`},yn={key:0,class:`metrics`},bn={id:`traceTokens`},xn={key:1,class:`notice`},Sn={id:`traceDetail`},Cn=D(O({__name:`ReplaySheet`,props:{open:{type:Boolean},sessionId:{},events:{}},emits:[`close`,`load`],setup(n,{emit:i}){let s=n,l=i,g=c({sent:w(`开口了`),silent:w(`没出声`),glanced:w(`扫了一眼`),deferred:w(`睡着了`),running:w(`处理中`),error:w(`失败`),complete:w(`完成`),stale:w(`旧稿作废`),cancelled:w(`已取消`),interrupted:w(`已中断`)}),_=c({live:w(`真实聊天`),demo:w(`模拟预览`),replay:w(`测试回放`),memory:w(`记忆整理`),summary:w(`语境压缩`)}),y=R([]),b=R(null),S=R(``),C=R(``),T=R(!1),E=R(``);async function D(){s.sessionId&&(y.value=await ae(s.sessionId))}function O(){let e=s.events.map(e=>Number(e.seq));e.length&&(S.value||=String(Math.min(...e)),C.value||=String(Math.max(...e)))}async function k(){if(!T.value){T.value=!0;try{F(a(`回放正在运行`));let e=await Z({session:s.sessionId,from:Number(S.value),to:Number(C.value)});E.value=JSON.stringify(e,null,2),F(a(`回放结束`)),await D()}catch(e){F(e.message,!0)}finally{T.value=!1}}}async function A(e){b.value=await X(e),E.value=JSON.stringify(b.value,null,2)}function j(e){return e?a(`输入 {v}(缓存读 {v2} / 写 {v3})· 输出 {v4}`,{v:G(e.input),v2:G(e.cachedRead),v3:G(e.cacheWrite),v4:G(e.output)}):`—`}return x(()=>[s.open,s.sessionId],()=>{s.open&&(S.value=``,C.value=``,b.value=null,O(),D())},{immediate:!0}),x(()=>s.events.length,O),(i,s)=>(P(),m(ne,{open:n.open,title:t(a)(`回到那一刻`),eyebrow:`REPLAY`,width:`1180px`,onClose:s[3]||=e=>l(`close`)},{default:I(()=>[o(`div`,tn,[o(`section`,nn,[o(`div`,rn,[o(`h3`,null,r(t(a)(`历史消息`)),1),o(`button`,{id:`loadMessages`,class:`small`,onClick:s[0]||=e=>{l(`load`),D()}},r(t(a)(`↻ 加载`)),1)]),o(`div`,an,[n.events.length?(P(),h(`table`,on,[o(`thead`,null,[o(`tr`,null,[o(`th`,null,r(t(a)(`序号`)),1),o(`th`,null,r(t(a)(`发送者`)),1),o(`th`,null,r(t(a)(`消息`)),1)])]),o(`tbody`,null,[(P(!0),h(f,null,v([...n.events].reverse(),e=>(P(),h(`tr`,{key:e.seq},[o(`td`,null,r(e.seq),1),o(`td`,null,r(e.payload.name),1),o(`td`,null,r(e.payload.text),1)]))),128))])])):(P(),h(`p`,sn,r(t(a)(`当前会话暂无历史消息。`)),1))]),o(`form`,{class:`range`,onSubmit:u(k,[`prevent`])},[o(`label`,null,[e(r(t(a)(`起始序号`)),1),z(o(`input`,{"onUpdate:modelValue":s[1]||=e=>S.value=e,name:`from`,type:`number`,required:``},null,512),[[d,S.value]])]),o(`label`,null,[e(r(t(a)(`截止序号`)),1),z(o(`input`,{"onUpdate:modelValue":s[2]||=e=>C.value=e,name:`to`,type:`number`,required:``},null,512),[[d,C.value]])]),o(`button`,{id:`replay`,class:`primary`,disabled:T.value||!n.events.length},r(T.value?t(a)(`正在回放…`):t(a)(`回放这段对话`)),9,cn),o(`p`,ln,r(t(a)(`隔离回放:只测试回复,不发送 QQ,不修改真实记忆和 TA 的心智。`)),1)],32)]),o(`section`,un,[o(`div`,dn,[o(`h3`,null,r(t(a)(`处理记录`)),1)]),o(`div`,fn,[(P(!0),h(f,null,v(y.value,e=>(P(),h(`button`,{key:e.id,"data-trace":e.id,class:L([`trace-row`,{selected:b.value?.id===e.id}]),onClick:t=>A(e.id)},[o(`span`,null,[o(`time`,null,r(t(J)(e.time)),1),o(`small`,{class:`chip`,"data-tone":e.status===`error`?`danger`:`quiet`},r(t(g)[e.status]||e.status),9,mn)]),o(`p`,null,r(e.reason||e.error||t(a)(`查看处理详情`)),1)],10,pn))),128)),y.value.length?p(``,!0):(P(),h(`p`,hn,r(t(a)(`有新的消息处理记录后会显示在这里。`)),1))])]),o(`section`,gn,[o(`div`,_n,[o(`h3`,null,r(t(a)(`运行详情`)),1)]),o(`div`,vn,[b.value?(P(),h(`div`,yn,[o(`span`,null,[e(r(t(a)(`模式`)),1),o(`b`,null,r(t(_)[b.value.mode]||b.value.mode),1)]),o(`span`,null,[e(r(t(a)(`耗时`)),1),o(`b`,null,r(b.value.data?.elapsed??`—`)+` ms`,1)]),o(`span`,null,[e(r(t(a)(`模型调用`)),1),o(`b`,null,r(t(a)(`{v} 次`,{v:b.value.data?.calls?.length??0})),1)]),o(`span`,bn,[s[4]||=e(`Token`,-1),o(`b`,null,r(j(b.value.data?.tokens)),1)])])):p(``,!0),b.value?(P(),h(`p`,xn,r(b.value.reason||b.value.data?.decision?.reason||t(a)(`展开下方查看上下文、模型输入与原始输出。`)),1)):p(``,!0),o(`pre`,Sn,r(E.value||t(a)(`选择一条处理记录,查看最终上下文、Prompt、原始输出、Token 与耗时。`)),1)])])])]),_:1},8,[`open`,`title`]))}}),[[`__scopeId`,`data-v-839b3181`]]),wn={key:0,class:`card col list-col`},Tn={class:`card col talk-col`},En={class:`card col panel-col`},Dn={class:`sheet-list`},On=D(O({__name:`ChatsPage`,setup(e){let r=re(`(max-width: 1100px)`),i=A(()=>M.core?.sessions||[]),c=A(()=>i.value.filter(e=>!e.archived)),l=sessionStorage.activeSession,u=R(c.value.some(e=>e.id===l)?l:c.value[0]?.id||``),d=A(()=>c.value.find(e=>e.id===u.value)||null),f=R([]),v=R([]),S=R([]),w=R([]),E=R({}),D=R(``),O=R(!1),j=R(!1),N=R(!1),z=R(M.sub===`settings`),B=R(M.sub===`replay`),V=R(`here`),H=A(()=>M.health?.decisions||[]),te=A(()=>w.value.find(e=>e.session===u.value)||null),U=!1,G=!1,K=!1,q=``,J=0,Y=null,X=0;async function Z(e=!1){if(!u.value)return;if(U){G=!0,K||=e;return}let t=u.value,n=e||q!==t;U=!0;try{let[e,r]=await Promise.all([ie(t,n?void 0:J),ae(t,{limit:30,compact:!0})]);if(u.value!==t)return;let i=document.getElementById(`liveMessages`),o=q!==t||!i||i.scrollHeight-i.scrollTop-i.clientHeight<80;n?(f.value=e.reverse(),J=0):e.length&&(f.value=[...f.value,...e]);for(let t of e)J=Math.max(J,Number(t.seq)||0);!n&&e.length===100&&(G=!0),v.value=r,q=t,await C();let c=document.getElementById(`liveMessages`);c&&o&&(c.scrollTop=c.scrollHeight),D.value=a(`实时同步 · `)+new Date().toLocaleTimeString(s())}catch(e){D.value=a(`同步失败:`)+e.message}finally{if(U=!1,u.value!==t)G=!1,Z();else if(G){let e=K;G=!1,K=!1,Z(e)}}}async function he(){try{let[e,t]=await Promise.all([W.bonds(),W.overview()]);w.value=e.groups,E.value=Object.fromEntries(t.attention.map(e=>[e.session,e.unread]))}catch{}}x(u,e=>{if(Y?.abort(),e&&(sessionStorage.activeSession=e),f.value=[],v.value=[],S.value=[],q=``,J=0,G=!1,K=!1,N.value=!1,Z(),!e)return;pe(e).then(t=>{u.value===e&&(S.value=[...t].reverse())}).catch(()=>{});let t=new AbortController;Y=t;let n=``;ee(e=>{let t=Number(e?.messages);Number.isSafeInteger(t)&&t<J&&(q=``,J=0,f.value=[]);let r=JSON.stringify(e),i=n!==``&&r!==n;n=r,i&&Z()},{session:e,signal:t.signal,reconnectMs:1e3})},{immediate:!0}),x(c,e=>{e.some(e=>e.id===u.value)||(u.value=e[0]?.id||``)}),x(V,async e=>{if(e===`feedback`)try{M.health=await b()}catch{}}),x(B,e=>k(e?`replay`:z.value?`settings`:``)),x(()=>M.sub,e=>{e===`replay`&&(B.value=!0),e===`settings`&&(z.value=!0)}),x(()=>M.pulse,he),_(()=>{he(),X=window.setInterval(()=>Z(!0),15e3)}),T(()=>{clearInterval(X),Y?.abort()});async function ge(e){try{let t=await ce(e);await g(),u.value=t?.sessionId||`${e.kind}:${e.id}`,z.value=!0,V.value=`here`,j.value=!1,F(a(`会话已添加`))}catch(e){F(e.message,!0)}}async function Q(e){await le(e.id,!e.enabled),await g()}async function _e(e){await ue(e,!0),await g()}async function ve(e){await ue(e,!1),await g()}async function ye(e){await n(a(`永久删除这个会话?它的消息和设置都会消失。`),{title:a(`永久删除`),confirmText:a(`删除`),danger:!0})&&(await de(e),await g())}async function be(e){if(d.value)try{await fe(d.value.id,{...e,name:String(e.name||``).trim()||d.value.name}),M.dirty=!1,F(a(`会话配置已保存`)),await g()}catch(e){F(e.message,!0)}}async function xe(){u.value&&await n(a(`确定清空这个会话的消息上下文吗?长期记忆不会删除。`),{title:a(`清空上下文`),confirmText:a(`清空`),danger:!0})&&(await me(u.value),f.value=[],v.value=[],q=``,J=0,await Z(!0))}async function Se(e){if(!O.value&&u.value){O.value=!0;try{let t=await oe({sessionId:u.value,...e});F(t.reason||a(`已发送`)),M.health=await b(),await Z()}catch(e){F(e.message,!0)}finally{O.value=!1}}}async function Ce(e,t){try{await se(e,t),F(a(`反馈已保存`)),M.health=await b()}catch(e){F(e.message,!0)}}return(e,n)=>(P(),h(`div`,{class:L([`page chats`,{compact:t(r)}])},[t(r)?p(``,!0):(P(),h(`aside`,wn,[y(Oe,{sessions:i.value,selected:u.value,unread:E.value,onSelect:n[0]||=e=>u.value=e,onAdd:n[1]||=e=>j.value=!0,onToggle:Q,onRestore:ve,onRemove:ye},null,8,[`sessions`,`selected`,`unread`])])),o(`div`,Tn,[y(pt,{"session-id":u.value,session:d.value,events:f.value,traces:v.value,decisions:H.value,status:D.value||t(a)(`请选择会话`),demo:!!t(M).health.settings.demo,compact:t(r),sending:O.value,onSimulate:Se,onFeedback:Ce,onOpenList:n[2]||=e=>N.value=!0,onOpenReplay:n[3]||=e=>B.value=!0},null,8,[`session-id`,`session`,`events`,`traces`,`decisions`,`status`,`demo`,`compact`,`sending`])]),o(`aside`,En,[y(en,{"settings-open":z.value,"onUpdate:settingsOpen":n[4]||=e=>z.value=e,tab:V.value,"onUpdate:tab":n[5]||=e=>V.value=e,session:d.value,group:te.value,summaries:S.value,decisions:H.value,onToggle:Q,onArchive:_e,onClear:xe,onSave:be,onFeedback:Ce},null,8,[`settings-open`,`tab`,`session`,`group`,`summaries`,`decisions`])]),t(r)?(P(),m(ne,{key:1,open:N.value,title:t(a)(`全部会话`),eyebrow:`CHATS`,width:`400px`,onClose:n[8]||=e=>N.value=!1},{default:I(()=>[o(`div`,Dn,[y(Oe,{sessions:i.value,selected:u.value,unread:E.value,onSelect:n[6]||=e=>u.value=e,onAdd:n[7]||=e=>j.value=!0,onToggle:Q,onRestore:ve,onRemove:ye},null,8,[`sessions`,`selected`,`unread`])])]),_:1},8,[`open`,`title`])):p(``,!0),y(Ne,{open:j.value,channel:t(M).health?.connection?.channel===`qqbot`?`qqbot`:`onebot`,ready:!!t(M).health?.connection?.qqbot?.appId,onClose:n[9]||=e=>j.value=!1,onAdd:ge},null,8,[`open`,`channel`,`ready`]),y(Cn,{open:B.value,"session-id":u.value,events:f.value,onClose:n[10]||=e=>B.value=!1,onLoad:n[11]||=e=>Z(!0)},null,8,[`open`,`session-id`,`events`])],2))}}),[[`__scopeId`,`data-v-c328f9fe`]]);export{On as default};