用户画像(跨会话、按登录用户隔离,只记称谓/行业/偏好三字段):新建/清空会话时把画像渲染文本+现取的近期关注(最近5条会话标题,不入库)冻结进sessions.profile_snapshot,buildMessages以system后首条user恒定注入(不入messages表故阶段归档/压缩免疫,字节恒定不破前缀缓存);唯一更新时机enterExecuting落槌——advising轮历史+当前画像+任务书快照喂一次模型调用(templates/profile-prompt.txt锁三字段JSON全量覆写语义:未提及原值拷回、被纠正才改写/清空),服务端按字段覆写、漏字段/解析失败保旧值,fire-and-forget永不抛出;user_profiles表(user主键,data JSON,enabled开关);/api/profile读写按req.user隔离,账户设置页新增用户画像子页(可见可改可停用,停用即清现存快照且不再提取);auth未启用=空串键隐式单用户
This commit is contained in:
@@ -113,6 +113,16 @@ function initDb(dbPath) {
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
-- 用户画像(user-profile.js):一行一个登录用户,跨会话共享;未启用认证时为空串键的隐式单用户。
|
||||
-- data = {honorific,industry,preference} JSON(只记「不知道就会做错」的信息,封闭 schema);
|
||||
-- enabled 用户级开关:关 = 新会话不冻结注入快照、也不再提取更新。
|
||||
CREATE TABLE IF NOT EXISTS user_profiles (
|
||||
user TEXT PRIMARY KEY,
|
||||
data TEXT NOT NULL DEFAULT '{}',
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_files_session ON files(session_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_model_usage_model_time ON model_usage(model_id, created_at);
|
||||
@@ -149,6 +159,9 @@ function initDb(dbPath) {
|
||||
if (!cols.some(c => c.name === 'profile')) {
|
||||
db.exec("ALTER TABLE sessions ADD COLUMN profile TEXT DEFAULT ''");
|
||||
}
|
||||
// 迁移:profile_snapshot 存会话创建/清空时冻结的用户画像注入文本(buildMessages 每轮首条 user 注入,
|
||||
// 字节恒定不破坏前缀缓存;不入 messages 表,阶段切换/压缩动不到它,见 user-profile.js)。
|
||||
if (!cols.some(c => c.name === 'profile_snapshot')) db.exec("ALTER TABLE sessions ADD COLUMN profile_snapshot TEXT DEFAULT ''");
|
||||
// 迁移:phase 语义重定义为 advising(顾问:澄清需求/规划)/ executing(执行)。
|
||||
// 存量会话(旧值 planning/NULL)统一回填 executing——它们都有历史,行为与改造前一致、零打扰;
|
||||
// 只有新建会话进 advising(createSession 显式写入)。幂等,每次启动一条廉价 UPDATE。
|
||||
|
||||
@@ -7,6 +7,7 @@ const { executeTool, resolveInTask } = require('./tools/executor');
|
||||
const publicFiles = require('./public-files');
|
||||
const mcp = require('./mcp');
|
||||
const log = require('./log');
|
||||
const profile = require('./user-profile');
|
||||
|
||||
const TOOL_DEFINITIONS = require('./tools/definitions.json');
|
||||
|
||||
@@ -305,6 +306,8 @@ function enterExecuting(sessionId) {
|
||||
return;
|
||||
}
|
||||
if (!snapshot.trim()) return; // 空任务书不构成承诺,继续留在顾问模式
|
||||
// 画像提取的输入:归档前的 advising 轮全量历史(归档后就拿不到了,先抓引用)
|
||||
const adviceRows = loadHistory(sessionId);
|
||||
const n = db.prepare(
|
||||
"UPDATE messages SET type = 'archived' WHERE session_id = ? AND (type IS NULL OR type != 'archived')"
|
||||
).run(sessionId).changes;
|
||||
@@ -318,6 +321,8 @@ function enterExecuting(sessionId) {
|
||||
bus.emit(sessionId, 'phase', { phase: 'executing' });
|
||||
emitStatus(sessionId);
|
||||
log.info('engine', sessionId + ' advising → executing:task.md 落地,存档 ' + n + ' 条消息,上下文重建为任务书快照');
|
||||
// 用户画像唯一更新时机:一轮需求尘埃落定时异步提取(fire-and-forget,永不抛出,见 user-profile.js)
|
||||
profile.runExtraction(db, cfg, { sessionId, user: session.user, modelId: session.model_id, historyRows: adviceRows, briefText: snapshot });
|
||||
}
|
||||
|
||||
// 清空即回 advising:上一轮任务书 mv 进 .task-history/(带时间戳名,撞名再加 -N,同上传风格),
|
||||
@@ -993,6 +998,7 @@ function createSession(title, preferModelId, assistantType, user) {
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, title, status, phase, model_id, assistant_type, user, created_at, updated_at) VALUES (?,?,'queued','advising',NULL,?,?,?,?)"
|
||||
).run(id, title || '', assistantType || 'secretary', user || '', now(), now());
|
||||
profile.freezeSnapshot(db, id); // 冻结画像快照:仅创建/清空时点注入,会话内恒定(见 user-profile.js)
|
||||
// 新会话一律落 advising(顾问模式):先聊天判意图,任务书 task.md 落地才转 executing(见 enterExecuting)
|
||||
// 指定了模型且其平台恰好有空闲 key → 直接绑定,跳过排队;否则回退到 FIFO 队列
|
||||
const prefer = preferModelId && platformModels(platformOf(preferModelId)).includes(preferModelId)
|
||||
@@ -1228,6 +1234,7 @@ function clearSessionMessages(sessionId) {
|
||||
// 标题随历史一并清零:旧标题描述的是已删除的对话,留着会让新对话文不对题;
|
||||
// 新一轮交互结束后 maybeGenerateTitle 见 title 为空会自动重新生成。
|
||||
touch(sessionId, { status: 'completed', completed_at: now(), cancelled_at: null, held_at: null, title: null, phase: 'advising' });
|
||||
profile.freezeSnapshot(db, sessionId); // 回 advising 重新规划:画像快照随新一轮重新冻结
|
||||
bus.emit(sessionId, 'done', { status: 'completed' });
|
||||
bus.emit(sessionId, 'title', { title: null }); // 供其他打开同一会话的窗口同步清掉旧标题
|
||||
bus.emit(sessionId, 'phase', { phase: 'advising' });
|
||||
|
||||
+34
-1
@@ -16,6 +16,11 @@ const COMPRESS_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates
|
||||
// 末尾追加一条 user(本模板,{{language}} 占位符替换为配置语言),见 titleMessages。
|
||||
const TITLE_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'title-prompt.txt'), 'utf8');
|
||||
|
||||
// 用户画像提取提示词(templates/profile-prompt.txt):advising→executing 落槌(enterExecuting)时触发一次。
|
||||
// 与 titleMessages 同构:advising 轮历史 + 末条 user(任务书快照 + 本模板,{{language}} 替换为配置语言),
|
||||
// 见 profileMessages;拼装后的回合不传 tools,只收一段 JSON(解析/合并在 user-profile.js)。
|
||||
const PROFILE_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'profile-prompt.txt'), 'utf8');
|
||||
|
||||
// 拼标题回合的 messages:历史原样(只留 user/assistant 纯文本行)+ 末尾一条标题指令 user。
|
||||
// 与 buildMessages 同取舍:archived 行不进;__blocks__ 哨兵 JSON 还原为文字,图片以 [图片] 占位;
|
||||
// 含 tool_calls 的 assistant 行无文本内容则跳过,tool 回执行整体跳过(只要对话主干)。
|
||||
@@ -35,6 +40,30 @@ function titleMessages(history, language) {
|
||||
return messages;
|
||||
}
|
||||
|
||||
// 拼画像提取回合的 messages(同 titleMessages 的取行口径):历史主干 + 末条 user
|
||||
//(当前画像 + 任务书快照截 4000 字 + 本模板)。当前画像随证据一起给到,提取按全量覆写输出
|
||||
//(见 profile-prompt.txt);画像文本的渲染在 user-profile.js,此处只拼接。
|
||||
function profileMessages(history, language, currentProfileText, briefText) {
|
||||
const messages = [];
|
||||
for (const row of history || []) {
|
||||
if (row.type === 'archived') continue;
|
||||
if (row.role !== 'user' && row.role !== 'assistant') continue;
|
||||
let content = row.content || '';
|
||||
const blocks = decodeBlocks(content);
|
||||
if (blocks) content = blocks.map(b => (b && b.type === 'text' ? b.text : '[图片]')).join('\n');
|
||||
if (!content.trim()) continue;
|
||||
messages.push({ role: row.role, content });
|
||||
}
|
||||
const lang = String(language || '').trim() || 'the same language as the conversation';
|
||||
const brief = String(briefText || '').slice(0, 4000);
|
||||
messages.push({
|
||||
role: 'user',
|
||||
content: '【Current profile】\n' + String(currentProfileText || '').trim() +
|
||||
'\n\n【Task brief】\n' + brief + '\n\n' + PROFILE_PROMPT_TEMPLATE.replaceAll('{{language}}', () => lang),
|
||||
});
|
||||
return messages;
|
||||
}
|
||||
|
||||
// system prompt 进程内恒定(利于上游前缀缓存)。多套并存:默认模板 + 每套 model_profiles
|
||||
// 的自定义 prompt(文本随配置加载时读入,见 config.js normalizeModelProfiles,经
|
||||
// setProfilePrompts 注册)。请求时按 profile 名选取——纯内存指针选择,零 IO。
|
||||
@@ -144,6 +173,10 @@ function cachedDecodeBlocks(session, row) {
|
||||
// 空 = 默认全量组合。
|
||||
function buildMessages(session, language, mintUrl, profile) {
|
||||
const messages = [{ role: 'system', content: systemPromptText(language, profile) }];
|
||||
// 用户画像快照(sessions.profile_snapshot,建会话/清空时冻结,见 user-profile.js):
|
||||
// 作为 system 后首条 user 注入,会话内字节恒定不破坏前缀缓存;
|
||||
// 刻意不落 messages 表:阶段切换归档、压缩摘要都只动 messages 表,碰不到它。
|
||||
if (session.profile_snapshot) messages.push({ role: 'user', content: session.profile_snapshot });
|
||||
const history = session.history;
|
||||
// 行被删除后清理残留的图片解析缓存条目(只增不清会缓慢泄漏;条数不会超过现存行数)
|
||||
if (session.blocksCache && session.blocksCache.size > history.length) {
|
||||
@@ -490,4 +523,4 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
||||
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted, sseFrames };
|
||||
}
|
||||
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages };
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages, profileMessages };
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
* GET /api/models | GET /api/platforms/balance 模型·模型池与余额
|
||||
* GET/POST/PUT/DELETE /api/skills[/:name][/file|/upload|/rename] 技能·技能与文件管理
|
||||
* GET /api/me | POST /api/password | GET /logout 账户·信息/改密/退出
|
||||
* GET/PUT /api/profile 账户·用户画像(可见/可改/可关)
|
||||
*
|
||||
* 后端已有但 v2 尚未接入 UI 的接口(先列出,不实现):
|
||||
* PATCH /api/sessions/:id 重命名(后端已支持)
|
||||
|
||||
@@ -250,6 +250,7 @@
|
||||
const ctx = () => tok === setTok && setTop() === p; // 异步回包时页面可能已切走
|
||||
if (p === 'home') return setPageHome(ctx);
|
||||
if (p === 'account') return setPageAccount(ctx);
|
||||
if (p === 'profile') return setPageProfile(ctx);
|
||||
if (p === 'service') return setPageService(ctx);
|
||||
if (p === 'cfg-editor') return setPageCfgEditor(ctx);
|
||||
if (p === 'skills') return setPageSkills(ctx);
|
||||
@@ -272,7 +273,7 @@
|
||||
|
||||
// ---------- 页:设置主页(卡片入口) ----------
|
||||
const SET_CARDS = [
|
||||
{ go: 'account', name: '账户', desc: '修改密码 · 退出登录',
|
||||
{ go: 'account', name: '账户', desc: '修改密码 · 用户画像 · 退出登录',
|
||||
icon: '<svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"></circle><path d="M4 21c0-4 4-6 8-6s8 2 8 6"></path></svg>' },
|
||||
{ go: 'service', name: '服务', desc: '服务状态 · 系统配置',
|
||||
icon: '<svg class="ic" viewBox="0 0 24 24"><line x1="4" y1="21" x2="4" y2="14"></line><line x1="4" y1="10" x2="4" y2="3"></line><line x1="12" y1="21" x2="12" y2="12"></line><line x1="12" y1="8" x2="12" y2="3"></line><line x1="20" y1="21" x2="20" y2="16"></line><line x1="20" y1="12" x2="20" y2="3"></line><line x1="1" y1="14" x2="7" y2="14"></line><line x1="9" y1="8" x2="15" y2="8"></line><line x1="17" y1="16" x2="23" y2="16"></line></svg>' },
|
||||
@@ -353,7 +354,12 @@
|
||||
setBody('<div class="set-scroll"><div class="empty-tip">未启用登录认证,无账户设置。</div></div>');
|
||||
return;
|
||||
}
|
||||
setBody('<div class="set-scroll">' + userCardHtml(me.user) + '</div>');
|
||||
setBody('<div class="set-scroll">' + userCardHtml(me.user) +
|
||||
'<button class="set-card" data-go="profile"><span class="set-ico">' +
|
||||
'<svg class="ic" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"></rect><circle cx="8" cy="11" r="2"></circle><path d="M5.5 16.5c0-1.8 1.2-2.8 2.5-2.8s2.5 1 2.5 2.8"></path><line x1="14" y1="10" x2="18" y2="10"></line><line x1="14" y1="14" x2="18" y2="14"></line></svg>' +
|
||||
'</span><span class="set-tt"><span class="set-name">用户画像</span><span class="set-desc">称谓 · 行业 · 偏好 · 开关</span></span>' +
|
||||
'<svg class="ic sm set-arrow" viewBox="0 0 24 24"><polyline points="9 6 15 12 9 18"></polyline></svg></button>' +
|
||||
'</div>');
|
||||
}
|
||||
async function changePassword() {
|
||||
try {
|
||||
@@ -364,6 +370,39 @@
|
||||
toast('密码已修改,立即生效');
|
||||
} catch (e) { toast('修改失败:' + e.message); }
|
||||
}
|
||||
// ---------- 页:用户画像(三字段 + 总开关;「近期关注」注入时现取会话标题,不展示不维护) ----------
|
||||
const PROFILE_FIELDS = [
|
||||
['honorific', '称谓', '希望被怎么称呼'],
|
||||
['industry', '行业', '影响术语与默认假设'],
|
||||
['preference', '偏好', '语言 / 交付格式等输出要求'],
|
||||
];
|
||||
async function setPageProfile(ctx) {
|
||||
setTitle('用户画像');
|
||||
setActions('');
|
||||
setBody('<div class="set-scroll"><div class="empty-tip">加载中…</div></div>');
|
||||
let p;
|
||||
try { p = await req('GET', '/api/profile'); }
|
||||
catch (e) { if (ctx()) setBody('<div class="set-scroll"><div class="empty-tip">加载失败:' + esc(e.message) + '</div></div>'); return; }
|
||||
if (!ctx()) return;
|
||||
let html = '<div class="set-scroll"><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] of PROFILE_FIELDS) {
|
||||
const v = String(p[k] || '');
|
||||
html += '<div class="cfg-kv"><label>' + esc(name) + '</label>' +
|
||||
'<input class="cfg-input" id="prof-' + k + '" type="text" maxlength="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">画像只记「不知道就会做错」的信息,新会话开始时作为背景注入(会话内不更新;清空字段保存即抹除)。' +
|
||||
'停用后不再注入也不再更新,重新启用仅对新会话/清空后的会话生效。近期关注(最近会话标题)自动带入背景,无需维护。</div></div></div>';
|
||||
setBody(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(); }
|
||||
try { await req('PUT', '/api/profile', body); toast('已保存,新会话生效'); }
|
||||
catch (e) { toast('保存失败:' + e.message); }
|
||||
}
|
||||
|
||||
// ---------- 页:服务(服务状态 + 系统配置;搬自 settings.js) ----------
|
||||
const CFG_FORM = [
|
||||
@@ -1399,6 +1438,7 @@
|
||||
window.sUI = {
|
||||
// 账户
|
||||
changePassword: changePassword,
|
||||
saveProfile: saveProfile,
|
||||
logout: async function () {
|
||||
sessionStorage.removeItem('agent_creds'); // 旧版本遗留的 Basic 凭据,顺带清理
|
||||
localStorage.removeItem('agent_token'); // 清 autoRestore token,防止自动恢复旧用户
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// 用户画像 API(账户设置 → 用户画像):读写均按登录用户隔离(req.user 由认证中间件挂上,
|
||||
// 不信客户端传的 user)。未启用认证时 req.user 为空 = 空串键的隐式单用户(与 sessions.user 同语义)。
|
||||
const express = require('express');
|
||||
const engine = require('../engine');
|
||||
const profile = require('../user-profile');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const user = String(req.user || '');
|
||||
res.json(Object.assign({ user }, profile.getProfile(engine.getDb(), user)));
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: String(err && err.message || err) });
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/', (req, res) => {
|
||||
try {
|
||||
const db = engine.getDb();
|
||||
const user = String(req.user || '');
|
||||
const patch = profile.sanitizePatch(req.body);
|
||||
profile.saveProfile(db, user, patch);
|
||||
// 停用画像时顺带清掉现存会话的快照(本会话内即不再注入;重新启用只影响新会话/清空后的会话)
|
||||
if (patch.enabled === false) {
|
||||
db.prepare("UPDATE sessions SET profile_snapshot = '' WHERE user = ? AND profile_snapshot != ''").run(user);
|
||||
}
|
||||
res.json({ ok: true, profile: profile.getProfile(db, user) });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: String(err && err.message || err) });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -51,6 +51,8 @@ app.use('/api/skills', require('./routes/skills'));
|
||||
app.use('/api/config', require('./routes/config'));
|
||||
app.use('/api/platforms', require('./routes/platforms'));
|
||||
app.use('/api/system', require('./routes/system'));
|
||||
// 用户画像(账户设置):读写按登录用户隔离,逻辑在 user-profile.js
|
||||
app.use('/api/profile', require('./routes/profile'));
|
||||
// data-page 技能配套:任务 app/ 子树页面向导 /app/{task_id}/ + 数据 API /api/db/{task_id}/query。
|
||||
// 随其余业务路由一样挂在 auth.middleware 之后(登录态才能访问)。
|
||||
app.use(require('./routes/data-page'));
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
You maintain a minimal profile of the current user. The 【Current profile】 block in the last message is the stored state; your evidence is the planning conversation above plus the task brief appended with it.
|
||||
Respond with JSON only — exactly {"honorific": "", "industry": "", "preference": ""}, no markdown fences, no prose. Output all three fields: this is a full-state update, not a diff.
|
||||
- Carry every current value through UNCHANGED unless the conversation clearly replaces it or shows it is wrong; put "" only to clear a field the conversation invalidates (or one that is already empty). Never drop or rewrite a value on weak evidence.
|
||||
- New non-empty values require clear evidence in the conversation; never guess, never infer personality, never record secrets or ID numbers.
|
||||
- honorific: how the user wants to be addressed.
|
||||
- industry: the user's industry/domain.
|
||||
- preference: durable output preferences (reply language, delivery format, style) that would change the deliverable if unknown.
|
||||
Write each non-empty value in {{language}}, at most 40 characters.
|
||||
@@ -0,0 +1,139 @@
|
||||
// 用户画像:一行一个登录用户(user_profiles 表),跨会话共享、按登录用户隔离;
|
||||
// 未启用认证时即空串键的隐式单用户,功能不变。
|
||||
//
|
||||
// 设计原则(「只记不知道就会做错的信息」):
|
||||
// - 存储封闭三字段 honorific/industry/preference;「近期关注」不入库,
|
||||
// 仅在快照冻结时从该用户最近会话标题现取现拼,UI 不展示也不编辑。
|
||||
// - 注入:会话创建/清空时把渲染文本冻结进 sessions.profile_snapshot,
|
||||
// buildMessages 每轮以 system 后首条 user 消息注入——内容字节恒定不破坏前缀缓存,
|
||||
// 且不落 messages 表,阶段切换归档/压缩都动不到它。
|
||||
// - 更新:唯一提取时机是 enterExecuting(任务书落地、advising 轮尘埃落定),一次廉价模型调用;
|
||||
// 当前画像随证据一起喂给模型,要求按【全量覆写】输出(见 profile-prompt.txt):没提的字段
|
||||
// 原值拄回,明确被纠正的才改写/清空。服务端按字段覆写(空串 = 清),模型漏输出/解析失败的
|
||||
// 字段保留旧值;不中途写、不定时投递写。
|
||||
const { profileMessages, callModel } = require('./llm');
|
||||
const log = require('./log');
|
||||
|
||||
const FIELDS = ['honorific', 'industry', 'preference'];
|
||||
const MAX_FIELD = 80; // 字段长度帽:防模型把画像写成小作文
|
||||
const RECENT_TITLES = 5;
|
||||
const SNAPSHOT_HEAD = '【用户画像 · 背景参考】以下为历史会话沉淀的粗粒度认知,非任务约束;与当前请求冲突时,一律以当前请求为准。';
|
||||
const FIELD_LABELS = { honorific: '称谓', industry: '行业', preference: '偏好' };
|
||||
|
||||
function readRow(db, user) {
|
||||
return db.prepare('SELECT data, enabled FROM user_profiles WHERE user = ?').get(String(user || ''));
|
||||
}
|
||||
function readData(row) {
|
||||
try { const d = JSON.parse((row && row.data) || '{}'); return d && typeof d === 'object' ? d : {}; }
|
||||
catch (_) { return {}; }
|
||||
}
|
||||
|
||||
function getProfile(db, user) {
|
||||
const row = readRow(db, user);
|
||||
const data = readData(row);
|
||||
const out = { enabled: row ? !!row.enabled : true }; // 无行 = 默认启用(首次保存/提取前即此语义)
|
||||
for (const k of FIELDS) out[k] = typeof data[k] === 'string' ? data[k] : '';
|
||||
return out;
|
||||
}
|
||||
|
||||
function writeRow(db, user, data, enabled) {
|
||||
db.prepare(`
|
||||
INSERT INTO user_profiles (user, data, enabled, updated_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(user) DO UPDATE SET data = excluded.data, enabled = excluded.enabled, updated_at = excluded.updated_at
|
||||
`).run(String(user || ''), JSON.stringify(data), enabled ? 1 : 0, Date.now());
|
||||
}
|
||||
|
||||
// UI PUT 入参规范化:只认白名单键;字符串压空白 + 截断;enabled 仅认显式布尔/0/1(缺省 = 不改)。
|
||||
function sanitizePatch(body) {
|
||||
const b = body && typeof body === 'object' ? 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, MAX_FIELD);
|
||||
}
|
||||
if (typeof b.enabled === 'boolean' || b.enabled === 0 || b.enabled === 1) patch.enabled = !!b.enabled;
|
||||
return patch;
|
||||
}
|
||||
|
||||
// 用户手动保存:字段照写(空串 = 清空,尊重显式操作)。
|
||||
function saveProfile(db, user, patch) {
|
||||
const row = readRow(db, user);
|
||||
const data = readData(row);
|
||||
for (const k of FIELDS) if (typeof patch.fields[k] === 'string') data[k] = patch.fields[k];
|
||||
const enabled = patch.enabled === undefined ? (row ? !!row.enabled : true) : patch.enabled;
|
||||
writeRow(db, user, data, enabled);
|
||||
}
|
||||
|
||||
// 提取结果应用:全量覆写——parseExtraction 只收录了模型确实返回的字符串字段,
|
||||
// 其中空串 = 按对话证据清除;未返回的字段(漏输出/胡输出)不收录,保留旧值。
|
||||
// 返回实际变化的字段名(无变化不写库、不刷 updated_at)。
|
||||
function mergeExtraction(db, user, parsed) {
|
||||
const row = readRow(db, user);
|
||||
const data = readData(row);
|
||||
const changed = [];
|
||||
for (const k of FIELDS) {
|
||||
const v = parsed[k]; // undefined = 模型没给这个字段 → 不动;'' = 显式清除
|
||||
if (typeof v === 'string' && v !== (typeof data[k] === 'string' ? data[k] : '')) { data[k] = v; changed.push(k); }
|
||||
}
|
||||
if (changed.length) writeRow(db, user, data, row ? !!row.enabled : true);
|
||||
return changed;
|
||||
}
|
||||
|
||||
// 提取回合喂给模型的【Current profile】文本:三键定序,空值渲染 (empty)。
|
||||
function profileForExtraction(p) {
|
||||
return FIELDS.map(k => k + ' = ' + (p[k] ? JSON.stringify(p[k]) : '(empty)')).join('\n');
|
||||
}
|
||||
|
||||
// 渲染注入文本:三字段(非空才成行)+ 现取的近期关注;停用或全空 → 空串(不注入)。
|
||||
function snapshotText(db, user, excludeSessionId) {
|
||||
const p = getProfile(db, user);
|
||||
if (!p.enabled) return '';
|
||||
const lines = [];
|
||||
for (const k of FIELDS) if (p[k]) lines.push('- ' + FIELD_LABELS[k] + ':' + p[k]);
|
||||
const titles = db.prepare(
|
||||
"SELECT title FROM sessions WHERE user = ? AND id != ? AND title IS NOT NULL AND title != '' ORDER BY updated_at DESC LIMIT " + RECENT_TITLES
|
||||
).all(String(user || ''), String(excludeSessionId || '')).map(r => r.title);
|
||||
if (titles.length) lines.push('- 近期关注:' + titles.join(';'));
|
||||
return lines.length ? SNAPSHOT_HEAD + '\n' + lines.join('\n') : '';
|
||||
}
|
||||
|
||||
// 会话创建/清空时冻结画像快照。失败静默(大不了这轮不注入,不影响建会话/清空主流程)。
|
||||
function freezeSnapshot(db, sessionId) {
|
||||
try {
|
||||
const s = db.prepare('SELECT user FROM sessions WHERE id = ?').get(sessionId);
|
||||
if (!s) return;
|
||||
db.prepare('UPDATE sessions SET profile_snapshot = ? WHERE id = ?').run(snapshotText(db, s.user, sessionId), sessionId);
|
||||
} catch (e) { log.warn('profile', '画像快照冻结失败(忽略):' + (e && e.message || e)); }
|
||||
}
|
||||
|
||||
// 提取输出解析:剥 ``` 围栏、JSON.parse、只取白名单字段(同样截断)。解析失败返回 null。
|
||||
function parseExtraction(content) {
|
||||
let text = String(content || '').trim();
|
||||
const fence = /^```[a-zA-Z]*\r?\n?([\s\S]*?)\r?\n?```$/.exec(text);
|
||||
if (fence) text = fence[1].trim();
|
||||
if (!text.startsWith('{')) { const m = /\{[\s\S]*\}/.exec(text); if (m) text = m[0]; }
|
||||
let obj;
|
||||
try { obj = JSON.parse(text); } catch (_) { return null; }
|
||||
if (!obj || typeof obj !== 'object') return null;
|
||||
const out = {};
|
||||
for (const k of FIELDS) if (typeof obj[k] === 'string') out[k] = obj[k].replace(/\s+/g, ' ').trim().slice(0, MAX_FIELD);
|
||||
return out;
|
||||
}
|
||||
|
||||
// advising→executing 落槌处调用的一次提取更新:fire-and-forget,永不抛出。
|
||||
// 不传 key_slot:旁路调用回落到该模型首个 key 副本,避免与在跑的回合抢同一槽限流(失败本就静默)。
|
||||
async function runExtraction(db, cfg, ctx) {
|
||||
try {
|
||||
const { sessionId, user, modelId, historyRows, briefText } = ctx || {};
|
||||
const p = getProfile(db, user);
|
||||
if (!modelId || !p.enabled) return;
|
||||
if (!(historyRows || []).length || !String(briefText || '').trim()) return;
|
||||
const msgs = profileMessages(historyRows, (cfg.agent || {}).language, profileForExtraction(p), briefText);
|
||||
const r = await callModel(cfg, modelId, msgs, null, {});
|
||||
const parsed = parseExtraction(r && r.content);
|
||||
if (!parsed) { log.debug('profile', '提取输出不可解析,忽略:' + sessionId); return; }
|
||||
const changed = mergeExtraction(db, user, parsed);
|
||||
log.info('profile', '画像' + (changed.length ? '更新 ' + (user || '-') + ':' + changed.join(',') : '无变化') + ' ←' + sessionId);
|
||||
} catch (e) { log.warn('profile', '画像提取失败(忽略):' + (e && e.message || e)); }
|
||||
}
|
||||
|
||||
module.exports = { getProfile, sanitizePatch, saveProfile, snapshotText, freezeSnapshot, runExtraction };
|
||||
@@ -60,7 +60,8 @@ agent/
|
||||
│ │ │ ├── system-prompt.txt system prompt 静态模板(每次请求复用,利于上游前缀缓存)
|
||||
│ │ │ ├── advising-system.txt 顾问阶段提示词(内置 profile:advising,phase=advising 时强制命中,见 §4.1)
|
||||
│ │ │ ├── compress-prompt.txt 上下文压缩提示词(压缩回合末尾追加为 user 消息,历史照常走 messages)
|
||||
│ │ │ └── title-prompt.txt 会话标题自动生成提示词(首次交互结束后触发,{{language}} 填配置语言)
|
||||
│ │ │ ├── title-prompt.txt 会话标题自动生成提示词(首次交互结束后触发,{{language}} 填配置语言)
|
||||
│ │ │ └── profile-prompt.txt 用户画像提取提示词(advising→executing 落槌时触发一次,输出锁三字段 JSON,见 user-profile.js)
|
||||
│ │ └── public/ 前端 H5 SPA(无构建,Vanilla JS 经典脚本多文件 + SSE)
|
||||
│ │ ├── index.html 主页(HTML+样式;脚本全部在 js/,按序加载共享全局作用域)
|
||||
│ │ ├── login.html 登录页
|
||||
@@ -447,6 +448,7 @@ AI 通过 `schedule` 工具为所在会话建周期性任务(`scheduled_tasks`
|
||||
| `/api/config` | `routes/config.js` | `GET /` 原文+生效(脱敏)、`POST /validate`、`PUT /` 整文件保存、`PATCH /` 单项修改(path/value/op[delete\|append]) |
|
||||
| `/api/platforms` | `routes/platforms.js` | `GET /balance?pi=&ki=` 余额 |
|
||||
| `/api/system` | `routes/system.js` | `GET /status` + `/restart?force=...`(原 `model_profiles` 可用名单字段已删,前端无消费方) |
|
||||
| `/api/profile` | `routes/profile.js` | `GET /` 读画像、`PUT /` 保存(三字段 + enabled);按 `req.user` 隔离,逻辑全在 `user-profile.js`(快照冻结见 engine `createSession`/`clearSessionMessages`,提取见 `enterExecuting`) |
|
||||
| `/api/models` | `server.js` | 空闲/占用模型池 + token 用量 |
|
||||
| `/api/health` | `server.js` | 健康检查 |
|
||||
| `/api/login` `/api/login_restore` `/api/logout` `/api/password` `/api/me` | `auth.js` | 认证路由(认证前) |
|
||||
|
||||
Reference in New Issue
Block a user