diff --git a/app/config.example.yml b/app/config.example.yml
index afada90..7d575e1 100644
--- a/app/config.example.yml
+++ b/app/config.example.yml
@@ -11,8 +11,8 @@ tools_deny: [lab, handoff]
# 模型 profile:prompt + tools 名单组合,模型用 profile: <名> 引用(不配 = 全量)。
# 内置 advising 不靠引用:会话处于 advising 阶段(顾问澄清需求/规划)时强制命中,见 server/engine.js resolveProfileName。
model_profiles:
- advising: # 顾问阶段:只聊和读不写,唯一出口 handoff,配专属提示词
- tools_allow: [read_file, fetch, handoff]
+ advising: # 顾问阶段:只聊和读不写(profile 画像元信息除外),唯一出口 handoff,配专属提示词
+ tools_allow: [read_file, fetch, handoff, profile]
tools_deny: [] # 必须显式清空全局黑名单,否则 handoff 自己也被 deny(同 lab 的教训)
system_prompt_file: advising-system.txt
lab: # 统一入口自测:tools 只有 lab,其余能力经 lab(help) 现场发现
diff --git a/app/server/config.js b/app/server/config.js
index cc3e484..b0b24bd 100644
--- a/app/server/config.js
+++ b/app/server/config.js
@@ -103,9 +103,10 @@ const DEFAULTS = {
model_profiles: {
// advising:顾问阶段(sessions.phase)专用组合——不由模型配置引用,而是 resolveProfileName 在
// advising 时强制命中:顾问只聊和读、不写(write_file 已移除,批内幻觉调用另由引擎挡下),
+ // 例外是 profile(画像元信息,不碰任务目录;顾问问答恰是收集称谓/偏好密度最高的时刻);
// 唯一出口是 handoff;tools_deny 必须显式清空:不配 = 继承全局 ['lab','handoff'],
// allow 滤完再叠 deny 会把 handoff 自己禁掉(同 lab 组合的教训)。
- advising: { tools_allow: ['read_file', 'fetch', 'handoff'], tools_deny: [], system_prompt_file: 'advising-system.txt' },
+ advising: { tools_allow: ['read_file', 'fetch', 'handoff', 'profile'], tools_deny: [], system_prompt_file: 'advising-system.txt' },
// lab:统一入口元工具自测组合——tools 收缩到 1 个,其余能力经 lab(help) 现场发现。
// tools_deny 必须显式清空:不配 = 继承全局 ['lab'],deny 后叠加会把 lab 自己禁掉 → 零工具。
lab: { tools_allow: ['lab'], tools_deny: [], system_prompt_file: 'lab-system.txt' },
diff --git a/app/server/engine.js b/app/server/engine.js
index 76baeb9..8894992 100644
--- a/app/server/engine.js
+++ b/app/server/engine.js
@@ -294,8 +294,6 @@ 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;
@@ -312,8 +310,6 @@ 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,同上传风格),
diff --git a/app/server/llm.js b/app/server/llm.js
index b9bd761..5400c5c 100644
--- a/app/server/llm.js
+++ b/app/server/llm.js
@@ -16,11 +16,6 @@ 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 回执行整体跳过(只要对话主干)。
@@ -40,30 +35,6 @@ 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。
@@ -527,4 +498,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, profileMessages };
+module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages };
diff --git a/app/server/public/js/settings.js b/app/server/public/js/settings.js
index 89fc9f5..2071a3f 100644
--- a/app/server/public/js/settings.js
+++ b/app/server/public/js/settings.js
@@ -366,22 +366,23 @@
}
// ---------- 页:账户——用户画像编辑卡直接渲染在账户页(无二级页;保存后 renderSetPage 重拉刷新停用徽标) ----------
const PROFILE_FIELDS = [
- ['honorific', '称谓', '希望被怎么称呼'],
- ['industry', '行业', '影响术语与默认假设'],
- ['preference', '偏好', '语言 / 交付格式等输出要求'],
+ ['honorific', '称谓', '希望被怎么称呼', 80],
+ ['industry', '行业', '影响术语与默认假设', 80],
+ ['preference', '偏好', '顿号分隔标签(AI 会在沟通中自动补充,可手动增删)', 300],
];
function profileCardHtml(p) {
let html = '
';
}
html += '' +
'画像只记「不知道就会做错」的信息,新会话开始时作为背景注入(会话内不更新;清空字段保存即抹除)。' +
- '停用后不再注入也不再更新,重新启用仅对新会话/清空后的会话生效。近期关注(最近会话标题)自动带入背景,无需维护。
';
+ 'AI 会在沟通中持续维护(尤其偏好标签,只记明确表达过的,写入自下个会话生效),这里手动改随时可覆盖。' +
+ '停用后不再注入,AI 的记录请求也会被拒。近期关注(最近会话标题)自动带入背景,无需维护。';
return html;
}
async function saveProfile() {
diff --git a/app/server/templates/profile-prompt.txt b/app/server/templates/profile-prompt.txt
deleted file mode 100644
index bfc4aed..0000000
--- a/app/server/templates/profile-prompt.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-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.
diff --git a/app/server/tools/definitions.json b/app/server/tools/definitions.json
index daae79a..c3d0447 100644
--- a/app/server/tools/definitions.json
+++ b/app/server/tools/definitions.json
@@ -181,6 +181,23 @@
}
}
},
+ {
+ "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": {
diff --git a/app/server/tools/executor.js b/app/server/tools/executor.js
index 0dbf17a..6332a59 100644
--- a/app/server/tools/executor.js
+++ b/app/server/tools/executor.js
@@ -10,6 +10,7 @@ const Database = require('better-sqlite3'); // db 工具:会话目录下的 da
const rexec = require('../remote-exec');
const publicFiles = require('../public-files');
const scheduler = require('../scheduler'); // 只依赖 log/cron-parser,不成环(engine→executor→scheduler 单向)
+const profile = require('../user-profile'); // profile 工具的数据面(仅 llm/log 依赖,无环)
// lab 的 help 伪工具要读全量定义:与 engine 同路径 require → node 缓存同一对象,单一事实源。
const BUILTIN_TOOL_DEFS = require('./definitions.json');
@@ -803,6 +804,39 @@ 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 兼容
@@ -1160,6 +1194,7 @@ const HANDLERS = {
terminal: toolTerminal,
fetch: toolFetch,
schedule: toolScheduleTask,
+ profile: toolProfile,
db: toolDb,
skill: toolSkill,
lab: toolLab,
diff --git a/app/server/user-profile.js b/app/server/user-profile.js
index 5bbe7bd..ba98a3a 100644
--- a/app/server/user-profile.js
+++ b/app/server/user-profile.js
@@ -7,15 +7,19 @@
// - 注入:会话创建/清空时把渲染文本冻结进 sessions.profile_snapshot,
// buildMessages 每轮以 system 后首条 user 消息注入——内容字节恒定不破坏前缀缓存,
// 且不落 messages 表,阶段切换归档/压缩都动不到它。
-// - 更新:唯一提取时机是 enterExecuting(任务书落地、advising 轮尘埃落定),一次廉价模型调用;
-// 当前画像随证据一起喂给模型,要求按【全量覆写】输出(见 profile-prompt.txt):没提的字段
-// 原值拄回,明确被纠正的才改写/清空。服务端按字段覆写(空串 = 清),模型漏输出/解析失败的
-// 字段保留旧值;不中途写、不定时投递写。
-const { profileMessages, callModel } = require('./llm');
+// - 更新(原 handoff 落槌一次性提取链路已移除):AI 沟通中经 profile 工具增量维护
+// (list/set/add/remove,见 executor.js;写入只影响下个会话——快照冻结语义不变),
+// 用户也可在设置页手动编辑。preference 按顿号标签列表管理,工具只做增量增删、
+// 不做整段覆写——防模型重写时吃掉旧标签;停用(enabled=0)时拒写不拒读。
const log = require('./log');
const FIELDS = ['honorific', 'industry', 'preference'];
-const MAX_FIELD = 80; // 字段长度帽:防模型把画像写成小作文
+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 RECENT_TITLES = 5;
const SNAPSHOT_HEAD = '【用户画像 · 背景参考】以下为历史会话沉淀的粗粒度认知,非任务约束;与当前请求冲突时,一律以当前请求为准。';
const FIELD_LABELS = { honorific: '称谓', industry: '行业', preference: '偏好' };
@@ -31,7 +35,7 @@ function readData(row) {
function getProfile(db, user) {
const row = readRow(db, user);
const data = readData(row);
- const out = { enabled: row ? !!row.enabled : true }; // 无行 = 默认启用(首次保存/提取前即此语义)
+ const out = { enabled: row ? !!row.enabled : true }; // 无行 = 默认启用(首次保存前即此语义)
for (const k of FIELDS) out[k] = typeof data[k] === 'string' ? data[k] : '';
return out;
}
@@ -43,18 +47,20 @@ function writeRow(db, user, data, enabled) {
`).run(String(user || ''), JSON.stringify(data), enabled ? 1 : 0, Date.now());
}
-// UI PUT 入参规范化:只认白名单键;字符串压空白 + 截断;enabled 仅认显式布尔/0/1(缺省 = 不改)。
+// UI PUT 入参规范化:只认白名单键;字符串压空白 + 截断(preference 高帽);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[k] === 'string') {
+ patch.fields[k] = b[k].replace(/\s+/g, ' ').trim().slice(0, k === 'preference' ? PREF_MAX : MAX_FIELD);
+ }
}
if (typeof b.enabled === 'boolean' || b.enabled === 0 || b.enabled === 1) patch.enabled = !!b.enabled;
return patch;
}
-// 用户手动保存:字段照写(空串 = 清空,尊重显式操作)。
+// 落库入口:字段照写(空串 = 清空,尊重显式操作);enabled 缺省保持现状。
function saveProfile(db, user, patch) {
const row = readRow(db, user);
const data = readData(row);
@@ -63,24 +69,75 @@ function saveProfile(db, user, patch) {
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;
+// ---------- profile 工具(AI 增量维护入口;op 语义与 executor.js toolProfile 对应) ----------
+// preference 存顿号连接的标签串;读取按分隔符拆 token(人工输入的整句会被拆为 token 存留,可接受)。
+function profileTokens(preference) {
+ return String(preference || '').split(TAG_SPLIT).map(t => t.trim()).filter(Boolean);
}
-// 提取回合喂给模型的【Current profile】文本:三键定序,空值渲染 (empty)。
-function profileForExtraction(p) {
- return FIELDS.map(k => k + ' = ' + (p[k] ? JSON.stringify(p[k]) : '(empty)')).join('\n');
+// 所有写 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;
}
// 渲染注入文本:三字段(非空才成行)+ 现取的近期关注;停用或全空 → 空串(不注入)。
@@ -105,35 +162,7 @@ function freezeSnapshot(db, 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 };
+module.exports = {
+ getProfile, sanitizePatch, saveProfile, snapshotText, freezeSnapshot,
+ setProfileField, addProfileTags, removeProfileTags,
+};
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 7abf4a0..daf6a26 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -42,7 +42,7 @@ agent/
│ │ ├── balance.js 余额查询适配器(按 platform.type 分发)
│ │ ├── version.js 版本信息(package.json + git 短提交号)
│ │ ├── tools/
-│ │ │ ├── definitions.json 内置 9 个工具的 OpenAI function 格式定义(含元工具 lab)
+│ │ │ ├── definitions.json 内置工具的 OpenAI function 格式定义(现 12 项,含元工具 lab 与全局屏蔽的 handoff)
│ │ │ ├── executor.js 工具执行器(文件类 + terminal + skill 委托)
│ │ │ └── skills.js Skill Manager(skill 工具的 list/get/run + 路径预处理)
│ │ ├── download-token.js 下载链接签名(浏览器原生下载用;密钥进程内随机)
@@ -63,8 +63,7 @@ agent/
│ │ │ ├── system-prompt.txt system prompt 静态模板(每次请求复用,利于上游前缀缓存)
│ │ │ ├── advising-system.txt 顾问阶段提示词(内置 profile:advising,phase=advising 时强制命中,见 §4.1)
│ │ │ ├── compress-prompt.txt 上下文压缩提示词(压缩回合末尾追加为 user 消息,历史照常走 messages)
-│ │ │ ├── title-prompt.txt 会话标题自动生成提示词(首次交互结束后触发,{{language}} 填配置语言)
-│ │ │ └── profile-prompt.txt 用户画像提取提示词(advising→executing 落槌时触发一次,输出锁三字段 JSON,见 user-profile.js)
+│ │ │ └── title-prompt.txt 会话标题自动生成提示词(首次交互结束后触发,{{language}} 填配置语言)
│ │ └── public/ 前端 H5 SPA(无构建,Vanilla JS 经典脚本多文件 + SSE)
│ │ ├── index.html 主页(HTML+样式;脚本全部在 js/,按序加载共享全局作用域)
│ │ ├── login.html 登录页
@@ -251,7 +250,8 @@ stateDiagram-v2
```
- advising(顾问):profile 被 `resolveProfileName` 强制为内置 `advising` 组合(问答/判意图/引导澄清需求),
- 只聊和读不写(`write_file`/`edit_file` 不在其白名单,批内幻觉调用也被 runLoopInner 挡下);
+ 只聊和读不写(`write_file`/`edit_file` 不在其白名单,批内幻觉调用也被 runLoopInner 挡下;例外 `profile`——
+ 画像元信息不碰任务目录,顾问问答恰是收集称谓/偏好密度最高的时刻),
唯一出口是 `handoff` 工具:handler 把 `brief` 原样落盘根 `task.md`(reason ∈ ready/user_skip/user_stuck,
空 brief 拒回不切);`handoff` 与 `lab` 同入全局 `tools_deny`,advising 组合显式 `tools_deny: []` 独享可见。
- executing(执行):回到常规 profile 链路(模型配置 > 默认全量);单会话只解决一个问题,一路走到底,回头路只有「清空」。
@@ -328,7 +328,7 @@ stateDiagram-v2
- session 补偿:MCP 规范的 `Mcp-Session-Id` 缓存在 `server.sessionId`;过期(400 + 含 "session" 字样)自动重 initialize 后重试一次。
- 某些老服务无 `initialize` → catch `Method not found` 不阻断。
-### 5.4 `tools/executor.js` —— 内置 9 工具(含元工具 `lab`)的派发器
+### 5.4 `tools/executor.js` —— 内置工具(现 12 项,含元工具 `lab`)的派发器
`HANDLERS` 是 `name → async(ctx, args) → result` 的表;`executeTool(ctx, name, args)` 按 `name` 派发;**未知名直接转发给 MCP**(若 `mcp.hasTool(name)`,调 `mcp.callTool`)。
@@ -336,12 +336,13 @@ stateDiagram-v2
|---|---|
| `read_file` | 走 `resolveInTask` 防路径穿越;图像(PNG/JPEG/WebP/GIF/BMP/TIFF)按 vision 能力走 `sharp` 压缩后落盘 `.imgcache/` 并回传 `image_rel`(长边 ≤ 2000px,JPEG q=80;文件名带源文件 mtime+size 指纹,重读复用不增殖;重编码无收益时不落盘、直指原文件),发送前由 `llm.buildMessages` 现签成公网外链(engine 侧 mint 前 realpath 复核);大文本/二进制给 outline,超 32MB 拒读并引导 terminal;行号前缀格式 "`<6位右对齐行号>\\t<原文>`"(`edit_file` 用) |
| `write_file` / `edit_file` | `edit_file` 用模糊定位(Zed 风格):先精确匹配,失败后用 Levenshtein DP 找最相似行;超 32MB 拒绝整文件读写(OOM 防护);DP 候选区间不连续(中间跳过无关 buffer 行)即弃用,防静默吞行;空 `new_text` = 整行干净删除(精确/模糊两层统一,对齐 `"".lines()` 零行语义);`old_text`/`new_text` 协议见 `definitions.json` |
-| 已移除的工具 | `list_directory` / `create_directory` / `delete_path` / `move_path` / `copy_path` / `find_path` / `grep`:环境固定,文件操作与检索统一走 `terminal`(ls / mkdir / rm / mv / cp / find / rg),内置工具 17 → 10;技能三件套又并为 `skill` 后为 8;再增元工具 `lab` 为 9(默认被全局 `tools_deny` 屏蔽) |
+| 已移除的工具 | `list_directory` / `create_directory` / `delete_path` / `move_path` / `copy_path` / `find_path` / `grep`:环境固定,文件操作与检索统一走 `terminal`(ls / mkdir / rm / mv / cp / find / rg),内置工具 17 → 10;技能三件套又并为 `skill` 后为 8;再增元工具 `lab` 为 9(默认被全局 `tools_deny` 屏蔽);后续增 `db`、`profile` 各一 → 现 12 项 |
| `terminal` | **唯一一个走 executor 的内置工具**(当 `rexec.isRemote(cfg)`);本地分支用 `spawn` + `detached` + 进程组 kill;远端分支 `rexec.run` SSE 收流,结果套上超时/截断/取消注解后 `truncate(text, cfg.terminal.max_output_chars)` 返回 |
| `fetch` | `AbortController` 覆盖全生命周期(响应头之后的 body 读流同样被超时/取消打断,取消用与 terminal 同款的 200ms 轮询);content-type 先行,非文本只回状态/类型/尺寸不读 body;流式读到 `cfg.fetch.max_bytes`(默认 1MB)即断开并标注截断;按响应 charset 解码(full-icu 支持 gbk/gb18030 等,未知编码退回 UTF-8);HTML 用 `htmlToMarkdown` 转;HTML 实体单遍解码(常见命名实体+数字实体通吃,修 `&` 双重解码);网络错误解包 `err.cause` 直述 ENOTFOUND/TLS 等真因;engine 不截工具结果,返回值末尾另有 `truncate` 1MB 字符护栏 |
| `mint_public_link` | **唯一的 mint 入口**:与 core 同进程,直接 `publicFiles.mint()`,不绕任何 HTTP;`ctx.taskDir` 就是会话目录,`relOf` 的结果正是取用侧要的 `rel`。校验:`public_link.base_url` 已配 + `resolveInTask` 沙箱 + 确认是文件 + `realpath` 未沿符号链接跳出任务目录;返回单行 URL |
| `skill` | op 分派 list/get/run(三件套合并:同一 `name` 标识空间 + 同一生命周期,见 `docs/tool-design.md` §一);委托 `tools/skills.js`;`input_args` 仅 op=run 且可缺省 `{}`,缺参由各技能 `input_schema` 校验点名报错;front matter 带 `visit_url` 的技能在 op=run 成功后由 executor 层拼 `public_link.base_url`(与 mint 同源)追加完整「访问地址」行(技能进程不知公网前缀,AI 拿相对路径会原样转给用户) |
| `schedule` | **当前会话**(`ctx.sessionId`,AI 不可指定他会话)定时任务的完整生命周期:op 分派 get/create/update/delete(表主键 session_id → 每会话至多一条,无 id 参数);条件必填在代码里校验、错误回显 op 与缺失字段;数据层在 `scheduler.js`(cron 可解析 → 间隔 ≥1h → prompt ≤20000 → 查重/存在性检查),delete 不落 scheduler_note;描述里限定「仅用户明确要求时调用」(安全缓解,见 §5.12) |
+| `profile` | 用户画像增量维护(op 分派:list / set(honorific\|industry 单值≤20字,空串清除) / add / remove(preference 顿号标签));user 取自会话行,AI 不可指定他人;护栏单标≤15字×≤24个×总≤300字,整批原子(任一超限不落库);停用(enabled=0)拒写不拒读;写入自新会话生效(快照冻结语义不变),list 永远给 live 状态——取代了原 handoff 落槌一次性提取链路 |
| `lab` | 元工具统一入口:`tool` + 自由 `args` 转发内置 + MCP 全部能力(目标 schema 定义期不可知,条件校验归内层 handler);`help` 伪工具做现场发现(无参列名单、带 `args.tool` 出完整 schema),未知名回显全清单,禁嵌套、内层错误冒泡不包装。默认被全局 `tools_deny: ['lab']` 屏蔽,仅 `lab` profile(allow `[lab]` + deny `[]` 清空)下发,见 §5.8 |
`resolveInTask(taskDir, relOrAbs)`:把相对路径或绝对路径解析为绝对路径并校验落在 `taskDir` 之内(含根),防穿越。
@@ -492,7 +493,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/profile` | `routes/profile.js` | `GET /` 读画像、`PUT /` 保存(三字段 + enabled);按 `req.user` 隔离,逻辑全在 `user-profile.js`(快照冻结见 engine `createSession`/`clearSessionMessages`;日常更新由 AI 经 `profile` 工具增量维护,见 §5.4) |
| `/api/channel` | `routes/channel.js` | `POST /send {channel, text}` 文本命令接入端(IM/CLI 等无 UI 客户端,走 Basic/cookie 鉴权):命令仅在本入口解析(Web 消息路由不受影响,防误伤路径/代码文本);严格匹配白名单 `/new[文本] /stop /compact /clear /status /help`,未知斜杠词回提示、不像命令的当普通消息;(user,channel) 经 `channel_sessions` 表绑定当前会话(普通消息无绑定自动建);命令动作不落消息行(与 Web 按钮对称),AI 回复由接入端复用既有 SSE/详情接口获取;`handleSend()` 另供微信桥接直调 |
| `/api/wechat` | `routes/wechat.js` | 微信绑定管理(设置页,cookie 鉴权 + req.user 隔离):`GET /`(enabled/alive/我的绑定)、`POST /`(新建绑定,一人一绑)、`GET /:id/qr`(登录二维码 SVG 代理)、`POST /:id/refresh`(重发登录)、`DELETE /:id`(解绑,销毁实例与凭证);业务全在 `wechat.js`(§5.13) |
| `/wxhook` | `routes/wechat.js`(hookRouter) | wxbot → core 内网回调(**挂 auth.middleware 与全局 express.json 之前**,自带 32mb 解析器容纳媒体 base64):`POST /inbox {id, from, text, media?}` 文本/媒体转 channel 层——media={kind:image\|video\|file, b64, filename?},core 按 magic 嗅探定扩展名、落会话任务目录(文件保留消毒原名,图/视频生成 wximg-/wxvid- 时间戳名)+ 记 files 表 + 拼「用户上传了文件:<名>」告知行(同 web 附件模式,vision 模型 read_file 即见);非 2xx 时 wxbot 把 error 文案回给微信用户;`POST /hook {id, event}` 实例状态回报;Bearer 共享服务 token(哈希后定长比较,未配一律 503) |