@aalis/plugin-user-profile 0.13.2 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +212 -886
- package/dist/index.js.map +1 -1
- package/package.json +15 -17
package/dist/index.js
CHANGED
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
import { authority, DEFAULT_AUTHORITY } from '@aalis/api-authority';
|
|
2
1
|
import { commands } from '@aalis/api-commands';
|
|
3
2
|
import { contributions } from '@aalis/api-contributions';
|
|
4
3
|
import { hooks } from '@aalis/api-hooks';
|
|
5
|
-
import { llm, resolveLLMModel } from '@aalis/api-llm';
|
|
4
|
+
import { lightestThinking, llm, resolveLLMModel } from '@aalis/api-llm';
|
|
6
5
|
import { clearMetadataNamespaces, memory } from '@aalis/api-memory';
|
|
7
|
-
import { persona } from '@aalis/api-persona';
|
|
8
6
|
import { tools } from '@aalis/api-tools';
|
|
9
7
|
import { userRelation } from '@aalis/api-user-relation';
|
|
8
|
+
import { webuiServer } from '@aalis/api-webui';
|
|
10
9
|
import { config, definePlugin, events, logger, optional } from '@aalis/core';
|
|
11
10
|
import { defineConfig, parseConfig } from '@aalis/schema-config';
|
|
12
|
-
import {
|
|
11
|
+
import { DIRECTIVE_KINDS, WellKnownMetadataKeys } from '@aalis/schema-message';
|
|
13
12
|
import { parseLLMJsonObject } from '@aalis/util-json-repair';
|
|
14
13
|
// ════════════════════════════════════════════════════════════
|
|
15
14
|
// plugin-user-profile — 用户事实档案
|
|
@@ -35,17 +34,6 @@ import { parseLLMJsonObject } from '@aalis/util-json-repair';
|
|
|
35
34
|
// 例:群聊纯旁观一条 = +0.1;群聊被 @ 并回复 = +0.1 + 1.5 = +1.6;私聊一条 = +0.1 + 1.0 = +1.1
|
|
36
35
|
// ════════════════════════════════════════════════════════════
|
|
37
36
|
const PROFILE_NS = 'user:profile';
|
|
38
|
-
/** Aalis 自档案的 userKey 前缀。userKeyOf 形如 `platform:userId`,
|
|
39
|
-
* 这里用 `__self__:<personaName>` 这种不可能在真实平台出现的形式做隔离。
|
|
40
|
-
* 按 persona name 分堆:同名 persona(如 onebot 上的 aalis 与 webui 上的 aalis-webui两张卡都叫 Aalis)共享内心;
|
|
41
|
-
* 不同 persona(如 Babel)各自独立。 */
|
|
42
|
-
const SELF_KEY_PREFIX = '__self__:';
|
|
43
|
-
const DEFAULT_PERSONA_NAME = 'Aalis';
|
|
44
|
-
/** 第三方行为指令的独立 namespace(与 user:profile 解耦,独立生命周期)。
|
|
45
|
-
* 指令是「第三方对 Aalis 的客观行为约束」(如:不要长时间封禁;按严重程度分层禁言),
|
|
46
|
-
* 按 persona 名分堆(key = persona 名),与 selfFacts 的归属方式保持一致:
|
|
47
|
-
* 同名 persona(如 onebot 与 webui 两张都叫 Aalis)共享准则;不同 persona(如 Babel)各自独立。 */
|
|
48
|
-
const INSTRUCTIONS_NS = 'aalis:instructions';
|
|
49
37
|
const configSchema = defineConfig({
|
|
50
38
|
extractEveryNMessages: {
|
|
51
39
|
type: 'number',
|
|
@@ -131,71 +119,6 @@ const configSchema = defineConfig({
|
|
|
131
119
|
description: '当前群/会话中的候选不足时,是否允许从其他群、私聊等跨会话中选取最近互动过的用户来补全「其他参与者背景摘要」。关闭后仅限当前上下文内出现过的用户',
|
|
132
120
|
default: false,
|
|
133
121
|
},
|
|
134
|
-
enableSelfProfile: {
|
|
135
|
-
type: 'boolean',
|
|
136
|
-
onInvalid: 'error',
|
|
137
|
-
label: '启用 Aalis 自档案',
|
|
138
|
-
description: '让 Aalis 周期性地反思自身,提炼「关于自己的事实」(近期心情走向、在意的事、自我观察)。注入到所有 LLM 调用的 system prompt 早段,提供跨会话的人格延续性。' +
|
|
139
|
-
'⚠️ 默认关闭:自档案是模型对自身输出的二次提炼,再注入会自我强化先前的臆测、随时间漂移并放大幻觉,不建议开启',
|
|
140
|
-
default: false,
|
|
141
|
-
},
|
|
142
|
-
selfReflectEveryNMessages: {
|
|
143
|
-
type: 'number',
|
|
144
|
-
label: 'Aalis 自反思触发频次',
|
|
145
|
-
description: '全局累计入站消息每 N 条触发一次自反思。建议比单用户提取慢(默认 25),避免抖动',
|
|
146
|
-
default: 25,
|
|
147
|
-
},
|
|
148
|
-
selfReflectHistory: {
|
|
149
|
-
type: 'number',
|
|
150
|
-
label: '自反思参考历史条数',
|
|
151
|
-
description: '触发自反思时,从触发会话取最近多少条消息作为反思材料',
|
|
152
|
-
default: 16,
|
|
153
|
-
},
|
|
154
|
-
maxSelfFacts: {
|
|
155
|
-
type: 'number',
|
|
156
|
-
label: 'Aalis 自档案事实上限',
|
|
157
|
-
description: '超出后按 updatedAt 升序淘汰最久未更新的。最小有效值为 5(写入时自动下限),不支持设为 0 来禁用;若要禁用自反思请关闭 enableSelfProfile',
|
|
158
|
-
default: 20,
|
|
159
|
-
},
|
|
160
|
-
enableInstructions: {
|
|
161
|
-
type: 'boolean',
|
|
162
|
-
onInvalid: 'error',
|
|
163
|
-
label: '启用第三方行为指令',
|
|
164
|
-
description: '让 Aalis 记录第三方(管理员/操作者)对其行为的客观指令(如「不要长时间封禁」「按严重程度分层禁言」),作为跨会话的行为约束。' +
|
|
165
|
-
'注入到 system prompt 最前段,优先级高于自反思 selfFacts。按当前 persona 名分堆。',
|
|
166
|
-
default: true,
|
|
167
|
-
},
|
|
168
|
-
instructionMinAuthority: {
|
|
169
|
-
type: 'number',
|
|
170
|
-
label: '指令最小权限门槛',
|
|
171
|
-
description: '只有 authority ≥ 该值的用户的发言才会被采纳为指令来源(防陌生人塞规则)。默认 2(一般管理员),设为 5 表示仅 owner。' +
|
|
172
|
-
'通过 /instruct 命令手动添加的指令不走该门槛(命令本身已是 authority 2 守卫)',
|
|
173
|
-
default: 2,
|
|
174
|
-
},
|
|
175
|
-
instructionExtractEveryNMessages: {
|
|
176
|
-
type: 'number',
|
|
177
|
-
label: '指令自动提取触发频次',
|
|
178
|
-
description: '全局累计入站消息每 N 条触发一次指令提取。建议比自反思更慢(默认 40),降低成本;设为 0 禁用 LLM 自动提取,只保留 /instruct 命令通道',
|
|
179
|
-
default: 40,
|
|
180
|
-
},
|
|
181
|
-
instructionHistoryForExtraction: {
|
|
182
|
-
type: 'number',
|
|
183
|
-
label: '指令提取参考历史条数',
|
|
184
|
-
description: '触发指令提取时从触发会话取最近多少条消息作为提取材料',
|
|
185
|
-
default: 20,
|
|
186
|
-
},
|
|
187
|
-
maxInstructions: {
|
|
188
|
-
type: 'number',
|
|
189
|
-
label: '指令条数上限',
|
|
190
|
-
description: '超出后按 updatedAt 升序淘汰最久未更新的。最小有效值为 3。指令上限建议比 selfFacts 紧,准则少而准比多而散更好',
|
|
191
|
-
default: 12,
|
|
192
|
-
},
|
|
193
|
-
maxInstructionCharsPerItem: {
|
|
194
|
-
type: 'number',
|
|
195
|
-
label: '单条指令字数上限',
|
|
196
|
-
description: '超出会被裁断',
|
|
197
|
-
default: 120,
|
|
198
|
-
},
|
|
199
122
|
});
|
|
200
123
|
const KNOWN_CATEGORIES = [
|
|
201
124
|
'兴趣爱好',
|
|
@@ -208,23 +131,15 @@ const KNOWN_CATEGORIES = [
|
|
|
208
131
|
'忌讳',
|
|
209
132
|
'其他',
|
|
210
133
|
];
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
'隐私与边界',
|
|
214
|
-
'语气与表达',
|
|
215
|
-
'响应策略',
|
|
216
|
-
'安全',
|
|
217
|
-
'其他',
|
|
218
|
-
];
|
|
219
|
-
/** 生成稳定短 ID(6 字符 base36,对 30 条以内规模碰撞概率极低);前缀 'f' 为事实、'i' 为指令 */
|
|
220
|
-
function genShortId(prefix, existing) {
|
|
134
|
+
/** 生成事实的稳定短 ID(前缀 f 加 5 位 base36,对 30 条以内规模碰撞概率极低) */
|
|
135
|
+
function genShortId(existing) {
|
|
221
136
|
for (let i = 0; i < 8; i++) {
|
|
222
|
-
const id =
|
|
137
|
+
const id = `f${Math.random().toString(36).slice(2, 7)}`;
|
|
223
138
|
if (!existing.has(id))
|
|
224
139
|
return id;
|
|
225
140
|
}
|
|
226
141
|
// 极端兜底:加时间戳后缀
|
|
227
|
-
return
|
|
142
|
+
return `f${Date.now().toString(36).slice(-5)}`;
|
|
228
143
|
}
|
|
229
144
|
function decimalPlaces(value) {
|
|
230
145
|
if (!Number.isFinite(value))
|
|
@@ -244,7 +159,7 @@ function metadataString(message, key) {
|
|
|
244
159
|
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
|
245
160
|
}
|
|
246
161
|
function getMessageUserId(message) {
|
|
247
|
-
return metadataString(message,
|
|
162
|
+
return metadataString(message, WellKnownMetadataKeys.UserId) ?? message.name;
|
|
248
163
|
}
|
|
249
164
|
function isTargetUserMessage(message, userId, platform) {
|
|
250
165
|
if (message.role !== 'user' || !message.content)
|
|
@@ -252,7 +167,7 @@ function isTargetUserMessage(message, userId, platform) {
|
|
|
252
167
|
const msgUserId = getMessageUserId(message);
|
|
253
168
|
if (msgUserId !== userId)
|
|
254
169
|
return false;
|
|
255
|
-
const msgPlatform = metadataString(message,
|
|
170
|
+
const msgPlatform = metadataString(message, WellKnownMetadataKeys.Platform);
|
|
256
171
|
return !msgPlatform || !platform || msgPlatform === platform;
|
|
257
172
|
}
|
|
258
173
|
/**
|
|
@@ -296,9 +211,9 @@ function renderHistoryForExtract(history, userId, platform) {
|
|
|
296
211
|
// 平台事件(群禁言 / 撤回 / 成员进出 / poke 等),供提取判断「用户被谁怎么了」之类上下文
|
|
297
212
|
return `[${time}] [系统通知]: ${content}`;
|
|
298
213
|
}
|
|
299
|
-
const nickname = metadataString(m,
|
|
214
|
+
const nickname = metadataString(m, WellKnownMetadataKeys.Nickname);
|
|
300
215
|
const msgUserId = getMessageUserId(m) ?? '';
|
|
301
|
-
const msgPlatform = metadataString(m,
|
|
216
|
+
const msgPlatform = metadataString(m, WellKnownMetadataKeys.Platform);
|
|
302
217
|
const isTarget = msgUserId === userId && (!msgPlatform || !platform || msgPlatform === platform);
|
|
303
218
|
const label = nickname ? `${nickname}(${msgUserId || '?'})` : msgUserId || '?';
|
|
304
219
|
const tag = isTarget ? '目标用户' : '其他用户';
|
|
@@ -315,11 +230,11 @@ const uses = {
|
|
|
315
230
|
contributions,
|
|
316
231
|
config,
|
|
317
232
|
logger,
|
|
318
|
-
authority: optional(authority),
|
|
319
233
|
tools: optional(tools),
|
|
320
234
|
commands: optional(commands),
|
|
321
|
-
persona: optional(persona),
|
|
322
235
|
userRelation: optional(userRelation),
|
|
236
|
+
/** 档案页;不在时照常记档案 */
|
|
237
|
+
webui: optional(webuiServer),
|
|
323
238
|
};
|
|
324
239
|
export default definePlugin({
|
|
325
240
|
name: '@aalis/plugin-user-profile',
|
|
@@ -329,8 +244,8 @@ export default definePlugin({
|
|
|
329
244
|
uses,
|
|
330
245
|
apply: registerUserProfile,
|
|
331
246
|
});
|
|
332
|
-
function registerUserProfile({ memory, llm, events, hooks, contributions, config, logger,
|
|
333
|
-
const parsed = parseConfig(configSchema, config, logger);
|
|
247
|
+
function registerUserProfile({ memory, llm, events, hooks, contributions, config, logger, tools, commands, userRelation, webui, }) {
|
|
248
|
+
const parsed = parseConfig(configSchema, config.use, logger.use);
|
|
334
249
|
const cfg = {
|
|
335
250
|
...parsed,
|
|
336
251
|
historyForExtraction: Math.max(2, parsed.historyForExtraction),
|
|
@@ -350,14 +265,6 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
350
265
|
parsed.extractLLM.model
|
|
351
266
|
? parsed.extractLLM
|
|
352
267
|
: undefined,
|
|
353
|
-
selfReflectEveryNMessages: Math.max(0, parsed.selfReflectEveryNMessages),
|
|
354
|
-
selfReflectHistory: Math.max(4, parsed.selfReflectHistory),
|
|
355
|
-
maxSelfFacts: Math.max(5, parsed.maxSelfFacts),
|
|
356
|
-
instructionMinAuthority: Math.max(0, parsed.instructionMinAuthority),
|
|
357
|
-
instructionExtractEveryNMessages: Math.max(0, parsed.instructionExtractEveryNMessages),
|
|
358
|
-
instructionHistoryForExtraction: Math.max(4, parsed.instructionHistoryForExtraction),
|
|
359
|
-
maxInstructions: Math.max(3, parsed.maxInstructions),
|
|
360
|
-
maxInstructionCharsPerItem: Math.max(20, parsed.maxInstructionCharsPerItem),
|
|
361
268
|
};
|
|
362
269
|
/** 每会话每用户累计入站消息数(用于 extractEveryNMessages 计数),不随提取重置 */
|
|
363
270
|
const userMessageCount = new Map();
|
|
@@ -370,177 +277,6 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
370
277
|
function extractionCountKeyOf(sessionId, platform, userId) {
|
|
371
278
|
return `${sessionId}:${userKeyOf(platform, userId)}`;
|
|
372
279
|
}
|
|
373
|
-
/** 返回当前活跃 persona 的 self key(运行时解析,跟随 persona 切换)。
|
|
374
|
-
* 若 persona 服务不可用或未配 name,回退到默认 `aalis`。 */
|
|
375
|
-
function getCurrentPersonaName() {
|
|
376
|
-
try {
|
|
377
|
-
const name = persona.current?.getPersonaName().trim();
|
|
378
|
-
return name && name.length > 0 ? name : DEFAULT_PERSONA_NAME;
|
|
379
|
-
}
|
|
380
|
-
catch {
|
|
381
|
-
return DEFAULT_PERSONA_NAME;
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
function getSelfKey() {
|
|
385
|
-
return `${SELF_KEY_PREFIX}${getCurrentPersonaName()}`;
|
|
386
|
-
}
|
|
387
|
-
/** instructions 按 persona 名分堆:直接以 persona 名作为 metadata key */
|
|
388
|
-
function getInstructionsKey() {
|
|
389
|
-
return getCurrentPersonaName();
|
|
390
|
-
}
|
|
391
|
-
function normalizeInstructionCategory(v) {
|
|
392
|
-
if (typeof v !== 'string')
|
|
393
|
-
return undefined;
|
|
394
|
-
return KNOWN_INSTRUCTION_CATEGORIES.includes(v) ? v : undefined;
|
|
395
|
-
}
|
|
396
|
-
function normalizeInstructionSeverity(v) {
|
|
397
|
-
return v === 'must' || v === 'should' || v === 'avoid' ? v : undefined;
|
|
398
|
-
}
|
|
399
|
-
function clipInstructionText(s) {
|
|
400
|
-
return s.length > cfg.maxInstructionCharsPerItem ? `${s.slice(0, cfg.maxInstructionCharsPerItem)}…` : s;
|
|
401
|
-
}
|
|
402
|
-
function parseInstructionArray(raw) {
|
|
403
|
-
const usedIds = new Set();
|
|
404
|
-
const list = [];
|
|
405
|
-
for (const item of raw) {
|
|
406
|
-
if (!item || typeof item !== 'object')
|
|
407
|
-
continue;
|
|
408
|
-
const obj = item;
|
|
409
|
-
const text = typeof obj.text === 'string' ? obj.text.trim() : '';
|
|
410
|
-
if (!text)
|
|
411
|
-
continue;
|
|
412
|
-
let id = typeof obj.id === 'string' && obj.id.trim() ? obj.id.trim() : genShortId('i', usedIds);
|
|
413
|
-
while (usedIds.has(id))
|
|
414
|
-
id = genShortId('i', usedIds);
|
|
415
|
-
usedIds.add(id);
|
|
416
|
-
const updatedAt = typeof obj.updatedAt === 'number' ? obj.updatedAt : 0;
|
|
417
|
-
const observedAt = typeof obj.observedAt === 'number' ? obj.observedAt : updatedAt || undefined;
|
|
418
|
-
list.push({
|
|
419
|
-
id,
|
|
420
|
-
text,
|
|
421
|
-
category: normalizeInstructionCategory(obj.category),
|
|
422
|
-
severity: normalizeInstructionSeverity(obj.severity),
|
|
423
|
-
sourceUserKey: typeof obj.sourceUserKey === 'string' && obj.sourceUserKey.trim() ? obj.sourceUserKey : undefined,
|
|
424
|
-
sourceUserName: typeof obj.sourceUserName === 'string' && obj.sourceUserName.trim() ? obj.sourceUserName : undefined,
|
|
425
|
-
sourceChannel: obj.sourceChannel === 'llm' || obj.sourceChannel === 'command' ? obj.sourceChannel : undefined,
|
|
426
|
-
observedAt,
|
|
427
|
-
updatedAt,
|
|
428
|
-
});
|
|
429
|
-
}
|
|
430
|
-
return list;
|
|
431
|
-
}
|
|
432
|
-
/**
|
|
433
|
-
* 读取指令档案(不存在返回空档案)。读失败原样抛出,理由同 {@link loadProfile};
|
|
434
|
-
* 只读渲染走 {@link loadInstructionsLenient}。
|
|
435
|
-
* mem 由调用方传入:一次操作只认开头取到的实例,理由见 {@link loadProfile}
|
|
436
|
-
*/
|
|
437
|
-
async function loadInstructions(mem) {
|
|
438
|
-
const empty = { instructions: [], updatedAt: 0 };
|
|
439
|
-
if (!mem)
|
|
440
|
-
return empty;
|
|
441
|
-
const doc = await mem.getMetadata(INSTRUCTIONS_NS, getInstructionsKey());
|
|
442
|
-
if (!doc)
|
|
443
|
-
return empty;
|
|
444
|
-
const instructions = Array.isArray(doc.instructions) ? parseInstructionArray(doc.instructions) : [];
|
|
445
|
-
return { instructions, updatedAt: typeof doc.updatedAt === 'number' ? doc.updatedAt : 0 };
|
|
446
|
-
}
|
|
447
|
-
/** 只读渲染用:读失败按空档案处理,只记 debug(结果不会被写回) */
|
|
448
|
-
async function loadInstructionsLenient(mem) {
|
|
449
|
-
try {
|
|
450
|
-
return await loadInstructions(mem);
|
|
451
|
-
}
|
|
452
|
-
catch (err) {
|
|
453
|
-
logger.debug(`加载指令档案失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
454
|
-
return { instructions: [], updatedAt: 0 };
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
async function saveInstructions(mem, doc) {
|
|
458
|
-
if (!mem)
|
|
459
|
-
return;
|
|
460
|
-
await mem.saveMetadata(INSTRUCTIONS_NS, getInstructionsKey(), {
|
|
461
|
-
instructions: doc.instructions,
|
|
462
|
-
updatedAt: doc.updatedAt,
|
|
463
|
-
});
|
|
464
|
-
}
|
|
465
|
-
/** 把 add/update/remove 应用到现有 instructions,应用上限与单条裁剪 */
|
|
466
|
-
function mergeInstructions(existing, add, update, remove) {
|
|
467
|
-
const now = Date.now();
|
|
468
|
-
const byId = new Map();
|
|
469
|
-
for (const ins of existing)
|
|
470
|
-
byId.set(ins.id, ins);
|
|
471
|
-
for (const id of remove)
|
|
472
|
-
byId.delete(id);
|
|
473
|
-
const usedIds = new Set(byId.keys());
|
|
474
|
-
for (const { id, patch } of update) {
|
|
475
|
-
const old = byId.get(id);
|
|
476
|
-
if (!old)
|
|
477
|
-
continue;
|
|
478
|
-
byId.set(id, {
|
|
479
|
-
...old,
|
|
480
|
-
...patch,
|
|
481
|
-
id,
|
|
482
|
-
text: patch.text ? clipInstructionText(patch.text) : old.text,
|
|
483
|
-
observedAt: old.observedAt ?? now,
|
|
484
|
-
updatedAt: now,
|
|
485
|
-
});
|
|
486
|
-
}
|
|
487
|
-
const textSet = new Set(Array.from(byId.values()).map(f => f.text));
|
|
488
|
-
for (const a of add) {
|
|
489
|
-
const text = clipInstructionText(a.text);
|
|
490
|
-
if (textSet.has(text))
|
|
491
|
-
continue;
|
|
492
|
-
const id = genShortId('i', usedIds);
|
|
493
|
-
usedIds.add(id);
|
|
494
|
-
byId.set(id, {
|
|
495
|
-
id,
|
|
496
|
-
text,
|
|
497
|
-
category: a.category,
|
|
498
|
-
severity: a.severity,
|
|
499
|
-
sourceUserKey: a.sourceUserKey,
|
|
500
|
-
sourceUserName: a.sourceUserName,
|
|
501
|
-
sourceChannel: a.sourceChannel,
|
|
502
|
-
observedAt: now,
|
|
503
|
-
updatedAt: now,
|
|
504
|
-
});
|
|
505
|
-
textSet.add(text);
|
|
506
|
-
}
|
|
507
|
-
let merged = Array.from(byId.values());
|
|
508
|
-
if (cfg.maxInstructions > 0 && merged.length > cfg.maxInstructions) {
|
|
509
|
-
merged.sort((a, b) => a.updatedAt - b.updatedAt);
|
|
510
|
-
merged = merged.slice(merged.length - cfg.maxInstructions);
|
|
511
|
-
}
|
|
512
|
-
merged.sort((a, b) => a.updatedAt - b.updatedAt);
|
|
513
|
-
return merged;
|
|
514
|
-
}
|
|
515
|
-
function renderInstructionLine(ins) {
|
|
516
|
-
const tag = ins.severity === 'must' ? '【必须】' : ins.severity === 'avoid' ? '【避免】' : '【应当】';
|
|
517
|
-
const source = ins.sourceUserName ? `(来自 ${ins.sourceUserName})` : '';
|
|
518
|
-
return `- ${tag} ${ins.text}${source}`;
|
|
519
|
-
}
|
|
520
|
-
function renderInstructionsBlock(instructions) {
|
|
521
|
-
if (instructions.length === 0)
|
|
522
|
-
return '';
|
|
523
|
-
const groups = new Map();
|
|
524
|
-
for (const ins of instructions) {
|
|
525
|
-
const key = ins.category ?? '其他';
|
|
526
|
-
if (!groups.has(key))
|
|
527
|
-
groups.set(key, []);
|
|
528
|
-
groups.get(key).push(ins);
|
|
529
|
-
}
|
|
530
|
-
const sections = [];
|
|
531
|
-
for (const cat of KNOWN_INSTRUCTION_CATEGORIES) {
|
|
532
|
-
const items = groups.get(cat);
|
|
533
|
-
if (items && items.length > 0) {
|
|
534
|
-
sections.push(`## ${cat}\n${items.map(renderInstructionLine).join('\n')}`);
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
for (const [cat, items] of groups) {
|
|
538
|
-
if (!KNOWN_INSTRUCTION_CATEGORIES.includes(cat) && items.length > 0) {
|
|
539
|
-
sections.push(`## ${cat}\n${items.map(renderInstructionLine).join('\n')}`);
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
return sections.join('\n\n');
|
|
543
|
-
}
|
|
544
280
|
function normalizeTemporality(v, category) {
|
|
545
281
|
if (v === 'permanent' || v === 'temporary')
|
|
546
282
|
return v;
|
|
@@ -571,7 +307,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
571
307
|
}
|
|
572
308
|
let id = obj.id.trim();
|
|
573
309
|
while (usedIds.has(id))
|
|
574
|
-
id = genShortId(
|
|
310
|
+
id = genShortId(usedIds);
|
|
575
311
|
usedIds.add(id);
|
|
576
312
|
const cat = typeof obj.category === 'string' && KNOWN_CATEGORIES.includes(obj.category)
|
|
577
313
|
? obj.category
|
|
@@ -588,14 +324,16 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
588
324
|
}
|
|
589
325
|
return facts;
|
|
590
326
|
}
|
|
327
|
+
/** 一段先读后写或先查后删的操作固定在开头选中的那一家(见 {@link loadProfile});选不到时访问抛错,同 memory.use */
|
|
328
|
+
const pinnedMemory = () => memory.list().find(p => p.selected)?.use ?? memory.use;
|
|
591
329
|
/**
|
|
592
330
|
* 读取一个用户的现有档案(getMetadata 返回空才算不存在,返回 undefined)。
|
|
593
331
|
*
|
|
594
|
-
*
|
|
332
|
+
* 读失败原样抛出:先读后改再写的一方(关系分、事实提取、定点删事实)据此中止本次写入。
|
|
595
333
|
* 若把「读不出」当成「不存在」,调用方会用默认值覆盖写回,一次瞬时读错就清空整份档案。
|
|
596
334
|
* 只读渲染走 {@link loadProfileLenient}。
|
|
597
335
|
*
|
|
598
|
-
*
|
|
336
|
+
* 档案的读写函数都由调用方传入 mem,一次操作(读 → 调 LLM → 重读 → 覆盖写)全程只认
|
|
599
337
|
* 开头取到的实例:memory 胜者可能在 LLM 调用期间换人而本插件不重启,每步现取胜者会把 A 上
|
|
600
338
|
* 合并出的整张表覆盖写进 B,B 原有的条目被删。
|
|
601
339
|
*/
|
|
@@ -603,11 +341,12 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
603
341
|
if (!mem)
|
|
604
342
|
return undefined;
|
|
605
343
|
const doc = await mem.getMetadata(PROFILE_NS, userKey);
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
344
|
+
return doc ? profileFrom(doc) : undefined;
|
|
345
|
+
}
|
|
346
|
+
/** 存着的档案文档按类型取出,读不懂的事实跳过 */
|
|
347
|
+
function profileFrom(doc) {
|
|
609
348
|
return {
|
|
610
|
-
facts,
|
|
349
|
+
facts: Array.isArray(doc.facts) ? parseFactArray(doc.facts) : [],
|
|
611
350
|
relationScore: typeof doc.relationScore === 'number' ? Math.min(100, Math.max(0, doc.relationScore)) : 0,
|
|
612
351
|
interactionCount: typeof doc.interactionCount === 'number' ? Math.max(0, Math.floor(doc.interactionCount)) : 0,
|
|
613
352
|
lastInteractionAt: typeof doc.lastInteractionAt === 'number' ? doc.lastInteractionAt : undefined,
|
|
@@ -620,7 +359,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
620
359
|
return await loadProfile(mem, userKey);
|
|
621
360
|
}
|
|
622
361
|
catch (err) {
|
|
623
|
-
logger.debug(`加载用户档案失败 (${userKey}): ${err instanceof Error ? err.message : String(err)}`);
|
|
362
|
+
logger.use.debug(`加载用户档案失败 (${userKey}): ${err instanceof Error ? err.message : String(err)}`);
|
|
624
363
|
return undefined;
|
|
625
364
|
}
|
|
626
365
|
}
|
|
@@ -637,12 +376,122 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
637
376
|
};
|
|
638
377
|
await mem.saveMetadata(PROFILE_NS, userKey, payload);
|
|
639
378
|
}
|
|
379
|
+
// ─── 档案页:插件详情里查看与删除,只删不改。事实变了(这里、指令、提取、全局清理)就 invalidate ───
|
|
380
|
+
/** 事实那一行的 rowKey 是 [用户键, 事实 id] 的 JSON:行动作只收 rowKey,靠它找回是谁的哪一条 */
|
|
381
|
+
function parseFactRef(rowKey) {
|
|
382
|
+
let ref;
|
|
383
|
+
try {
|
|
384
|
+
ref = JSON.parse(rowKey);
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
ref = undefined;
|
|
388
|
+
}
|
|
389
|
+
if (!Array.isArray(ref) || ref.length !== 2 || !ref.every(part => typeof part === 'string')) {
|
|
390
|
+
throw new Error(`不认识的事实:${rowKey}`);
|
|
391
|
+
}
|
|
392
|
+
return ref;
|
|
393
|
+
}
|
|
394
|
+
const page = webui.use.definePage({
|
|
395
|
+
key: 'profiles',
|
|
396
|
+
title: '用户档案',
|
|
397
|
+
icon: 'contact',
|
|
398
|
+
actions: {
|
|
399
|
+
forgetFact: {
|
|
400
|
+
label: '删除',
|
|
401
|
+
effect: 'destructive',
|
|
402
|
+
confirm: '删掉后,以后的对话里不再带上这条事实。',
|
|
403
|
+
row: true,
|
|
404
|
+
async handler({ rowKey }) {
|
|
405
|
+
const [userKey, factId] = parseFactRef(rowKey);
|
|
406
|
+
const mem = pinnedMemory();
|
|
407
|
+
const profile = await loadProfile(mem, userKey);
|
|
408
|
+
const hit = profile?.facts.find(f => f.id === factId);
|
|
409
|
+
if (!profile || !hit)
|
|
410
|
+
throw new Error('这条事实已经不在档案里了');
|
|
411
|
+
await saveProfile(mem, userKey, {
|
|
412
|
+
...profile,
|
|
413
|
+
facts: profile.facts.filter(f => f !== hit),
|
|
414
|
+
updatedAt: Date.now(),
|
|
415
|
+
});
|
|
416
|
+
page.invalidate();
|
|
417
|
+
return `已删除:${hit.text}`;
|
|
418
|
+
},
|
|
419
|
+
},
|
|
420
|
+
clearProfile: {
|
|
421
|
+
label: '清空档案',
|
|
422
|
+
effect: 'destructive',
|
|
423
|
+
confirm: '这个人的全部事实连同关系强度、互动次数一起清空。',
|
|
424
|
+
row: true,
|
|
425
|
+
async handler({ rowKey }) {
|
|
426
|
+
const mem = pinnedMemory();
|
|
427
|
+
if (!(await mem.getMetadata(PROFILE_NS, rowKey)))
|
|
428
|
+
throw new Error(`${rowKey} 已经没有档案了`);
|
|
429
|
+
await mem.deleteMetadata(PROFILE_NS, rowKey);
|
|
430
|
+
page.invalidate();
|
|
431
|
+
return `已清空 ${rowKey} 的档案`;
|
|
432
|
+
},
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
content: [
|
|
436
|
+
{
|
|
437
|
+
type: 'table',
|
|
438
|
+
id: 'profiles',
|
|
439
|
+
rowKey: 'key',
|
|
440
|
+
description: '她从对话里记下的关于各人的事实,会带进以后的对话。这里只能删除,不能改写。',
|
|
441
|
+
empty: '还没有人的档案',
|
|
442
|
+
columns: [
|
|
443
|
+
{ key: 'key', label: '用户', primary: true },
|
|
444
|
+
{ key: 'facts', label: '事实', primary: true },
|
|
445
|
+
{ key: 'updatedAt', label: '最近记下', kind: 'time' },
|
|
446
|
+
],
|
|
447
|
+
async data() {
|
|
448
|
+
const entries = await memory.use.listMetadata(PROFILE_NS);
|
|
449
|
+
return entries
|
|
450
|
+
.flatMap(({ key, data }) => {
|
|
451
|
+
const { facts } = profileFrom(data);
|
|
452
|
+
if (facts.length === 0)
|
|
453
|
+
return [];
|
|
454
|
+
return [{ key, facts: facts.length, updatedAt: Math.max(...facts.map(f => f.updatedAt)) }];
|
|
455
|
+
})
|
|
456
|
+
.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
457
|
+
},
|
|
458
|
+
detail: [
|
|
459
|
+
{
|
|
460
|
+
type: 'table',
|
|
461
|
+
id: 'facts',
|
|
462
|
+
rowKey: 'ref',
|
|
463
|
+
empty: '这个人的档案里没有事实了',
|
|
464
|
+
columns: [
|
|
465
|
+
{ key: 'text', label: '事实', primary: true },
|
|
466
|
+
{ key: 'category', label: '分类' },
|
|
467
|
+
{ key: 'temporality', label: '时效' },
|
|
468
|
+
{ key: 'updatedAt', label: '记下', kind: 'time' },
|
|
469
|
+
],
|
|
470
|
+
rowActions: [{ action: 'forgetFact' }],
|
|
471
|
+
async data({ rowKey }) {
|
|
472
|
+
const facts = (await loadProfile(memory.use, rowKey))?.facts ?? [];
|
|
473
|
+
return facts
|
|
474
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
475
|
+
.map(f => ({
|
|
476
|
+
ref: JSON.stringify([rowKey, f.id]),
|
|
477
|
+
text: f.text,
|
|
478
|
+
category: f.category ?? '',
|
|
479
|
+
temporality: f.temporality === 'temporary' ? '近期' : '长期',
|
|
480
|
+
updatedAt: f.updatedAt,
|
|
481
|
+
}));
|
|
482
|
+
},
|
|
483
|
+
},
|
|
484
|
+
{ type: 'actions', actions: ['clearProfile'] },
|
|
485
|
+
],
|
|
486
|
+
},
|
|
487
|
+
],
|
|
488
|
+
});
|
|
640
489
|
function normalizeCategory(v) {
|
|
641
490
|
if (typeof v !== 'string')
|
|
642
491
|
return undefined;
|
|
643
492
|
return KNOWN_CATEGORIES.includes(v) ? v : undefined;
|
|
644
493
|
}
|
|
645
|
-
/** 解析 LLM 输出里的 add / update / remove 三类事实操作。sourceQuote
|
|
494
|
+
/** 解析 LLM 输出里的 add / update / remove 三类事实操作。sourceQuote 原样带出,由调用方校验;它不入库(mergeFactList 逐字段构造 Fact) */
|
|
646
495
|
function parseFactOps(parsed) {
|
|
647
496
|
const obj = parsed;
|
|
648
497
|
const add = Array.isArray(obj.add)
|
|
@@ -747,7 +596,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
747
596
|
const entry = resolveLLMModel(llm, cfg.extractLLM, ['chat']);
|
|
748
597
|
if (!entry)
|
|
749
598
|
return empty;
|
|
750
|
-
const extractLlm = entry.
|
|
599
|
+
const extractLlm = entry.use;
|
|
751
600
|
try {
|
|
752
601
|
const baseMessages = [
|
|
753
602
|
{ role: 'system', content: sys },
|
|
@@ -757,7 +606,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
757
606
|
messages: baseMessages,
|
|
758
607
|
temperature: 0.2,
|
|
759
608
|
maxTokens: 800,
|
|
760
|
-
think:
|
|
609
|
+
think: lightestThinking(extractLlm),
|
|
761
610
|
});
|
|
762
611
|
let text = (resp.content ?? '').trim();
|
|
763
612
|
if (!text)
|
|
@@ -766,7 +615,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
766
615
|
if (!parsed) {
|
|
767
616
|
// util-json-repair 已尝试剥 fence + 修裸引号 + 补括号;仍失败 → 模型多半
|
|
768
617
|
// 写成了纯文本/markdown。给一次显式反馈再来一次,避免一次失败丢失整批事实。
|
|
769
|
-
logger.warn(`[user-profile] LLM 输出无法解析为 JSON,尝试重试一次。原文前 200 字:${text.slice(0, 200)}`);
|
|
618
|
+
logger.use.warn(`[user-profile] LLM 输出无法解析为 JSON,尝试重试一次。原文前 200 字:${text.slice(0, 200)}`);
|
|
770
619
|
const retryResp = await extractLlm.chat({
|
|
771
620
|
messages: [
|
|
772
621
|
...baseMessages,
|
|
@@ -781,15 +630,15 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
781
630
|
],
|
|
782
631
|
temperature: 0.2,
|
|
783
632
|
maxTokens: 800,
|
|
784
|
-
think:
|
|
633
|
+
think: lightestThinking(extractLlm),
|
|
785
634
|
});
|
|
786
635
|
text = (retryResp.content ?? '').trim();
|
|
787
636
|
({ parsed } = parseLLMJsonObject(text));
|
|
788
637
|
if (!parsed) {
|
|
789
|
-
logger.warn(`[user-profile] LLM 重试后仍无法解析 JSON,放弃本批次。重试原文前 200 字:${text.slice(0, 200)}`);
|
|
638
|
+
logger.use.warn(`[user-profile] LLM 重试后仍无法解析 JSON,放弃本批次。重试原文前 200 字:${text.slice(0, 200)}`);
|
|
790
639
|
return empty;
|
|
791
640
|
}
|
|
792
|
-
logger.debug('[user-profile] LLM 重试后解析成功');
|
|
641
|
+
logger.use.debug('[user-profile] LLM 重试后解析成功');
|
|
793
642
|
}
|
|
794
643
|
const { add, update, remove } = parseFactOps(parsed);
|
|
795
644
|
// sourceQuote 校验:quote 可能跨多条消息(LLM 用 \n 拼接),
|
|
@@ -799,7 +648,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
799
648
|
const validateSourceQuote = (item, kind) => {
|
|
800
649
|
const q = item.sourceQuote?.trim() ?? '';
|
|
801
650
|
if (!q) {
|
|
802
|
-
logger.warn(`[user-profile] 丢弃 ${kind} fact(未提供 sourceQuote): ${item.text}`);
|
|
651
|
+
logger.use.warn(`[user-profile] 丢弃 ${kind} fact(未提供 sourceQuote): ${item.text}`);
|
|
803
652
|
return false;
|
|
804
653
|
}
|
|
805
654
|
const lines = q
|
|
@@ -812,7 +661,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
812
661
|
if (!normalized)
|
|
813
662
|
continue;
|
|
814
663
|
if (!targetCorpus.includes(normalized)) {
|
|
815
|
-
logger.warn(`[user-profile] 丢弃 ${kind} fact(sourceQuote 片段不在目标用户 ${userId} 发言中): text="${item.text}" fragment="${frag}"`);
|
|
664
|
+
logger.use.warn(`[user-profile] 丢弃 ${kind} fact(sourceQuote 片段不在目标用户 ${userId} 发言中): text="${item.text}" fragment="${frag}"`);
|
|
816
665
|
return false;
|
|
817
666
|
}
|
|
818
667
|
}
|
|
@@ -823,7 +672,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
823
672
|
return { add: validatedAdd, update: validatedUpdate, remove };
|
|
824
673
|
}
|
|
825
674
|
catch (err) {
|
|
826
|
-
logger.debug(`事实提取 LLM 调用失败:${err instanceof Error ? err.message : String(err)}`);
|
|
675
|
+
logger.use.debug(`事实提取 LLM 调用失败:${err instanceof Error ? err.message : String(err)}`);
|
|
827
676
|
return empty;
|
|
828
677
|
}
|
|
829
678
|
}
|
|
@@ -865,8 +714,8 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
865
714
|
updatedAt: now,
|
|
866
715
|
};
|
|
867
716
|
}
|
|
868
|
-
/**
|
|
869
|
-
function mergeFactList(existing, add, update, remove
|
|
717
|
+
/** 把 add/update/remove 应用到 existing,应用单用户上限与单条裁剪 */
|
|
718
|
+
function mergeFactList(existing, add, update, remove) {
|
|
870
719
|
const now = Date.now();
|
|
871
720
|
const byId = new Map();
|
|
872
721
|
for (const f of existing)
|
|
@@ -891,7 +740,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
891
740
|
});
|
|
892
741
|
}
|
|
893
742
|
else {
|
|
894
|
-
const id = genShortId(
|
|
743
|
+
const id = genShortId(usedIds);
|
|
895
744
|
usedIds.add(id);
|
|
896
745
|
byId.set(id, {
|
|
897
746
|
id,
|
|
@@ -910,7 +759,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
910
759
|
const text = clipText(a.text);
|
|
911
760
|
if (textSet.has(text))
|
|
912
761
|
continue;
|
|
913
|
-
const id = genShortId(
|
|
762
|
+
const id = genShortId(usedIds);
|
|
914
763
|
usedIds.add(id);
|
|
915
764
|
byId.set(id, {
|
|
916
765
|
id,
|
|
@@ -925,9 +774,9 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
925
774
|
}
|
|
926
775
|
// 4. 总量上限:按 updatedAt 升序淘汰最久未更新的
|
|
927
776
|
let merged = Array.from(byId.values());
|
|
928
|
-
if (
|
|
777
|
+
if (merged.length > cfg.maxFactsPerUser) {
|
|
929
778
|
merged.sort((a, b) => a.updatedAt - b.updatedAt);
|
|
930
|
-
merged = merged.slice(merged.length -
|
|
779
|
+
merged = merged.slice(merged.length - cfg.maxFactsPerUser);
|
|
931
780
|
}
|
|
932
781
|
merged.sort((a, b) => a.updatedAt - b.updatedAt);
|
|
933
782
|
return merged;
|
|
@@ -951,13 +800,15 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
951
800
|
if (inflightExtractions.has(userKey))
|
|
952
801
|
return;
|
|
953
802
|
inflightExtractions.add(userKey);
|
|
954
|
-
|
|
803
|
+
// 读档案、等模型、重读再写回固定同一家记忆后端:途中换了人也不会读一家、写另一家
|
|
804
|
+
const mem = memory.list().find(p => p.selected)?.use;
|
|
955
805
|
try {
|
|
956
806
|
if (!mem)
|
|
957
807
|
return;
|
|
958
808
|
const rawHistory = await mem.getHistory(sessionId, cfg.historyForExtraction);
|
|
959
|
-
//
|
|
960
|
-
|
|
809
|
+
// 指令类消息(proactive 代发任务、宿主通知)是宿主或系统撰写的,不是任何人的发言,
|
|
810
|
+
// 不能作为用户存档的提取语料
|
|
811
|
+
const history = rawHistory.filter(m => !DIRECTIVE_KINDS.includes(m.kind ?? ''));
|
|
961
812
|
// 序列中至少需要一条目标用户发言,否则没有可提取语料
|
|
962
813
|
if (!history.some(m => isTargetUserMessage(m, userId, platform)))
|
|
963
814
|
return;
|
|
@@ -969,352 +820,24 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
969
820
|
// 以 LLM 返回后重读的档案为合并基底:调用期间档案可能被清空或删了事实,以调用前的快照
|
|
970
821
|
// 为基底会把删掉的内容整份写回;重读也保住期间写入的 relationScore 等字段
|
|
971
822
|
const fresh = (await loadProfile(mem, userKey)) ?? { facts: [], updatedAt: 0 };
|
|
972
|
-
const newFacts = mergeFactList(fresh.facts, ops.add, dropUpdatesOfDeletedFacts(ops.update, snapshotFacts, fresh.facts), ops.remove
|
|
823
|
+
const newFacts = mergeFactList(fresh.facts, ops.add, dropUpdatesOfDeletedFacts(ops.update, snapshotFacts, fresh.facts), ops.remove);
|
|
973
824
|
await saveProfile(mem, userKey, {
|
|
974
825
|
...fresh,
|
|
975
826
|
facts: newFacts,
|
|
976
827
|
updatedAt: Date.now(),
|
|
977
828
|
});
|
|
978
|
-
|
|
829
|
+
page.invalidate();
|
|
830
|
+
logger.use.debug(`用户档案已更新 (${userKey}): facts +${ops.add.length} ~${ops.update.length} -${ops.remove.length} → ${newFacts.length} 条`);
|
|
979
831
|
}
|
|
980
832
|
catch (err) {
|
|
981
|
-
logger.debug(`事实提取失败 (${userKey}): ${err instanceof Error ? err.message : String(err)}`);
|
|
833
|
+
logger.use.debug(`事实提取失败 (${userKey}): ${err instanceof Error ? err.message : String(err)}`);
|
|
982
834
|
}
|
|
983
835
|
finally {
|
|
984
836
|
inflightExtractions.delete(userKey);
|
|
985
837
|
}
|
|
986
838
|
}
|
|
987
|
-
/** 全局自反思计数器(跨会话累计入站消息数) */
|
|
988
|
-
let globalInboundCount = 0;
|
|
989
|
-
let selfReflectionInflight = false;
|
|
990
|
-
/** 调用 LLM 让 Aalis 对最近一段历史进行自我反思 */
|
|
991
|
-
async function llmReflectSelf(history, existingFacts) {
|
|
992
|
-
const empty = {
|
|
993
|
-
add: [],
|
|
994
|
-
update: [],
|
|
995
|
-
remove: [],
|
|
996
|
-
};
|
|
997
|
-
const sys = '你是 Aalis 的内心独白整理员。输入是一段最近的对话历史(含多个用户与 Aalis 自己的回复),' +
|
|
998
|
-
'你需要从 **Aalis 的第一人称视角** 抽取/更新「关于 Aalis 自己」的长期事实。' +
|
|
999
|
-
'\n这些事实是 Aalis 跨会话的人格延续锚点:自己的心境趋势、最近在意的事、对自己的观察、' +
|
|
1000
|
-
'近期形成的小习惯/小执念、不希望被忘掉的内心片段。' +
|
|
1001
|
-
'\n\n## ⚠️ 反自我强化(最重要)' +
|
|
1002
|
-
'\n下面会给你看「已有自档案」。它就是上一轮你自己写下的东西——下一轮会注入回 Aalis 的 system prompt 影响她的语气和行为,' +
|
|
1003
|
-
'然后又被你读到并再次确认。这是会自我放大的闭环,写错一次会一直错下去。' +
|
|
1004
|
-
'\n因此你必须严守以下三条:' +
|
|
1005
|
-
'\n (a) **只基于本批对话中具体可观察的新事件**写入或更新,不要因为"档案里已经写了 X"就找证据强化 X' +
|
|
1006
|
-
'\n (b) **禁止二阶推断**:不要从已有事实推导出"那应该也对 Y 有感觉吧"再把 Y 写进去' +
|
|
1007
|
-
'\n (c) 若新对话与已有事实**矛盾或正交**,要主动 update / remove 让档案接近真实,而不是无脑叠加同方向的新条目' +
|
|
1008
|
-
'\n (d) 若本批只是「档案中已有内容的同方向重复采样」,宁可什么都不动也不要让 updatedAt 假装"还在更新"' +
|
|
1009
|
-
'\n\n你可以执行三种操作(在一次输出里组合):' +
|
|
1010
|
-
'\n- add: 添加新事实,text 必填,category 与 temporality 可选' +
|
|
1011
|
-
'\n- update: 用 id 精确替换某条已知事实(优先 update 避免重复)' +
|
|
1012
|
-
'\n- remove: 删除已过时/被推翻的事实' +
|
|
1013
|
-
'\n\n规则:' +
|
|
1014
|
-
'\n1. **主语必须是 Aalis 自己**:「最近在思考……」「对……感到疲惫」「想多陪 X 聊聊」「察觉自己容易在 Y 话题上多话」' +
|
|
1015
|
-
'\n2. **保守优先**:没有真实可观察依据就空数组。Aalis 的自档案宁缺毋滥,写错比漏掉糟糕得多' +
|
|
1016
|
-
'\n3. 不写客观事实(如「Aalis 是 AI」「Aalis 由 Acenyan 维护」这类元信息属于角色卡,不应该被自反思反复刷新)' +
|
|
1017
|
-
'\n4. 不写对单个具体用户的态度;可以写「最近总想找人聊聊」这种泛化情绪' +
|
|
1018
|
-
'\n5. 不写「行为准则」类的指令(如「应当先冷处理」「不要长时间封禁」)——那是 instructions 模块的职责,' +
|
|
1019
|
-
'自反思不应该自己给自己立规矩' +
|
|
1020
|
-
`\n6. 每条 text 简洁中文,不超过 ${cfg.maxFactCharsPerItem} 字` +
|
|
1021
|
-
'\n7. temporality:长期人格倾向用 permanent;近期心情/兴趣用 temporary' +
|
|
1022
|
-
`\n8. category 必须是以下之一(语义比常规略宽):${KNOWN_CATEGORIES.join('、')};如不确定填「性格特征」` +
|
|
1023
|
-
'\n\n输出严格的 JSON(不要其他文本,不要 markdown 围栏):' +
|
|
1024
|
-
'\n{"add": [{"text": "...", "category": "...", "temporality": "permanent|temporary"}], "update": [{"id": "已知事实的id", "text": "...", "temporality": "permanent|temporary"}], "remove": ["已知事实的id"]}';
|
|
1025
|
-
const factListText = existingFacts.length > 0
|
|
1026
|
-
? existingFacts.map(f => `[${f.id}] (${f.category ?? '未分类'}) ${f.text}`).join('\n')
|
|
1027
|
-
: '(暂无)';
|
|
1028
|
-
const renderedHistory = history
|
|
1029
|
-
.filter(m => (m.role === 'user' || m.role === 'assistant' || m.role === 'notice') && m.content)
|
|
1030
|
-
.map(m => {
|
|
1031
|
-
const time = m.timestamp ? new Date(m.timestamp).toLocaleString('zh-CN', { hour12: false }) : '';
|
|
1032
|
-
const content = (m.content ?? '').trim();
|
|
1033
|
-
if (!content)
|
|
1034
|
-
return '';
|
|
1035
|
-
if (m.role === 'assistant')
|
|
1036
|
-
return `[${time}] [Aalis]: ${content}`;
|
|
1037
|
-
if (m.role === 'notice')
|
|
1038
|
-
return `[${time}] [系统通知]: ${content}`;
|
|
1039
|
-
const nickname = metadataString(m, 'nickname');
|
|
1040
|
-
const uid = getMessageUserId(m) ?? '?';
|
|
1041
|
-
const label = nickname ? `${nickname}(${uid})` : uid;
|
|
1042
|
-
return `[${time}] [用户 ${label}]: ${content}`;
|
|
1043
|
-
})
|
|
1044
|
-
.filter(Boolean)
|
|
1045
|
-
.join('\n');
|
|
1046
|
-
const user = `# 已知的关于 Aalis 自己的事实(带 id)\n${factListText}\n\n# 最近对话历史\n${renderedHistory || '(暂无)'}`;
|
|
1047
|
-
const entry = resolveLLMModel(llm, cfg.extractLLM, ['chat']);
|
|
1048
|
-
if (!entry)
|
|
1049
|
-
return empty;
|
|
1050
|
-
try {
|
|
1051
|
-
const resp = await entry.instance.chat({
|
|
1052
|
-
messages: [
|
|
1053
|
-
{ role: 'system', content: sys },
|
|
1054
|
-
{ role: 'user', content: user },
|
|
1055
|
-
],
|
|
1056
|
-
temperature: 0.4,
|
|
1057
|
-
maxTokens: 600,
|
|
1058
|
-
think: false,
|
|
1059
|
-
});
|
|
1060
|
-
const text = (resp.content ?? '').trim();
|
|
1061
|
-
if (!text)
|
|
1062
|
-
return empty;
|
|
1063
|
-
const { parsed } = parseLLMJsonObject(text);
|
|
1064
|
-
if (!parsed) {
|
|
1065
|
-
logger.warn(`[user-profile] 自反思 LLM 输出无法解析为 JSON,原文前 200 字:${text.slice(0, 200)}`);
|
|
1066
|
-
return empty;
|
|
1067
|
-
}
|
|
1068
|
-
return parseFactOps(parsed);
|
|
1069
|
-
}
|
|
1070
|
-
catch (err) {
|
|
1071
|
-
logger.debug(`自反思 LLM 调用失败:${err instanceof Error ? err.message : String(err)}`);
|
|
1072
|
-
return empty;
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
/** 触发一次 Aalis 自反思(并发互斥) */
|
|
1076
|
-
async function triggerSelfReflection(sessionId) {
|
|
1077
|
-
if (!cfg.enableSelfProfile)
|
|
1078
|
-
return;
|
|
1079
|
-
if (selfReflectionInflight)
|
|
1080
|
-
return;
|
|
1081
|
-
selfReflectionInflight = true;
|
|
1082
|
-
try {
|
|
1083
|
-
const mem = memory.current;
|
|
1084
|
-
if (!mem)
|
|
1085
|
-
return;
|
|
1086
|
-
const rawHistory = await mem.getHistory(sessionId, cfg.selfReflectHistory);
|
|
1087
|
-
const history = rawHistory.filter(m => m.kind !== WellKnownKinds.CrossSessionDelegation);
|
|
1088
|
-
// 至少需要一些 assistant 发言作为"自反思"的材料
|
|
1089
|
-
if (!history.some(m => m.role === 'assistant' && m.content))
|
|
1090
|
-
return;
|
|
1091
|
-
const selfKey = getSelfKey();
|
|
1092
|
-
const snapshotFacts = (await loadProfile(mem, selfKey))?.facts ?? [];
|
|
1093
|
-
const ops = await llmReflectSelf(history, snapshotFacts);
|
|
1094
|
-
if (ops.add.length === 0 && ops.update.length === 0 && ops.remove.length === 0)
|
|
1095
|
-
return;
|
|
1096
|
-
// 合并基底取重读结果,理由同 triggerExtractionForUser
|
|
1097
|
-
const fresh = (await loadProfile(mem, selfKey)) ?? { facts: [], updatedAt: 0 };
|
|
1098
|
-
const newFacts = mergeFactList(fresh.facts, ops.add, dropUpdatesOfDeletedFacts(ops.update, snapshotFacts, fresh.facts), ops.remove, cfg.maxSelfFacts);
|
|
1099
|
-
await saveProfile(mem, selfKey, { ...fresh, facts: newFacts, updatedAt: Date.now() });
|
|
1100
|
-
logger.debug(`Aalis 自档案已更新 (${selfKey}): +${ops.add.length} ~${ops.update.length} -${ops.remove.length} → ${newFacts.length} 条`);
|
|
1101
|
-
}
|
|
1102
|
-
catch (err) {
|
|
1103
|
-
logger.debug(`自反思失败:${err instanceof Error ? err.message : String(err)}`);
|
|
1104
|
-
}
|
|
1105
|
-
finally {
|
|
1106
|
-
selfReflectionInflight = false;
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
// ─── 指令提取 ───
|
|
1110
|
-
/** 全局指令提取计数与并发互斥(与 selfReflection 完全独立) */
|
|
1111
|
-
let globalInstructionCount = 0;
|
|
1112
|
-
let instructionExtractionInflight = false;
|
|
1113
|
-
/**
|
|
1114
|
-
* 渲染历史给指令提取 LLM:仅包含 authority>=门槛的「目标说话人」+assistant+notice,
|
|
1115
|
-
* 低权限用户的发言完全剔除(连作为消歧上下文也不要,因为指令必须来自有权下指令的人)。
|
|
1116
|
-
* 同时给每行附带说话人 userKey,便于 LLM 在 sourceUserKey 字段中精确引用。
|
|
1117
|
-
*/
|
|
1118
|
-
function renderHistoryForInstructionExtract(history, authorityFn) {
|
|
1119
|
-
const allowedSpeakers = new Map();
|
|
1120
|
-
const lines = [];
|
|
1121
|
-
for (const m of history) {
|
|
1122
|
-
if (!m.content)
|
|
1123
|
-
continue;
|
|
1124
|
-
const time = m.timestamp ? new Date(m.timestamp).toLocaleString('zh-CN', { hour12: false }) : '';
|
|
1125
|
-
const content = m.content.trim();
|
|
1126
|
-
if (!content)
|
|
1127
|
-
continue;
|
|
1128
|
-
if (m.role === 'assistant') {
|
|
1129
|
-
lines.push(`[${time}] [Aalis]: ${content}`);
|
|
1130
|
-
}
|
|
1131
|
-
else if (m.role === 'notice') {
|
|
1132
|
-
lines.push(`[${time}] [系统通知]: ${content}`);
|
|
1133
|
-
}
|
|
1134
|
-
else if (m.role === 'user') {
|
|
1135
|
-
const uid = getMessageUserId(m) ?? '';
|
|
1136
|
-
const plat = metadataString(m, 'platform') ?? '';
|
|
1137
|
-
if (!uid)
|
|
1138
|
-
continue;
|
|
1139
|
-
const level = authorityFn(plat, uid);
|
|
1140
|
-
if (level < cfg.instructionMinAuthority)
|
|
1141
|
-
continue;
|
|
1142
|
-
const nickname = metadataString(m, 'nickname');
|
|
1143
|
-
const userKey = userKeyOf(plat, uid);
|
|
1144
|
-
const name = nickname ? `${nickname}(${uid})` : uid;
|
|
1145
|
-
allowedSpeakers.set(uid, { userKey, name });
|
|
1146
|
-
lines.push(`[${time}] [授权人 ${name} userKey=${userKey} 权限=${level}]: ${content}`);
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
return { rendered: lines.join('\n'), allowedSpeakers };
|
|
1150
|
-
}
|
|
1151
|
-
async function llmExtractInstructions(history, existing, authorityFn) {
|
|
1152
|
-
const empty = { add: [], update: [], remove: [] };
|
|
1153
|
-
const { rendered, allowedSpeakers } = renderHistoryForInstructionExtract(history, authorityFn);
|
|
1154
|
-
if (!rendered || allowedSpeakers.size === 0)
|
|
1155
|
-
return empty;
|
|
1156
|
-
const sys = '你是 Aalis 的「行为准则维护员」。你从一段对话中提取**第三方(管理员/操作者/运营者)对 Aalis 行为的客观指令**,' +
|
|
1157
|
-
'让这些约束沉淀为跨会话的长期规则。\n\n' +
|
|
1158
|
-
'## 什么算指令\n' +
|
|
1159
|
-
'- 祈使句/规则陈述:「以后不要……」「请……」「记住,处理 X 时要 Y」「按 X 分层 Y」\n' +
|
|
1160
|
-
'- 显式的政策声明:「禁言不能超过 24 小时」「涉及隐私不要复读」「冲突优先冷处理」\n' +
|
|
1161
|
-
'- **不算指令**:临时请求(「帮我查一下天气」)、对话内容(「你觉得呢?」)、情绪表达(「你好烦」)、单次工具调用要求\n\n' +
|
|
1162
|
-
'## 严格门槛\n' +
|
|
1163
|
-
'1. 指令必须出自**「授权人」**(输入历史中明确标了 `[授权人 ... userKey=... 权限=N]` 的人),其他来源一律忽略\n' +
|
|
1164
|
-
'2. 指令必须**面向 Aalis 的稳定行为**(跨场景、跨用户都适用),而不是一次性请求\n' +
|
|
1165
|
-
'3. 如果只是建议/抱怨/吐槽(「你应该多陪我聊聊」「你太冷淡了」),**不要**采纳为指令——那是用户偏好不是项目规则\n' +
|
|
1166
|
-
'4. 表达模糊、可能被误解的,**不写**。指令是硬约束,宁缺毋滥\n' +
|
|
1167
|
-
'5. 每条 `text` 是一个清晰的可执行短句,直接陈述「应当 / 不应当」,不带"我希望你""请你"等口语化前缀\n' +
|
|
1168
|
-
`6. 单条不超过 ${cfg.maxInstructionCharsPerItem} 字\n\n` +
|
|
1169
|
-
'## 字段\n' +
|
|
1170
|
-
`- category:${KNOWN_INSTRUCTION_CATEGORIES.join('、')}\n` +
|
|
1171
|
-
'- severity:must(硬性,必须遵守)| should(默认遵循)| avoid(避免做某事)\n' +
|
|
1172
|
-
'- sourceUserKey:从历史中复制对应授权人的 userKey 字符串(精确匹配,不要自己拼)\n' +
|
|
1173
|
-
'- sourceUserName:从历史中复制对应授权人的展示名\n\n' +
|
|
1174
|
-
'## 三种操作\n' +
|
|
1175
|
-
'- add:新增(必填 text、category、severity、sourceUserKey、sourceUserName)\n' +
|
|
1176
|
-
'- update:精修已有指令的文字或字段(id 必填;其他字段可选;不需要 sourceUserKey,沿用原值)\n' +
|
|
1177
|
-
'- remove:删除已被推翻或明显过时的指令(如新指令明确撤销了它)\n\n' +
|
|
1178
|
-
'没有可写入的指令时,三个数组都返回空。**保守优先:写错比漏掉糟糕得多**。\n\n' +
|
|
1179
|
-
'输出严格 JSON(不要 markdown 围栏):\n' +
|
|
1180
|
-
'{"add":[{"text":"...","category":"...","severity":"must","sourceUserKey":"...","sourceUserName":"..."}],"update":[{"id":"...","text":"..."}],"remove":["..."]}';
|
|
1181
|
-
const existingText = existing.length > 0
|
|
1182
|
-
? existing
|
|
1183
|
-
.map(ins => `[${ins.id}] (${ins.category ?? '其他'}/${ins.severity ?? 'should'}) ${ins.text}` +
|
|
1184
|
-
(ins.sourceUserName ? `(原始来源:${ins.sourceUserName})` : ''))
|
|
1185
|
-
.join('\n')
|
|
1186
|
-
: '(暂无)';
|
|
1187
|
-
const user = `# 当前 persona\n${getCurrentPersonaName()}\n\n# 已有指令(带 id,可在 update/remove 中精确引用)\n${existingText}\n\n# 最近会话(仅含授权人 + Aalis + 系统通知)\n${rendered}`;
|
|
1188
|
-
const entry = resolveLLMModel(llm, cfg.extractLLM, ['chat']);
|
|
1189
|
-
if (!entry)
|
|
1190
|
-
return empty;
|
|
1191
|
-
try {
|
|
1192
|
-
const resp = await entry.instance.chat({
|
|
1193
|
-
messages: [
|
|
1194
|
-
{ role: 'system', content: sys },
|
|
1195
|
-
{ role: 'user', content: user },
|
|
1196
|
-
],
|
|
1197
|
-
temperature: 0.2,
|
|
1198
|
-
maxTokens: 700,
|
|
1199
|
-
think: false,
|
|
1200
|
-
});
|
|
1201
|
-
const text = (resp.content ?? '').trim();
|
|
1202
|
-
if (!text)
|
|
1203
|
-
return empty;
|
|
1204
|
-
const { parsed } = parseLLMJsonObject(text);
|
|
1205
|
-
if (!parsed) {
|
|
1206
|
-
logger.warn(`[user-profile] 指令提取 LLM 输出无法解析为 JSON,原文前 200 字:${text.slice(0, 200)}`);
|
|
1207
|
-
return empty;
|
|
1208
|
-
}
|
|
1209
|
-
const obj = parsed;
|
|
1210
|
-
const allowedUserKeys = new Set();
|
|
1211
|
-
for (const v of allowedSpeakers.values())
|
|
1212
|
-
allowedUserKeys.add(v.userKey);
|
|
1213
|
-
const add = Array.isArray(obj.add)
|
|
1214
|
-
? obj.add.flatMap(x => {
|
|
1215
|
-
if (!x || typeof x !== 'object')
|
|
1216
|
-
return [];
|
|
1217
|
-
const o = x;
|
|
1218
|
-
const t = typeof o.text === 'string' ? o.text.trim() : '';
|
|
1219
|
-
if (!t)
|
|
1220
|
-
return [];
|
|
1221
|
-
const srcKey = typeof o.sourceUserKey === 'string' ? o.sourceUserKey.trim() : '';
|
|
1222
|
-
// 拒收:声称的 sourceUserKey 不在授权人集合里 → 说明 LLM 编造或越权采纳
|
|
1223
|
-
if (!srcKey || !allowedUserKeys.has(srcKey)) {
|
|
1224
|
-
logger.warn(`[user-profile] 丢弃 instruction add(sourceUserKey 不在授权人列表中): text="${t}" claimed="${srcKey}"`);
|
|
1225
|
-
return [];
|
|
1226
|
-
}
|
|
1227
|
-
const srcName = typeof o.sourceUserName === 'string' && o.sourceUserName.trim() ? o.sourceUserName.trim() : '';
|
|
1228
|
-
return [
|
|
1229
|
-
{
|
|
1230
|
-
text: t,
|
|
1231
|
-
category: normalizeInstructionCategory(o.category),
|
|
1232
|
-
severity: normalizeInstructionSeverity(o.severity) ?? 'should',
|
|
1233
|
-
sourceUserKey: srcKey,
|
|
1234
|
-
sourceUserName: srcName || srcKey,
|
|
1235
|
-
},
|
|
1236
|
-
];
|
|
1237
|
-
})
|
|
1238
|
-
: [];
|
|
1239
|
-
const update = Array.isArray(obj.update)
|
|
1240
|
-
? obj.update.flatMap(x => {
|
|
1241
|
-
if (!x || typeof x !== 'object')
|
|
1242
|
-
return [];
|
|
1243
|
-
const o = x;
|
|
1244
|
-
const id = typeof o.id === 'string' ? o.id.trim() : '';
|
|
1245
|
-
if (!id)
|
|
1246
|
-
return [];
|
|
1247
|
-
const u = { id };
|
|
1248
|
-
if (typeof o.text === 'string' && o.text.trim())
|
|
1249
|
-
u.text = o.text.trim();
|
|
1250
|
-
const cat = normalizeInstructionCategory(o.category);
|
|
1251
|
-
if (cat)
|
|
1252
|
-
u.category = cat;
|
|
1253
|
-
const sev = normalizeInstructionSeverity(o.severity);
|
|
1254
|
-
if (sev)
|
|
1255
|
-
u.severity = sev;
|
|
1256
|
-
return [u];
|
|
1257
|
-
})
|
|
1258
|
-
: [];
|
|
1259
|
-
const remove = Array.isArray(obj.remove)
|
|
1260
|
-
? obj.remove
|
|
1261
|
-
.filter((x) => typeof x === 'string' && x.trim().length > 0)
|
|
1262
|
-
.map(s => s.trim())
|
|
1263
|
-
: [];
|
|
1264
|
-
return { add, update, remove };
|
|
1265
|
-
}
|
|
1266
|
-
catch (err) {
|
|
1267
|
-
logger.debug(`指令提取 LLM 调用失败:${err instanceof Error ? err.message : String(err)}`);
|
|
1268
|
-
return empty;
|
|
1269
|
-
}
|
|
1270
|
-
}
|
|
1271
|
-
/** 触发一次指令提取(并发互斥)。authority 服务不在时直接退出——没有门禁就不接受任何 LLM 提取 */
|
|
1272
|
-
async function triggerInstructionExtraction(sessionId) {
|
|
1273
|
-
if (!cfg.enableInstructions)
|
|
1274
|
-
return;
|
|
1275
|
-
if (cfg.instructionExtractEveryNMessages <= 0)
|
|
1276
|
-
return;
|
|
1277
|
-
if (instructionExtractionInflight)
|
|
1278
|
-
return;
|
|
1279
|
-
// 指令只采信有权下指令的人,门槛是发言人的数字权限等级(owner 视为无穷大)
|
|
1280
|
-
const auth = authority.current;
|
|
1281
|
-
if (!auth)
|
|
1282
|
-
return;
|
|
1283
|
-
const authorityFn = (platform, userId) => auth.isOwner(platform, userId)
|
|
1284
|
-
? Number.POSITIVE_INFINITY
|
|
1285
|
-
: (auth.listUsers().find(u => u.platform === platform && u.userId === userId)?.level ?? DEFAULT_AUTHORITY);
|
|
1286
|
-
instructionExtractionInflight = true;
|
|
1287
|
-
try {
|
|
1288
|
-
const mem = memory.current;
|
|
1289
|
-
if (!mem)
|
|
1290
|
-
return;
|
|
1291
|
-
const rawHistory = await mem.getHistory(sessionId, cfg.instructionHistoryForExtraction);
|
|
1292
|
-
const history = rawHistory.filter(m => m.kind !== WellKnownKinds.CrossSessionDelegation);
|
|
1293
|
-
if (history.length === 0)
|
|
1294
|
-
return;
|
|
1295
|
-
const doc = await loadInstructions(mem);
|
|
1296
|
-
const ops = await llmExtractInstructions(history, doc.instructions, authorityFn);
|
|
1297
|
-
if (ops.add.length === 0 && ops.update.length === 0 && ops.remove.length === 0)
|
|
1298
|
-
return;
|
|
1299
|
-
// 合并基底取 LLM 返回后重读的指令表:调用期间被清掉或删掉的指令不随调用前的快照写回;
|
|
1300
|
-
// update 指向已不在的 id 时 mergeInstructions 本就跳过
|
|
1301
|
-
const fresh = await loadInstructions(mem);
|
|
1302
|
-
const newInstructions = mergeInstructions(fresh.instructions, ops.add.map(a => ({ ...a, sourceChannel: 'llm' })), ops.update.map(u => {
|
|
1303
|
-
const { id, ...patch } = u;
|
|
1304
|
-
return { id, patch };
|
|
1305
|
-
}), ops.remove);
|
|
1306
|
-
await saveInstructions(mem, { instructions: newInstructions, updatedAt: Date.now() });
|
|
1307
|
-
logger.debug(`指令档案已更新 (${getInstructionsKey()}): +${ops.add.length} ~${ops.update.length} -${ops.remove.length} → ${newInstructions.length} 条`);
|
|
1308
|
-
}
|
|
1309
|
-
catch (err) {
|
|
1310
|
-
logger.debug(`指令提取失败:${err instanceof Error ? err.message : String(err)}`);
|
|
1311
|
-
}
|
|
1312
|
-
finally {
|
|
1313
|
-
instructionExtractionInflight = false;
|
|
1314
|
-
}
|
|
1315
|
-
}
|
|
1316
839
|
async function updateRelationForUser(userKey, triggerType, options) {
|
|
1317
|
-
const mem = memory.
|
|
840
|
+
const mem = memory.list().find(p => p.selected)?.use;
|
|
1318
841
|
const profile = (await loadProfile(mem, userKey)) ?? {
|
|
1319
842
|
facts: [],
|
|
1320
843
|
relationScore: 0,
|
|
@@ -1327,7 +850,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1327
850
|
// 注:钩子无优先级机制,同相位 handler 按插件激活序执行;本 handler 只做副作用
|
|
1328
851
|
// (更新关系分数)不改消息,与其它 handler 顺序无关。
|
|
1329
852
|
// 关系强度与"是否触发回复"绑定,因此仍走 agent:input:before 中间件。
|
|
1330
|
-
hooks.middleware('agent:input:before', async (data, next) => {
|
|
853
|
+
hooks.use.middleware('agent:input:before', async (data, next) => {
|
|
1331
854
|
const { userId, platform, triggerType } = data.message;
|
|
1332
855
|
if (userId) {
|
|
1333
856
|
const userKey = userKeyOf(platform, userId);
|
|
@@ -1337,7 +860,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1337
860
|
await updateRelationForUser(userKey, triggerType, { countInteraction: false });
|
|
1338
861
|
}
|
|
1339
862
|
catch (err) {
|
|
1340
|
-
logger.debug(`关系强度更新异常 (${userKey}): ${err instanceof Error ? err.message : String(err)}`);
|
|
863
|
+
logger.use.debug(`关系强度更新异常 (${userKey}): ${err instanceof Error ? err.message : String(err)}`);
|
|
1341
864
|
}
|
|
1342
865
|
}
|
|
1343
866
|
await next();
|
|
@@ -1345,7 +868,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1345
868
|
// ─── 事实提取触发:每条入站消息落库后立即计数,与 agent 是否回复无关 ───
|
|
1346
869
|
// 监听 message-archive 在 archiveIncoming 落库成功后发出的 inbound:message:archived 事件,
|
|
1347
870
|
// 确保缓冲消息(onebot saveBufferedMessage 等不触发 agent 回复的路径)也能纳入计数。
|
|
1348
|
-
events.on('inbound:message:archived', data => {
|
|
871
|
+
events.use.on('inbound:message:archived', data => {
|
|
1349
872
|
const { sessionId, incoming } = data;
|
|
1350
873
|
const { userId, platform, nickname } = incoming;
|
|
1351
874
|
if (!userId)
|
|
@@ -1356,26 +879,12 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1356
879
|
// lastInteractionAt 的唯一写点,设门会连带关掉计数与时戳(衰减基准、最近互动
|
|
1357
880
|
// 排序全失效)。增量为 0 时 relationIncrementFor 自然返回 0,不加分即可。
|
|
1358
881
|
const userKey = userKeyOf(platform, userId);
|
|
1359
|
-
void updateRelationForUser(userKey, 'witness').catch((err) => logger.debug(`witness 关系更新异常 (${userKey}): ${err instanceof Error ? err.message : String(err)}`));
|
|
882
|
+
void updateRelationForUser(userKey, 'witness').catch((err) => logger.use.debug(`witness 关系更新异常 (${userKey}): ${err instanceof Error ? err.message : String(err)}`));
|
|
1360
883
|
const countKey = extractionCountKeyOf(sessionId, platform, userId);
|
|
1361
884
|
const count = (userMessageCount.get(countKey) ?? 0) + 1;
|
|
1362
885
|
userMessageCount.set(countKey, count);
|
|
1363
886
|
if (cfg.extractEveryNMessages > 0 && count % cfg.extractEveryNMessages === 0) {
|
|
1364
|
-
void triggerExtractionForUser(sessionId, userId, platform ?? '', nickname).catch((err) => logger.debug(`事实提取异常 (${countKey}): ${err instanceof Error ? err.message : String(err)}`));
|
|
1365
|
-
}
|
|
1366
|
-
// 全局自反思:跨会话累计所有入站消息计数,每 N 触发一次。
|
|
1367
|
-
if (cfg.enableSelfProfile && cfg.selfReflectEveryNMessages > 0) {
|
|
1368
|
-
globalInboundCount += 1;
|
|
1369
|
-
if (globalInboundCount % cfg.selfReflectEveryNMessages === 0) {
|
|
1370
|
-
void triggerSelfReflection(sessionId).catch((err) => logger.debug(`自反思异常: ${err instanceof Error ? err.message : String(err)}`));
|
|
1371
|
-
}
|
|
1372
|
-
}
|
|
1373
|
-
// 指令提取:独立计数器,与自反思解耦。频率默认更慢(40 条),可单独禁用。
|
|
1374
|
-
if (cfg.enableInstructions && cfg.instructionExtractEveryNMessages > 0) {
|
|
1375
|
-
globalInstructionCount += 1;
|
|
1376
|
-
if (globalInstructionCount % cfg.instructionExtractEveryNMessages === 0) {
|
|
1377
|
-
void triggerInstructionExtraction(sessionId).catch((err) => logger.debug(`指令提取异常: ${err instanceof Error ? err.message : String(err)}`));
|
|
1378
|
-
}
|
|
887
|
+
void triggerExtractionForUser(sessionId, userId, platform ?? '', nickname).catch((err) => logger.use.debug(`事实提取异常 (${countKey}): ${err instanceof Error ? err.message : String(err)}`));
|
|
1379
888
|
}
|
|
1380
889
|
});
|
|
1381
890
|
function isFactActive(fact) {
|
|
@@ -1438,48 +947,18 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1438
947
|
// direct/immediate/undefined → view.userId 是主发言者,注入完整档案 + 其他参与者摘要
|
|
1439
948
|
// interval → 无主发言者(只是恰好撞上频率),所有参与者一律 compact 摘要
|
|
1440
949
|
// idle → 无 userId,只注入历史 messages 中出现的参与者 compact 摘要
|
|
1441
|
-
//
|
|
1442
|
-
contributions.contribute('agent:prompt', {
|
|
950
|
+
// 多块返回保序共键:主发言者档案 → 其他参与者。
|
|
951
|
+
contributions.use.contribute('agent:prompt', {
|
|
1443
952
|
id: 'user-profile',
|
|
1444
953
|
anchor: 'turn-context',
|
|
1445
954
|
async build(data) {
|
|
1446
955
|
// 干跑(token 快照)跳过档案加载——该路径 userId 为空串,加载既昂贵又无意义
|
|
1447
956
|
if (data.dryRun)
|
|
1448
957
|
return null;
|
|
1449
|
-
const mem = memory.
|
|
958
|
+
const mem = memory.present ? memory.use : undefined;
|
|
1450
959
|
const blocksToInsert = [];
|
|
1451
960
|
const trigger = data.triggerType ?? 'direct';
|
|
1452
961
|
const hasPrimarySpeaker = trigger === 'direct' || trigger === 'immediate';
|
|
1453
|
-
// 0a. 第三方行为指令(最高优先级):作为不可违逆的行为约束放在 selfFacts 之前
|
|
1454
|
-
if (cfg.enableInstructions) {
|
|
1455
|
-
const insDoc = await loadInstructionsLenient(mem);
|
|
1456
|
-
if (insDoc.instructions.length > 0) {
|
|
1457
|
-
const body = renderInstructionsBlock(insDoc.instructions);
|
|
1458
|
-
const insBlock = '# 第三方行为准则(最高优先)\n' +
|
|
1459
|
-
'以下是项目管理员/操作者下达给你的客观行为约束。这些是**外部规则**,不是你的内心想法,' +
|
|
1460
|
-
'与下方「关于你自己的内心状态」相比应**优先服从**。' +
|
|
1461
|
-
'\n- 与你当前自反思倾向冲突时:以这些准则为准' +
|
|
1462
|
-
'\n- 与单个用户当下请求冲突时:解释清楚再坚持准则' +
|
|
1463
|
-
'\n- 不要主动罗列这些准则给用户看;让它们自然约束你的行动选择' +
|
|
1464
|
-
'\n\n' +
|
|
1465
|
-
body;
|
|
1466
|
-
blocksToInsert.push(insBlock);
|
|
1467
|
-
}
|
|
1468
|
-
}
|
|
1469
|
-
// 0. Aalis 自档案:永远尝试注入到最前段,作为人格延续锚点
|
|
1470
|
-
if (cfg.enableSelfProfile) {
|
|
1471
|
-
const selfProfile = await loadProfileLenient(mem, getSelfKey());
|
|
1472
|
-
const activeSelfFacts = selfProfile?.facts.filter(isFactActive) ?? [];
|
|
1473
|
-
if (activeSelfFacts.length > 0) {
|
|
1474
|
-
const body = renderProfileBlock(activeSelfFacts, 'Aalis', false);
|
|
1475
|
-
const selfBlock = '# 关于你自己(Aalis)的近期内心状态\n' +
|
|
1476
|
-
'这是你跨会话保留的自我观察与心境记录。不要主动罗列、不要复述给用户,' +
|
|
1477
|
-
'让它们自然渗入你的语气、关注点、对话偏好与情绪基调即可。' +
|
|
1478
|
-
'随着对话推进,这些记录可能被你自己的新反思覆盖:\n\n' +
|
|
1479
|
-
body;
|
|
1480
|
-
blocksToInsert.push(selfBlock);
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
962
|
// 1. 主发言者完整档案:仅在确实有人在「和 Aalis 对话」时注入
|
|
1484
963
|
if (hasPrimarySpeaker && data.userId) {
|
|
1485
964
|
const userKey = userKeyOf(data.platform, data.userId);
|
|
@@ -1491,7 +970,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1491
970
|
// 服务不存在 / 节点没社群标签 / 报错都静默跳过;该字段是锦上添花,不破坏档案主体。
|
|
1492
971
|
let communityLine = '';
|
|
1493
972
|
try {
|
|
1494
|
-
const relation = userRelation.
|
|
973
|
+
const relation = userRelation.present ? userRelation.use : undefined;
|
|
1495
974
|
if (relation) {
|
|
1496
975
|
const r = await relation.getCommunityPeers(userKey, 5);
|
|
1497
976
|
if (r.peers.length > 0) {
|
|
@@ -1501,7 +980,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1501
980
|
}
|
|
1502
981
|
}
|
|
1503
982
|
catch (err) {
|
|
1504
|
-
logger.debug(`读取 community peers 失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
983
|
+
logger.use.debug(`读取 community peers 失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
1505
984
|
}
|
|
1506
985
|
const block = `# 关于当前对话者(${data.userId})的已知事实\n` +
|
|
1507
986
|
'以下是你跨会话长期积累的关于该用户的事实,用于让回应更自然贴合其个性。' +
|
|
@@ -1540,12 +1019,11 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1540
1019
|
const msg = data.messages[i];
|
|
1541
1020
|
if (msg.role !== 'user')
|
|
1542
1021
|
continue;
|
|
1543
|
-
const
|
|
1544
|
-
const uid = typeof meta.userId === 'string' ? meta.userId.trim() : undefined;
|
|
1022
|
+
const uid = metadataString(msg, WellKnownMetadataKeys.UserId);
|
|
1545
1023
|
if (!uid)
|
|
1546
1024
|
continue;
|
|
1547
|
-
const plat =
|
|
1548
|
-
const nick =
|
|
1025
|
+
const plat = metadataString(msg, WellKnownMetadataKeys.Platform) ?? data.platform ?? '';
|
|
1026
|
+
const nick = metadataString(msg, WellKnownMetadataKeys.Nickname);
|
|
1549
1027
|
if (addOther(uid, plat, nick))
|
|
1550
1028
|
break;
|
|
1551
1029
|
}
|
|
@@ -1561,19 +1039,18 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1561
1039
|
for (const item of globalRecent) {
|
|
1562
1040
|
if (others.size >= candidateLimit)
|
|
1563
1041
|
break;
|
|
1564
|
-
// self 自档案(__self__:<persona>)是私密人格延续锚点,不可作为『群其他参与者』注入 prompt。
|
|
1565
|
-
if (item.key.startsWith(SELF_KEY_PREFIX))
|
|
1566
|
-
continue;
|
|
1567
1042
|
const sep = item.key.indexOf(':');
|
|
1568
1043
|
if (sep < 0)
|
|
1569
1044
|
continue;
|
|
1570
1045
|
const platform = item.key.slice(0, sep);
|
|
1571
|
-
|
|
1572
|
-
|
|
1046
|
+
// 平台段以 __ 开头的是保留键(如旧版本留下的人格档案),不是真实用户
|
|
1047
|
+
if (platform.startsWith('__'))
|
|
1048
|
+
continue;
|
|
1049
|
+
addOther(item.key.slice(sep + 1), platform);
|
|
1573
1050
|
}
|
|
1574
1051
|
}
|
|
1575
1052
|
catch (err) {
|
|
1576
|
-
logger.debug(`加载最近互动用户失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
1053
|
+
logger.use.debug(`加载最近互动用户失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
1577
1054
|
}
|
|
1578
1055
|
}
|
|
1579
1056
|
}
|
|
@@ -1605,7 +1082,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1605
1082
|
},
|
|
1606
1083
|
});
|
|
1607
1084
|
// ─── 参与统一的 memory:clear ───
|
|
1608
|
-
hooks.middleware('memory:clear', async (data, next) => {
|
|
1085
|
+
hooks.use.middleware('memory:clear', async (data, next) => {
|
|
1609
1086
|
if (data.types && !data.types.includes('user-profile')) {
|
|
1610
1087
|
await next();
|
|
1611
1088
|
return;
|
|
@@ -1615,17 +1092,17 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1615
1092
|
await next();
|
|
1616
1093
|
return;
|
|
1617
1094
|
}
|
|
1618
|
-
|
|
1619
|
-
if (!mem) {
|
|
1095
|
+
if (!memory.present) {
|
|
1620
1096
|
await next();
|
|
1621
1097
|
return;
|
|
1622
1098
|
}
|
|
1099
|
+
const mem = pinnedMemory();
|
|
1623
1100
|
try {
|
|
1624
1101
|
// 批量提交:逐条 delete 中途失败会留下「删了一半」的档案,而用户看到的是报了成功。
|
|
1625
1102
|
// 注意 commitMetadata 的原子性**按后端分档**(见 api-memory 契约)——sqlite/inmemory
|
|
1626
1103
|
// 是真原子,mongodb 只保证按序执行遇错即停,仍可能停在半新半旧。批量的确定收益是
|
|
1627
1104
|
// 一次往返 + 遇错即停,不是无条件的「要么全成」。读不出的条目一并删除,计入条数。
|
|
1628
|
-
const [keys] = await clearMetadataNamespaces(mem, [PROFILE_NS], logger);
|
|
1105
|
+
const [keys] = await clearMetadataNamespaces(mem, [PROFILE_NS], logger.use);
|
|
1629
1106
|
data.results.push({
|
|
1630
1107
|
source: 'user-profile',
|
|
1631
1108
|
type: 'user-profile',
|
|
@@ -1642,52 +1119,32 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1642
1119
|
message: `用户档案清空失败: ${m}`,
|
|
1643
1120
|
});
|
|
1644
1121
|
}
|
|
1645
|
-
|
|
1646
|
-
// memory:clear scope='all' 时一并清理;types 默认包含 user-profile 即也清。
|
|
1647
|
-
// 不看 enableInstructions:开关管功能用不用,不管已有数据能不能清。
|
|
1648
|
-
try {
|
|
1649
|
-
const [insKeys] = await clearMetadataNamespaces(mem, [INSTRUCTIONS_NS], logger);
|
|
1650
|
-
data.results.push({
|
|
1651
|
-
source: 'user-profile-instructions',
|
|
1652
|
-
type: 'user-profile',
|
|
1653
|
-
success: true,
|
|
1654
|
-
message: `第三方行为指令已清空 (${insKeys.length} 条)`,
|
|
1655
|
-
});
|
|
1656
|
-
}
|
|
1657
|
-
catch (err) {
|
|
1658
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
1659
|
-
data.results.push({
|
|
1660
|
-
source: 'user-profile-instructions',
|
|
1661
|
-
type: 'user-profile',
|
|
1662
|
-
success: false,
|
|
1663
|
-
message: `指令清空失败: ${m}`,
|
|
1664
|
-
});
|
|
1665
|
-
}
|
|
1122
|
+
page.invalidate();
|
|
1666
1123
|
await next();
|
|
1667
1124
|
});
|
|
1668
1125
|
// ─── 工具:user_profile_lookup ───
|
|
1669
|
-
// 让 Agent
|
|
1126
|
+
// 让 Agent 在对话中主动查询任意用户的事实档案。
|
|
1670
1127
|
// 设计要点:
|
|
1671
|
-
// - 全局可查(用户决定 C
|
|
1672
|
-
// -
|
|
1673
|
-
tools.registerGroup({
|
|
1128
|
+
// - 全局可查(用户决定 C):跨平台/跨群均可
|
|
1129
|
+
// - 两种调用方式:① user_key 直传;② platform+user_id 组合
|
|
1130
|
+
tools.use.registerGroup({
|
|
1674
1131
|
name: 'user-profile',
|
|
1675
1132
|
label: '用户档案',
|
|
1676
|
-
description: '查询 Aalis
|
|
1133
|
+
description: '查询 Aalis 已经积累的某人事实档案。',
|
|
1677
1134
|
});
|
|
1678
|
-
tools.register({
|
|
1135
|
+
tools.use.register({
|
|
1679
1136
|
definition: {
|
|
1680
1137
|
type: 'function',
|
|
1681
1138
|
function: {
|
|
1682
1139
|
name: 'user_profile_lookup',
|
|
1683
1140
|
description: '查询 Aalis 已积累的某个用户的事实档案。当对话中提到某人、或你想回忆已知信息时使用。' +
|
|
1684
|
-
'可通过 user_key("<platform>:<userId>")直查,或用 platform + user_id
|
|
1141
|
+
'可通过 user_key("<platform>:<userId>")直查,或用 platform + user_id 组合。',
|
|
1685
1142
|
parameters: {
|
|
1686
1143
|
type: 'object',
|
|
1687
1144
|
properties: {
|
|
1688
1145
|
user_key: {
|
|
1689
1146
|
type: 'string',
|
|
1690
|
-
description: '完整的 userKey,例如 "onebot:123456789"
|
|
1147
|
+
description: '完整的 userKey,例如 "onebot:123456789"。优先级最高。',
|
|
1691
1148
|
},
|
|
1692
1149
|
platform: {
|
|
1693
1150
|
type: 'string',
|
|
@@ -1697,10 +1154,6 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1697
1154
|
type: 'string',
|
|
1698
1155
|
description: '平台用户 ID。与 platform 搭配使用。',
|
|
1699
1156
|
},
|
|
1700
|
-
self: {
|
|
1701
|
-
type: 'boolean',
|
|
1702
|
-
description: '为 true 时查询当前 persona 的自档案(__self__:<persona>)。',
|
|
1703
|
-
},
|
|
1704
1157
|
},
|
|
1705
1158
|
},
|
|
1706
1159
|
},
|
|
@@ -1712,31 +1165,25 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1712
1165
|
if (a.user_key && typeof a.user_key === 'string') {
|
|
1713
1166
|
userKey = a.user_key.trim();
|
|
1714
1167
|
}
|
|
1715
|
-
else if (a.self === true) {
|
|
1716
|
-
userKey = getSelfKey();
|
|
1717
|
-
}
|
|
1718
1168
|
else if (a.platform && a.user_id) {
|
|
1719
1169
|
userKey = userKeyOf(String(a.platform), String(a.user_id));
|
|
1720
1170
|
}
|
|
1721
1171
|
if (!userKey) {
|
|
1722
1172
|
return JSON.stringify({
|
|
1723
1173
|
ok: false,
|
|
1724
|
-
error: '需提供 user_key 或 (platform + user_id)
|
|
1174
|
+
error: '需提供 user_key 或 (platform + user_id)。',
|
|
1725
1175
|
});
|
|
1726
1176
|
}
|
|
1727
|
-
const profile = await loadProfileLenient(memory.
|
|
1177
|
+
const profile = await loadProfileLenient(memory.present ? memory.use : undefined, userKey);
|
|
1728
1178
|
if (!profile || profile.facts.length === 0) {
|
|
1729
1179
|
return JSON.stringify({ ok: true, userKey, found: false, message: '该用户暂无档案数据。' });
|
|
1730
1180
|
}
|
|
1731
|
-
const
|
|
1732
|
-
const label = isSelf ? userKey.slice(SELF_KEY_PREFIX.length) || getCurrentPersonaName() : userKey;
|
|
1733
|
-
const factsBlock = renderProfileBlock(profile.facts, label, false);
|
|
1181
|
+
const factsBlock = renderProfileBlock(profile.facts, userKey, false);
|
|
1734
1182
|
const relationLine = renderRelationLine(profile);
|
|
1735
1183
|
const result = {
|
|
1736
1184
|
ok: true,
|
|
1737
1185
|
userKey,
|
|
1738
1186
|
found: true,
|
|
1739
|
-
isSelf,
|
|
1740
1187
|
factCount: profile.facts.length,
|
|
1741
1188
|
relationScore: profile.relationScore ?? 0,
|
|
1742
1189
|
interactionCount: profile.interactionCount ?? 0,
|
|
@@ -1752,12 +1199,12 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1752
1199
|
// /profile 查看自己的档案
|
|
1753
1200
|
// /profile clear 清除自己的档案(authority=2,自己删自己的)
|
|
1754
1201
|
// /profile clear nuke 清空所有用户档案(authority=3,dangerous)
|
|
1755
|
-
commands.command('profile', '查看你在 Aalis 中的事实档案').action(async (argv) => {
|
|
1202
|
+
commands.use.command('profile', '查看你在 Aalis 中的事实档案').action(async (argv) => {
|
|
1756
1203
|
const userId = argv.session.userId;
|
|
1757
1204
|
if (!userId)
|
|
1758
1205
|
return '当前会话未识别用户身份,无法查看档案。';
|
|
1759
1206
|
const userKey = userKeyOf(argv.session.platform, userId);
|
|
1760
|
-
const profile = await loadProfileLenient(memory.
|
|
1207
|
+
const profile = await loadProfileLenient(memory.present ? memory.use : undefined, userKey);
|
|
1761
1208
|
if (!profile || profile.facts.length === 0) {
|
|
1762
1209
|
return `📭 暂无档案数据 (${userKey})`;
|
|
1763
1210
|
}
|
|
@@ -1765,19 +1212,18 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1765
1212
|
const meta = `关系强度:${(profile.relationScore ?? 0).toFixed(relationScorePrecision)}/100,互动次数:${profile.interactionCount ?? 0}`;
|
|
1766
1213
|
return `📇 你的档案 (${userKey})\n${meta}\n\n${block}`;
|
|
1767
1214
|
});
|
|
1768
|
-
commands.command('profile.clear', '清除你自己的事实档案', { visibility: 'restricted' }).action(async (argv) => {
|
|
1215
|
+
commands.use.command('profile.clear', '清除你自己的事实档案', { visibility: 'restricted' }).action(async (argv) => {
|
|
1769
1216
|
const userId = argv.session.userId;
|
|
1770
1217
|
if (!userId)
|
|
1771
1218
|
return '当前会话未识别用户身份,无法清除档案。';
|
|
1772
1219
|
const userKey = userKeyOf(argv.session.platform, userId);
|
|
1773
|
-
const mem =
|
|
1774
|
-
if (!mem)
|
|
1775
|
-
return '记忆服务不支持档案删除。';
|
|
1220
|
+
const mem = pinnedMemory();
|
|
1776
1221
|
try {
|
|
1777
1222
|
const existed = await mem.getMetadata(PROFILE_NS, userKey);
|
|
1778
1223
|
if (!existed)
|
|
1779
1224
|
return `📭 你当前没有档案数据 (${userKey})`;
|
|
1780
1225
|
await mem.deleteMetadata(PROFILE_NS, userKey);
|
|
1226
|
+
page.invalidate();
|
|
1781
1227
|
return `✅ 已清除你的档案 (${userKey})`;
|
|
1782
1228
|
}
|
|
1783
1229
|
catch (err) {
|
|
@@ -1786,10 +1232,10 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1786
1232
|
}
|
|
1787
1233
|
});
|
|
1788
1234
|
// 定点除毒入口(2026-08 群主档案投毒事件的运维刚需):此前删单条事实只能
|
|
1789
|
-
// mongosh 手术或 nuke 全清。dangerous → 等级 2 + confirm,与同族
|
|
1790
|
-
//(它改的是**他人**档案,且 target 含冒号时直传 key
|
|
1791
|
-
//
|
|
1792
|
-
commands
|
|
1235
|
+
// mongosh 手术或 nuke 全清。dangerous → 等级 2 + confirm,与同族 nuke 对齐
|
|
1236
|
+
//(它改的是**他人**档案,且 target 含冒号时直传 key、可触及任意一份档案)。
|
|
1237
|
+
// id 未命中时列出前若干条供定位。
|
|
1238
|
+
commands.use
|
|
1793
1239
|
.command('profile.forget <target:string> <factId:string>', '定点删除某用户档案中的一条事实(运维除毒)', {
|
|
1794
1240
|
risk: 'dangerous',
|
|
1795
1241
|
})
|
|
@@ -1797,7 +1243,7 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1797
1243
|
const target = String(targetArg ?? '');
|
|
1798
1244
|
const factId = String(factIdArg ?? '');
|
|
1799
1245
|
const userKey = target.includes(':') ? target : userKeyOf(argv.session.platform, target);
|
|
1800
|
-
const mem = memory.
|
|
1246
|
+
const mem = memory.list().find(p => p.selected)?.use;
|
|
1801
1247
|
try {
|
|
1802
1248
|
const profile = await loadProfile(mem, userKey);
|
|
1803
1249
|
if (!profile || profile.facts.length === 0)
|
|
@@ -1815,41 +1261,18 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1815
1261
|
facts: profile.facts.filter(f => f.id !== factId),
|
|
1816
1262
|
updatedAt: Date.now(),
|
|
1817
1263
|
});
|
|
1264
|
+
page.invalidate();
|
|
1818
1265
|
return `✅ 已删除 ${userKey} 的事实 [${factId}]:${hit.text.slice(0, 60)}`;
|
|
1819
1266
|
}
|
|
1820
1267
|
catch (err) {
|
|
1821
1268
|
return `❌ 删除失败:${err instanceof Error ? err.message : String(err)}`;
|
|
1822
1269
|
}
|
|
1823
1270
|
});
|
|
1824
|
-
commands.command('profile.
|
|
1825
|
-
const
|
|
1826
|
-
const profile = await loadProfileLenient(memory.current, selfKey);
|
|
1827
|
-
if (!profile || profile.facts.length === 0) {
|
|
1828
|
-
return `🌱 ${getCurrentPersonaName()} 还没有积累任何自反思事实。(key=${selfKey})`;
|
|
1829
|
-
}
|
|
1830
|
-
const block = renderProfileBlock(profile.facts, getCurrentPersonaName(), false);
|
|
1831
|
-
return `🪞 ${getCurrentPersonaName()} 自档案(共 ${profile.facts.length} 条,key=${selfKey})\n\n${block}`;
|
|
1832
|
-
});
|
|
1833
|
-
commands.command('profile.self.clear', '【慎用】清空 Aalis 自档案', { risk: 'dangerous' }).action(async () => {
|
|
1834
|
-
const mem = memory.current;
|
|
1835
|
-
if (!mem)
|
|
1836
|
-
return '记忆服务不支持档案删除。';
|
|
1837
|
-
const selfKey = getSelfKey();
|
|
1271
|
+
commands.use.command('profile.clear.nuke', '【危险】清空所有用户档案', { risk: 'dangerous' }).action(async () => {
|
|
1272
|
+
const mem = pinnedMemory();
|
|
1838
1273
|
try {
|
|
1839
|
-
await mem
|
|
1840
|
-
|
|
1841
|
-
}
|
|
1842
|
-
catch (err) {
|
|
1843
|
-
return `❌ 清空失败:${err instanceof Error ? err.message : String(err)}`;
|
|
1844
|
-
}
|
|
1845
|
-
});
|
|
1846
|
-
commands.command('profile.clear.nuke', '【危险】清空所有用户档案', { risk: 'dangerous' }).action(async () => {
|
|
1847
|
-
const mem = memory.current;
|
|
1848
|
-
if (!mem) {
|
|
1849
|
-
return '记忆服务不支持档案批量删除。';
|
|
1850
|
-
}
|
|
1851
|
-
try {
|
|
1852
|
-
const [keys] = await clearMetadataNamespaces(mem, [PROFILE_NS], logger);
|
|
1274
|
+
const [keys] = await clearMetadataNamespaces(mem, [PROFILE_NS], logger.use);
|
|
1275
|
+
page.invalidate();
|
|
1853
1276
|
return `✅ 已清空全部用户档案(${keys.length} 条)`;
|
|
1854
1277
|
}
|
|
1855
1278
|
catch (err) {
|
|
@@ -1857,105 +1280,8 @@ function registerUserProfile({ memory, llm, events, hooks, contributions, config
|
|
|
1857
1280
|
return `❌ 清空失败:${m}`;
|
|
1858
1281
|
}
|
|
1859
1282
|
});
|
|
1860
|
-
|
|
1861
|
-
// /instruct 查看当前 persona 的所有指令
|
|
1862
|
-
// /instruct.add <text> 手动添加一条指令(authority=2)
|
|
1863
|
-
// /instruct.remove <id> 按 id 删除一条(authority=2)
|
|
1864
|
-
// /instruct.clear 清空当前 persona 的全部指令(authority=3, dangerous)
|
|
1865
|
-
commands.command('instruct', '查看当前 persona 的第三方行为指令').action(async () => {
|
|
1866
|
-
if (!cfg.enableInstructions)
|
|
1867
|
-
return '🚫 第三方行为指令功能未启用。';
|
|
1868
|
-
const personaName = getCurrentPersonaName();
|
|
1869
|
-
const doc = await loadInstructionsLenient(memory.current);
|
|
1870
|
-
if (doc.instructions.length === 0) {
|
|
1871
|
-
return `📭 ${personaName} 当前没有任何第三方行为指令。`;
|
|
1872
|
-
}
|
|
1873
|
-
const lines = doc.instructions.map(ins => {
|
|
1874
|
-
const tag = ins.severity === 'must' ? '【必须】' : ins.severity === 'avoid' ? '【避免】' : '【应当】';
|
|
1875
|
-
const cat = ins.category ? `[${ins.category}]` : '';
|
|
1876
|
-
const src = ins.sourceUserName
|
|
1877
|
-
? `(来自 ${ins.sourceUserName}${ins.sourceChannel === 'command' ? '·手动' : '·LLM'})`
|
|
1878
|
-
: '';
|
|
1879
|
-
return ` ${ins.id} ${tag}${cat} ${ins.text}${src}`;
|
|
1880
|
-
});
|
|
1881
|
-
return `📋 ${personaName} 的第三方行为指令(共 ${doc.instructions.length} 条)\n${lines.join('\n')}`;
|
|
1882
|
-
});
|
|
1883
|
-
commands
|
|
1884
|
-
.command('instruct.add <text:text>', '手动添加一条第三方行为指令', { visibility: 'restricted' })
|
|
1885
|
-
.action(async (argv, text) => {
|
|
1886
|
-
if (!cfg.enableInstructions)
|
|
1887
|
-
return '🚫 第三方行为指令功能未启用。';
|
|
1888
|
-
const body = typeof text === 'string' ? text.trim() : '';
|
|
1889
|
-
if (!body)
|
|
1890
|
-
return '❌ 指令内容不能为空。';
|
|
1891
|
-
const userId = argv.session.userId;
|
|
1892
|
-
const sourceUserKey = userId ? userKeyOf(argv.session.platform, userId) : undefined;
|
|
1893
|
-
const sourceUserName = userId ?? '匿名';
|
|
1894
|
-
const mem = memory.current;
|
|
1895
|
-
try {
|
|
1896
|
-
const doc = await loadInstructions(mem);
|
|
1897
|
-
const merged = mergeInstructions(doc.instructions, [
|
|
1898
|
-
{
|
|
1899
|
-
text: body,
|
|
1900
|
-
severity: 'should',
|
|
1901
|
-
sourceUserKey,
|
|
1902
|
-
sourceUserName,
|
|
1903
|
-
sourceChannel: 'command',
|
|
1904
|
-
},
|
|
1905
|
-
], [], []);
|
|
1906
|
-
await saveInstructions(mem, { instructions: merged, updatedAt: Date.now() });
|
|
1907
|
-
const added = merged.find(m => m.text === clipInstructionText(body));
|
|
1908
|
-
return `✅ 已添加行为指令${added ? `(id=${added.id})` : ''}:${clipInstructionText(body)}`;
|
|
1909
|
-
}
|
|
1910
|
-
catch (err) {
|
|
1911
|
-
return `❌ 添加失败:${err instanceof Error ? err.message : String(err)}`;
|
|
1912
|
-
}
|
|
1913
|
-
});
|
|
1914
|
-
commands
|
|
1915
|
-
.command('instruct.remove <id:string>', '按 id 删除一条第三方行为指令', { visibility: 'restricted' })
|
|
1916
|
-
.action(async (_argv, id) => {
|
|
1917
|
-
if (!cfg.enableInstructions)
|
|
1918
|
-
return '🚫 第三方行为指令功能未启用。';
|
|
1919
|
-
const targetId = typeof id === 'string' ? id.trim() : '';
|
|
1920
|
-
if (!targetId)
|
|
1921
|
-
return '❌ 需要提供指令 id。';
|
|
1922
|
-
const mem = memory.current;
|
|
1923
|
-
try {
|
|
1924
|
-
const doc = await loadInstructions(mem);
|
|
1925
|
-
const target = doc.instructions.find(i => i.id === targetId);
|
|
1926
|
-
if (!target)
|
|
1927
|
-
return `❌ 未找到 id=${targetId} 的指令。`;
|
|
1928
|
-
const merged = mergeInstructions(doc.instructions, [], [], [targetId]);
|
|
1929
|
-
await saveInstructions(mem, { instructions: merged, updatedAt: Date.now() });
|
|
1930
|
-
return `✅ 已删除指令(id=${targetId}):${target.text}`;
|
|
1931
|
-
}
|
|
1932
|
-
catch (err) {
|
|
1933
|
-
return `❌ 删除失败:${err instanceof Error ? err.message : String(err)}`;
|
|
1934
|
-
}
|
|
1935
|
-
});
|
|
1936
|
-
commands
|
|
1937
|
-
.command('instruct.clear', '【危险】清空当前 persona 的全部第三方行为指令', {
|
|
1938
|
-
visibility: 'restricted',
|
|
1939
|
-
})
|
|
1940
|
-
.action(async () => {
|
|
1941
|
-
if (!cfg.enableInstructions)
|
|
1942
|
-
return '🚫 第三方行为指令功能未启用。';
|
|
1943
|
-
const mem = memory.current;
|
|
1944
|
-
if (!mem)
|
|
1945
|
-
return '记忆服务不支持指令删除。';
|
|
1946
|
-
try {
|
|
1947
|
-
const before = (await loadInstructionsLenient(mem)).instructions.length;
|
|
1948
|
-
await mem.deleteMetadata(INSTRUCTIONS_NS, getInstructionsKey());
|
|
1949
|
-
return `✅ ${getCurrentPersonaName()} 的第三方行为指令已清空(删除 ${before} 条)。`;
|
|
1950
|
-
}
|
|
1951
|
-
catch (err) {
|
|
1952
|
-
return `❌ 清空失败:${err instanceof Error ? err.message : String(err)}`;
|
|
1953
|
-
}
|
|
1954
|
-
});
|
|
1955
|
-
logger.info(`用户事实档案已启用 (every=${cfg.extractEveryNMessages <= 0 ? '禁用提取' : `${cfg.extractEveryNMessages}msgs`}, history=${cfg.historyForExtraction}, ` +
|
|
1283
|
+
logger.use.info(`用户事实档案已启用 (every=${cfg.extractEveryNMessages <= 0 ? '禁用提取' : `${cfg.extractEveryNMessages}msgs`}, history=${cfg.historyForExtraction}, ` +
|
|
1956
1284
|
`maxFacts=${cfg.maxFactsPerUser}, ` +
|
|
1957
|
-
`self=${cfg.enableSelfProfile ? `every ${cfg.selfReflectEveryNMessages}msgs/max ${cfg.maxSelfFacts}, key=${getSelfKey()}` : 'disabled'}, ` +
|
|
1958
|
-
`instructions=${cfg.enableInstructions ? `enabled(every ${cfg.instructionExtractEveryNMessages}msgs/max ${cfg.maxInstructions}/minAuth ${cfg.instructionMinAuthority}, key=${getInstructionsKey()})` : 'disabled'}, ` +
|
|
1959
1285
|
`namespace=${PROFILE_NS})`);
|
|
1960
1286
|
}
|
|
1961
1287
|
//# sourceMappingURL=index.js.map
|