feat(profile): 偏好改多行原样文本(PREF_MAX 1000);移除 AI 侧 profile 工具

This commit is contained in:
2026-11-20 09:28:02 +08:00
parent 2f0b056a63
commit 02c154ae24
5 changed files with 54 additions and 166 deletions
+10
View File
@@ -1539,6 +1539,16 @@ label.icon-btn { cursor: pointer; }
.cfg-input:focus { border-color: var(--active); background: var(--bg-fff); }
.cfg-input::-webkit-outer-spin-button, .cfg-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
.cfg-input.cfg-dirty { color: var(--fg-c0392b); border-color: var(--bd-e8b4b0); background: var(--bg-fdf3f2); }
/* 多行条目输入(如画像偏好):标签在上、输入框占整行,便于一行一条 */
.cfg-kv.stack { flex-direction: column; align-items: stretch; gap: 6px; }
.cfg-kv.stack label { max-width: none; }
.cfg-textarea {
width: 100%; min-height: 96px; box-sizing: border-box; resize: vertical;
font-size: 13px; line-height: 1.7; color: var(--ink); font-family: inherit;
text-align: left; background: var(--surface); border: 1px solid transparent;
border-radius: 8px; padding: 8px 10px; -webkit-appearance: none; appearance: none;
}
.cfg-textarea:focus { border-color: var(--active); background: var(--bg-fff); outline: none; }
.cfg-err {
margin: 0 0 8px; padding: 8px 12px; border-radius: 8px;
background: var(--bg-fdecea); color: var(--fg-a3352a); font-size: 12.5px;
+33 -6
View File
@@ -362,29 +362,55 @@
} catch (e) { toast('修改失败:' + e.message); }
}
// ---------- 页:账户——用户画像编辑卡直接渲染在账户页(无二级页;保存后 renderSetPage 重拉刷新停用徽标) ----------
const PREF_MAX = 1000; // 与后端 user-profile.js 的 PREF_MAX 对齐
const PROFILE_FIELDS = [
['honorific', '称谓', '希望被怎么称呼', 80],
['industry', '行业', '影响术语与默认假设', 80],
['preference', '偏好', '顿号分隔标签(AI 会在沟通中自动补充,可手动增删)', 300],
['preference', '偏好', '一行一条', 0, 'textarea'],
];
function prefCountText(n) {
return '已用 ' + n + ' / ' + PREF_MAX + ' 字' + (n > PREF_MAX ? ',超出部分保存时截断' : '');
}
function prefCount() {
const el = $('prof-preference'), out = $('prof-count-preference');
if (!el || !out) return;
const n = el.value.trim().length;
out.textContent = prefCountText(n);
out.style.color = n > PREF_MAX ? 'var(--fg-c0392b)' : '';
}
function profileCardHtml(p) {
let html = '<div class="settings-card"><h4>用户画像' +
(p.enabled === false ? ' <span class="badge held">已停用</span>' : '') + '</h4>' +
'<div class="cfg-kv"><label>启用</label><input type="checkbox" id="prof-enabled"' + (p.enabled === false ? '' : ' checked') + '></div>';
for (const [k, name, ph, maxLen] of PROFILE_FIELDS) {
for (const [k, name, ph, maxLen, kind] of PROFILE_FIELDS) {
const v = String(p[k] || '');
if (kind === 'textarea') {
// 用户输入什么就存什么、注入什么:不拆不拼、不规范化分隔符,换行原样保留
html += '<div class="cfg-kv stack"><label>' + esc(name) + '</label>' +
'<textarea class="cfg-textarea" id="prof-' + k + '" rows="8" placeholder="' + esc(ph) + '" oninput="sUI.prefCount()">' + esc(v) + '</textarea>' +
'<div class="cfg-note" id="prof-count-' + k + '">' + prefCountText(v.length) + '</div></div>';
} else {
html += '<div class="cfg-kv"><label>' + esc(name) + '</label>' +
'<input class="cfg-input" id="prof-' + k + '" type="text" maxlength="' + (maxLen || 80) + '" data-orig="' + att(v) + '" value="' + att(v) + '" placeholder="' + esc(ph) + '"></div>';
}
}
html += '<button class="primary-btn" style="margin-top:8px" onclick="sUI.saveProfile()">保存</button>' +
'<div class="cfg-note">画像只记「不知道就会做错」的信息,新会话开始时作为背景注入(会话内不更新;清空字段保存即抹除)。' +
'AI 会在沟通中持续维护(尤其偏好标签,只记明确表达过的,写入自下个会话生效),这里手动改随时可覆盖。' +
'停用后不再注入,AI 的记录请求也会被拒。近期关注(最近会话标题)自动带入背景,无需维护。</div></div>';
'<div class="cfg-note">新会话生效</div></div>';
return html;
}
async function saveProfile() {
const body = { enabled: $('prof-enabled').checked };
for (const [k] of PROFILE_FIELDS) { const el = $('prof-' + k); if (el) body[k] = el.value.trim(); }
for (const [k, , , , kind] of PROFILE_FIELDS) {
const el = $('prof-' + k);
if (!el) continue;
const v = el.value.trim();
if (kind === 'textarea' && v.length > PREF_MAX) {
body[k] = v.slice(0, PREF_MAX);
toast('偏好超过 ' + PREF_MAX + ' 字,已截断保存');
} else {
body[k] = v;
}
}
try { await req('PUT', '/api/profile', body); toast('已保存,新会话生效'); renderSetPage(); }
catch (e) { toast('保存失败:' + e.message); }
}
@@ -1998,6 +2024,7 @@
// 账户
changePassword: changePassword,
saveProfile: saveProfile,
prefCount: prefCount,
// 用户管理(仅管理员)
openUserAdd: openUserAdd,
openUserEdit: openUserEditor,
-40
View File
@@ -198,46 +198,6 @@
}
}
},
{
"type": "function",
"function": {
"name": "profile",
"description": "Maintain the current user's profile — stable facts that persist across conversations and get injected into the context of NEW sessions (the current session's injected copy is frozen). Ops: list (read the live profile), set (honorific or industry, single short value), add (append preference tags), remove (delete exact preference tags). Rules: only record what the user has clearly stated or asked to be remembered (form of address, domain, stable output/work preferences); never guess personality, never store one-time task parameters; brief tags beat essays. Preference is a 、-separated tag list (each tag ≤15 chars, ≤24 tags, ≤300 chars total; overflow is rejected — consolidate or remove first). When unsure what is already recorded, op=list returns live state — trust it over memory.",
"parameters": {
"type": "object",
"required": [
"op"
],
"properties": {
"op": {
"type": "string",
"enum": [
"list",
"set",
"add",
"remove"
],
"description": "list = read live profile; set = single-value honorific/industry; add/remove = preference tags."
},
"honorific": {
"type": "string",
"description": "op=set: how to address the user (≤20 chars, e.g. 王工). Pass empty string to clear. Exactly one of honorific/industry per call."
},
"industry": {
"type": "string",
"description": "op=set: the user's industry/domain (≤20 chars, e.g. 金融). Pass empty string to clear."
},
"tags": {
"type": "array",
"items": {
"type": "string"
},
"description": "op=add/remove: preference tag list, e.g. [\"偏好简洁回复\", \"图表中文标注\"]. Matching is exact text."
}
}
}
}
},
{
"type": "function",
"function": {
-35
View File
@@ -15,7 +15,6 @@ const devices = require('../devices'); // device 工具:远端执行节点(
const log = require('../log'); // device 工具调用日志(info 记动作+设备+耗时+命令截断)
const publicFiles = require('../public-files');
const scheduler = require('../scheduler'); // 只依赖 log/cron-parser/time.js,不成环(engine→executor→scheduler 单向)
const profile = require('../user-profile'); // profile 工具的数据面(仅 llm/log 依赖,无环)
const memory = require('../memory'); // recall 工具的数据面(日记翻阅;仅依赖 time.js,无环)
// lab 的 help 伪工具要读全量定义:与 engine 同路径 require → node 缓存同一对象,单一事实源。
const BUILTIN_TOOL_DEFS = require('./definitions.json');
@@ -1458,39 +1457,6 @@ function toolScheduleTask(ctx, args) {
}
}
// profile:用户画像增量维护(op 分派同 schedule 风格)。user 取自会话行,AI 不可指定他人;
// 条件必填/帽子校验全在 user-profile.js(抛错由引擎包成 is_error 回执),停用拒写不拒读。
function toolProfile(ctx, args) {
const op = String(args.op || '').trim().toLowerCase();
const s = ctx.db.prepare('SELECT user FROM sessions WHERE id = ?').get(ctx.sessionId);
if (!s) throw new Error('会话不存在');
const user = s.user;
switch (op) {
case 'list': {
const p = profile.getProfile(ctx.db, user);
const lines = [
'称谓:' + (p.honorific || '(未记录)'),
'行业:' + (p.industry || '(未记录)'),
'偏好:' + (p.preference || '(未记录)'),
];
if (!p.enabled) lines.push('(该用户已停用画像注入;set/add/remove 会被拒绝)');
lines.push('本会话已注入的快照不会因写入而变;新会话自动携带最新画像。');
return lines.join('\n');
}
case 'set': {
const keys = ['honorific', 'industry'].filter(k => typeof args[k] === 'string');
if (keys.length !== 1) throw new Error('op=set 需要 honorific 或 industry 恰一个字符串参数(偏好标签用 add/remove)');
return profile.setProfileField(ctx.db, user, keys[0], args[keys[0]]);
}
case 'add':
return profile.addProfileTags(ctx.db, user, args.tags);
case 'remove':
return profile.removeProfileTags(ctx.db, user, args.tags);
default:
throw new Error('未知的 op:"' + op + '"。可用:list / set(honorific|industry) / add(tags) / remove(tags)');
}
}
// db:会话本地 SQLite(taskDir/data.db,随会话目录隔离,首次使用自动建库建文件)。
// 连接策略:每次调用 open→用→close,不缓存句柄(会话删目录后不留脏连接);
// 单进程 + better-sqlite3 同步 API,同进程内不存在交叠。busy_timeout 兼容
@@ -1898,7 +1864,6 @@ const HANDLERS = {
terminal: toolTerminal,
fetch: toolFetch,
schedule: toolScheduleTask,
profile: toolProfile,
recall: toolRecall,
db: toolDb,
device: toolDevice,
+9 -83
View File
@@ -7,19 +7,15 @@
// - 注入:会话创建/清空时把渲染文本冻结进 sessions.profile_snapshot,
// buildMessages 每轮以 system 后首条 user 消息注入——内容字节恒定不破坏前缀缓存,
// 且不落 messages 表,阶段切换归档/压缩都动不到它。
// - 更新(原 handoff 落槌一次性提取链路已移除):AI 沟通中经 profile 工具增量维护
// (list/set/add/remove,见 executor.js;写入只影响下个会话——快照冻结语义不变),
// 用户也可在设置页手动编辑。preference 按顿号标签列表管理,工具只做增量增删、
// 不做整段覆写——防模型重写时吃掉旧标签;停用(enabled=0)时拒写不拒读。
// - 更新:只由用户在设置页手动编辑。原 AI 侧的 profile 工具(list/set/add/remove)已移除:
// 模型自主记录容易把错的东西冻结成长期上下文,记什么由用户把关。
// - preference 是用户自由输入的多行文本(一行一条即可):原样入库、原样注入,不拆不拼、
// 不把分隔符规范化;只卡一个总长帽(PREF_MAX)。
const log = require('./log');
const FIELDS = ['honorific', 'industry', 'preference'];
const MAX_FIELD = 80; // honorific/industry 长度帽(Web 手改与工具共用)
const PREF_MAX = 300; // preference 总长帽
const SET_MAX = 20; // AI 写 honorific/industry 的单值帽(称谓应当短小)
const TAG_MAX = 15; // 单个偏好标签长度帽
const TAGS_MAX = 24; // 偏好标签数量帽
const TAG_SPLIT = /[、,,;;\n]+/;
const MAX_FIELD = 80; // honorific/industry 长度帽
const PREF_MAX = 1000; // preference 总长帽(用户自由输入的多行文本,只卡总量)
// 画像快照头:AI 友好的分块标记(与 channel_note/memory_note 同款「# [CTX] <名>」体例,
// buildMessages 把快照作 system 后首条 user 注入,标题即自描述来源)。
const SNAPSHOT_HEAD = '# [CTX] user_profile\n\n以下为历史会话沉淀的粗粒度认知,非任务约束;与当前请求冲突时,一律以当前请求为准。';
@@ -54,7 +50,9 @@ function sanitizePatch(body) {
const patch = { fields: {}, enabled: undefined };
for (const k of FIELDS) {
if (typeof b[k] === 'string') {
patch.fields[k] = b[k].replace(/\s+/g, ' ').trim().slice(0, k === 'preference' ? PREF_MAX : MAX_FIELD);
// preference 是用户按条目输入的自由文本:保留换行,只去首尾空白;另两字段压成单行
const v = k === 'preference' ? b[k].trim() : b[k].replace(/\s+/g, ' ').trim();
patch.fields[k] = v.slice(0, k === 'preference' ? PREF_MAX : MAX_FIELD);
}
}
if (typeof b.enabled === 'boolean' || b.enabled === 0 || b.enabled === 1) patch.enabled = !!b.enabled;
@@ -70,77 +68,6 @@ function saveProfile(db, user, patch) {
writeRow(db, user, data, enabled);
}
// ---------- profile 工具(AI 增量维护入口;op 语义与 executor.js toolProfile 对应) ----------
// preference 存顿号连接的标签串;读取按分隔符拆 token(人工输入的整句会被拆为 token 存留,可接受)。
function profileTokens(preference) {
return String(preference || '').split(TAG_SPLIT).map(t => t.trim()).filter(Boolean);
}
// 所有写 op 的统一后缀:快照「新会话冻结注入」语义不因工具改变,明说免 AI 在本会话里困惑等待。
const WRITE_NOTE = '(新会话开始时注入,本会话内不变;可用 op=list 查看实时状态)';
function requireEnabled(db, user) {
if (!getProfile(db, user).enabled) {
throw new Error('该用户已停用画像(设置页·账户·用户画像可重新启用),本次未写入。');
}
}
// 单值字段(称谓/行业)设置;空串 = 清除。
function setProfileField(db, user, field, value) {
if (!FIELDS.includes(field) || field === 'preference') {
throw new Error('op=set 仅支持 honorific / industry(偏好标签请用 op=add / op=remove)');
}
requireEnabled(db, user);
const v = String(value == null ? '' : value).replace(/\s+/g, ' ').trim().slice(0, SET_MAX);
const cur = getProfile(db, user)[field];
if (cur === v) return FIELD_LABELS[field] + '已是「' + v + '」,未改动。';
saveProfile(db, user, { fields: { [field]: v } });
return v
? FIELD_LABELS[field] + '已设为「' + v + '」' + WRITE_NOTE
: FIELD_LABELS[field] + '已清除(下次冻结时将不再出现)。';
}
// 追加偏好标签:清洗 → 逐条校验长度 → 去重 → 数量/总长帽(整批原子:任一带帽违例则不落库)
function addProfileTags(db, user, tags) {
const list = (Array.isArray(tags) ? tags : [tags])
.map(t => String(t == null ? '' : t).replace(TAG_SPLIT, ' ').replace(/\s+/g, ' ').trim())
.filter(Boolean);
if (!list.length) throw new Error('op=add 需要非空的 tags 字符串数组(单个标签也用数组传)');
requireEnabled(db, user);
const cur = profileTokens(getProfile(db, user).preference);
const added = [], dup = [];
for (const t of list) {
if (t.length > TAG_MAX) throw new Error('标签「' + t + '」超过 ' + TAG_MAX + ' 字上限,请换成更概括的说法');
if (cur.includes(t)) { dup.push(t); continue; }
cur.push(t); added.push(t);
}
if (cur.length > TAGS_MAX) throw new Error('偏好标签已达 ' + TAGS_MAX + ' 个上限(本次将到 ' + cur.length + '),先用 op=remove 合并精简');
const joined = cur.join('、');
if (joined.length > PREF_MAX) throw new Error('偏好总长将超 ' + PREF_MAX + ' 字(现 ' + joined.length + '),先用 op=remove 精简');
if (!added.length) {
return '均已存在,未新增(' + dup.join('、') + ');当前偏好 ' + cur.length + ' 条。';
}
saveProfile(db, user, { fields: { preference: joined } });
return '已记录:' + added.join('、')
+ (dup.length ? '(已存在未重复:' + dup.join('、') + ')' : '')
+ ';偏好现共 ' + cur.length + ' 条' + WRITE_NOTE;
}
// 删除偏好标签:按 token 精确匹配;未命中的回报(引导先 list 核对写法)。
function removeProfileTags(db, user, tags) {
const list = (Array.isArray(tags) ? tags : [tags]).map(t => String(t == null ? '' : t).trim()).filter(Boolean);
if (!list.length) throw new Error('op=remove 需要非空的 tags 字符串数组');
requireEnabled(db, user);
const cur = profileTokens(getProfile(db, user).preference);
const removed = list.filter(t => cur.includes(t));
const missing = list.filter(t => !cur.includes(t));
if (!removed.length) return '未找到要删除的标签:' + missing.join('、') + '(op=list 可查看当前精确标签)';
saveProfile(db, user, { fields: { preference: cur.filter(t => !removed.includes(t)).join('、') } });
return '已移除:' + removed.join('、')
+ (missing.length ? ';未找到:' + missing.join('、') : '')
+ ';偏好现共 ' + (cur.length - removed.length) + ' 条' + WRITE_NOTE;
}
// 渲染注入文本:三字段(非空才成行);停用或全空 → 空串(不注入)。
function snapshotText(db, user) {
const p = getProfile(db, user);
@@ -161,5 +88,4 @@ function freezeSnapshot(db, sessionId) {
module.exports = {
getProfile, sanitizePatch, saveProfile, snapshotText, freezeSnapshot,
setProfileField, addProfileTags, removeProfileTags,
};