refactor(engine): 全面移除 advising 顾问模式与 handoff 工具——会话默认走模型配置 profile(未配=全量 profile-default.txt)

- engine: resolveProfileName 去掉 advising 强制档;删 enterExecuting/archiveTaskBrief 与 runLoopInner 的阶段守卫、批尾切换逻辑
- tools: definitions.json/executor.js 删 handoff 工具(内置工具 15→14);全局 tools_deny 回退为 ['lab']
- db: sessions.phase 列随概念移除(DROP COLUMN 迁移,旧 SQLite 兜底跳过);createSession/clearSessionMessages 不再读写 phase
- 模板 profile-advising.txt 删除;config.js/config.example.yml 去 advising 组合
- scheduler/wechat 投递前不再有强制 executing;SSE status 事件与会话接口不再携带 phase
- 前端去阶段徽标/phase 事件监听;README 与 docs/ARCHITECTURE.md 同步
This commit is contained in:
2026-10-17 13:00:53 +08:00
parent fe7441c37a
commit fd617b0b8d
19 changed files with 48 additions and 362 deletions
+2 -11
View File
@@ -109,19 +109,10 @@ const DEFAULTS = {
// 模型平台池(无默认值,结构见 config.example.yml)。
platforms: [],
// 全局工具黑名单:profile 未配 tools_deny 时继承它;allow 先、deny 后叠加(deny 赢,与 mcp_servers 同构)。
// 默认屏蔽元工具 lab 与阶段出口 handoff:它们只该出现在显式清空 deny 的 profile 里,
// 不进任何常规请求的 tools 数组(lab → lab 组合;handoff → advising 组合)。
tools_deny: ['lab', 'handoff'],
// 默认屏蔽元工具 lab:它只该出现在显式清空 deny 的 profile 里,不进常规请求的 tools 数组(lab → lab 组合)。
tools_deny: ['lab'],
// 模型 profile(prompt + tools 名单组合):platforms 里的模型用 profile: <名> 引用。
model_profiles: {
// advising:顾问阶段(sessions.phase)专用组合——不由模型配置引用,而是 resolveProfileName 在
// advising 时强制命中:顾问只聊和读、不写(write_file/edit_file/copy_path 不在名单,批内幻觉调用另由引擎挡下;
// list_directory 入选——翻阅历史目录是顾问高频刚需),
// 例外是 profile(画像元信息,不碰任务目录;顾问问答恰是收集称谓/偏好密度最高的时刻)
// 与 recall(日记只读翻阅;用户和顾问聊「上次那个事」恰是回忆查询的高峰场景);
// 唯一出口是 handoff;tools_deny 必须显式清空:不配 = 继承全局 ['lab','handoff'],
// allow 滤完再叠 deny 会把 handoff 自己禁掉(同 lab 组合的教训)。
advising: { tools_allow: ['read_file', 'list_directory', 'fetch', 'handoff', 'profile', 'recall'], tools_deny: [], system_prompt_file: 'profile-advising.txt' },
// lab:统一入口元工具自测组合——tools 收缩到 1 个,其余能力经 lab(help) 现场发现。
// tools_deny 必须显式清空:不配 = 继承全局 ['lab'],deny 后叠加会把 lab 自己禁掉 → 零工具。
lab: { tools_allow: ['lab'], tools_deny: [], system_prompt_file: 'profile-lab.txt' },
+8 -10
View File
@@ -14,7 +14,6 @@ function initDb(dbPath) {
id TEXT PRIMARY KEY,
title TEXT DEFAULT '',
status TEXT NOT NULL,
phase TEXT NOT NULL DEFAULT 'advising',
model_id TEXT,
last_model_id TEXT,
assistant_type TEXT DEFAULT 'secretary',
@@ -218,17 +217,17 @@ function initDb(dbPath) {
if (!cols.some(c => c.name === 'user')) {
db.exec("ALTER TABLE sessions ADD COLUMN user TEXT DEFAULT ''");
}
// 迁移:profile 曾记会话绑定的 prompt+tools 组合名(bind 弹窗「模式」区)。已废弃:
// 前端手动切换模式全部移除,profile 选取收敛为「phase 强制 + 模型配置默认」两档(见 engine.resolveProfileName);
// 升级老库:profile 曾记会话绑定的 prompt+tools 组合名(bind 弹窗「模式」区)。已废弃:
// 前端手动切换模式全部移除,profile 选取只剩模型配置默认一档(见 engine.resolveProfileName);
// 列保留(SQLite 删列不值得),代码不再读写。
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)。
// 字节恒定不破坏前缀缓存;不入 messages 表,压缩动不到它,见 user-profile.js)。
if (!cols.some(c => c.name === 'profile_snapshot')) db.exec("ALTER TABLE sessions ADD COLUMN profile_snapshot TEXT DEFAULT ''");
// 迁移:title_locked 用户手动重命名过标题(renameSession 置 1):handoff 的自动标题见锁即跳过,
// 不得静默冲掉用户给会话起的名字;清空会话时随标题一并复位(旧名字已文不对题)。
// 迁移:title_locked 用户手动重命名过标题(renameSession 置 1):显式留痕「名字是用户起的」,
// 不得静默冲掉;清空会话时随标题一并复位(旧名字已文不对题)。
if (!cols.some(c => c.name === 'title_locked')) db.exec("ALTER TABLE sessions ADD COLUMN title_locked INTEGER NOT NULL DEFAULT 0");
// 迁移:wechat_bindings 补 deep_think 列——微信端全局深度思考开关(routes/channel.js /think 读写,
// 投递时作为既有 deepThink 参数的取值来源);默认 0=关(与 H5 按钮初始态一致,/think on 手动开)。
@@ -259,10 +258,9 @@ function initDb(dbPath) {
`);
})();
}
// 迁移:phase 语义重定义为 advising(顾问:澄清需求/规划)/ executing(执行)。
// 存量会话(旧值 planning/NULL)统一回填 executing——它们都有历史,行为与改造前一致、零打扰;
// 只有新建会话进 advising(createSession 显式写入)。幂等,每次启动一条廉价 UPDATE。
db.exec("UPDATE sessions SET phase='executing' WHERE phase IS NULL OR phase NOT IN ('advising','executing')");
// 迁移:advising(顾问阶段)概念已全部移除,会话不再有 phase 语义;旧列直接删。
// 旧 SQLite 不支持 DROP COLUMN(<3.35)时静默跳过:残留死列无妨,代码已不再读写它。
try { db.exec('ALTER TABLE sessions DROP COLUMN phase'); } catch (_) { /* 旧版本 SQLite,保留死列 */ }
// 迁移(C 重构):memory_entries「一天一行拼 blob」→ memory_fragments「一片一行」。幂等:旧表存在才搬,
// 搬完即 drop;解析不出【sid】头的块(DAY_MAX 时代削出的孤儿残句)直接丢弃;
// 存量碎片的 day 顺手改判为来源会话最后活跃日(事件日语义修正,积压补记自然散布回真实日期)。
+10 -102
View File
@@ -140,7 +140,6 @@ function emitStatus(sessionId) {
bus.emit(sessionId, 'status', {
session_id: sessionId,
status: s.status,
phase: s.phase,
model_id: s.model_id,
});
}
@@ -314,12 +313,10 @@ function registerProfilePrompts() {
setProfilePrompts(map);
}
// 本轮生效的 profile 名(两档):advising 阶段强制命中内置 'advising' 组合(顾问只该看到顾问的工具);
// 否则 = 模型配置默认(cfg.models[].profile)> ''(默认全量)。
// 运行期手动切换已全部移除(消息级 profile 参数、sessions.profile 会话绑定均已废弃),
// 顾问/执行的节奏由 sessions.phase 单一状态机控制,见 enterExecuting / archiveTaskBrief。
// 本轮生效的 profile 名:模型配置默认(cfg.models[].profile)> ''(默认全量,profile-default.txt)。
// 运行期手动切换已全部移除(消息级 profile 参数、sessions.profile 会话绑定均已废弃);
// 原 advising 阶段强制组合已随顾问模式一并移除。
function resolveProfileName(session) {
if (session && session.phase === 'advising') return 'advising';
const m = session && session.model_id && (cfg.models || []).find(x => x.id === session.model_id);
return m && m.profile ? String(m.profile) : '';
}
@@ -345,71 +342,6 @@ function effectiveTools(profileName) {
return out;
}
// ---------- 阶段(sessions.phase:advising 顾问 / executing 执行) ----------
// advising:新建会话与「清空」的落点。profile 被 resolveProfileName 强制为 'advising',
// 只聊和读不写(write_file/edit_file/copy_path 不在其 schema,批内幻觉调用也在 runLoopInner 挡下;
// list_directory 在白名单里——顾问翻阅历史目录正当其用);
// 唯一出口 = handoff 工具成功返回(brief 由 handler 落盘任务目录根 task.md,见 tools/executor.js)。
// executing:一路走到底,只有清空才回 advising;压缩不碰 phase(压完仍回原模式)。
// advising → executing:任务书落地,当场重建上下文——
// 全部历史标 archived(UI 照常展示、不再发模型,与压缩/定时投递同机制),
// 插一条 type='task_brief' 的 user 行(内容 = 此刻 task.md 磁盘快照,非引用:后续文件怎么改都不动锚点)
// 作为执行阶段唯一上下文起点;runLoopInner 下一迭代重读历史 + 重解 profile,天然已在执行态,AI 同回合开工。
// 幂等:phase 已是 executing 直接返回(执行中再改 task.md 只是普通文件编辑,不重存档、不重插快照)。
function enterExecuting(sessionId) {
const session = getSession(sessionId);
if (!session || session.phase !== 'advising') return;
const briefPath = path.join(taskDirOf(sessionId), 'task.md');
let snapshot;
try {
snapshot = fs.readFileSync(briefPath, 'utf8');
} catch (e) {
log.warn('engine', sessionId + ' 阶段切换放弃:读不回 task.md — ' + (e && e.message || e));
return;
}
if (!snapshot.trim()) return; // 空任务书不构成承诺,继续留在顾问模式
const n = db.prepare(
"UPDATE messages SET type = 'archived' WHERE session_id = ? AND (type IS NULL OR type != 'archived')"
).run(sessionId).changes;
saveMessage(sessionId, {
role: 'user', type: 'task_brief',
// 只报「进入执行模式 + 行为约束 + 任务书本体」:task.md/.task-history 是系统内部传递机制,
// 不进模型视野(知道文件名只会引出无谓的读写尝试);Missing 逐项确认段是 user_skip
// 事故(执行者把跳过顾问泛化成跳过确认)的行为约束,不可减。
content: '【任务书】顾问阶段结束,会话已进入执行模式,以下任务书是唯一目标依据;'
+ '之前的顾问对话已存档、不再发送。若任务书列有 Missing/待确认事项:开工前逐项向用户提问并等待答复——'
+ '用户跳过的只是顾问阶段,不是确认环节,不得据此自行拍板;只有用户明确说过「别问,直接做」才可用默认值,且须把每个默认决定列出供用户检查;禁止把待确认项改写成「按默认执行」。\n\n' + snapshot,
});
db.prepare("UPDATE sessions SET phase='executing', updated_at=? WHERE id=?").run(now(), sessionId);
bus.emit(sessionId, 'phase', { phase: 'executing' });
emitStatus(sessionId);
log.info('engine', sessionId + ' advising → executing:task.md 落地,存档 ' + n + ' 条消息,上下文重建为任务书快照');
}
// 清空即回 advising:上一轮任务书 mv 进 .task-history/(带时间戳名,撞名再加 -N,同上传风格),
// 防旧约定污染新一轮规划。点前缀目录在文件列表默认隐藏(同 .imgcache 约定),AI/用户显式请求可查;
// 同步清掉 files 元数据表的 task.md 行(列表读磁盘不读表,清行只为不留孤儿记录)。
function archiveTaskBrief(sessionId) {
try {
const dir = taskDirOf(sessionId);
const src = path.join(dir, 'task.md');
if (!fs.existsSync(src)) return;
const hist = path.join(dir, '.task-history');
fs.mkdirSync(hist, { recursive: true });
const d = new Date();
const pad = x => String(x).padStart(2, '0');
const stamp = d.getFullYear() + pad(d.getMonth() + 1) + pad(d.getDate()) + '-' + pad(d.getHours()) + pad(d.getMinutes()) + pad(d.getSeconds());
let dest = path.join(hist, 'task-' + stamp + '.md');
for (let i = 1; fs.existsSync(dest); i++) dest = path.join(hist, 'task-' + stamp + '-' + i + '.md');
fs.renameSync(src, dest);
db.prepare("DELETE FROM files WHERE session_id = ? AND filename = 'task.md'").run(sessionId);
log.info('task', sessionId + ' 旧任务书归档 → ' + path.relative(dir, dest));
} catch (e) {
log.warn('task', sessionId + ' 旧任务书归档失败:' + (e && e.message || e));
}
}
// ---------- 绑定 ----------
// 写入绑定:会话粘住自己的 key+模型(断开/结版/终止不清,跨重启沿用,追问免选),
// 并刷新槽位 last_used_at(「最久未用先上」的轮转依据)。model_id 同时用于展示/统计。
@@ -567,7 +499,7 @@ function finalize(sessionId, run) {
// 连环「嗯」不算有效对话;不满足等下个 finalize 再判。
// 不带 system prompt:历史 user/assistant 原文(注入行不进,白名单见 llm.titleMessages)+
// 末尾一条标题指令 user,用会话当前 model_id 发一次不传 tools 的调用。
// 失败静默(title 仍空,下个回合结束自动重试);handoff 时顾问自写的标题占位后不再覆盖。
// 失败静默(title 仍空,下个回合结束自动重试);已有标题(建会话时填写或手动重命名)不再覆盖。
// force=true(仅收口兑底 wrapTitleFallback 传):跳过 n/chars 现推门槛无条件立题——
// 收口是最后一站,没有下个回合了,差一点的标题也比永远无名强;其余守卫(非空即跳/防重入/
// 清空校验)不受 force 影响,finalize 路径不传维持原门槛。
@@ -804,7 +736,6 @@ async function runLoopInner(sessionId, run) {
// 执行工具
const vision = modelVision(session);
let handoffDone = false; // 本批工具里是否有 handoff 成功返回(批量跑完统一切换,见循环尾注释)
// 标题门槛信号:本批参数预检通过并真实执行 = 会话在干实事(finalize 据此判是否立题,
// 见 maybeGenerateTitle);errAck 批(参数畸形、下轮整轮对模型不可见)不算。
if (!isErrAck) run.toolWorked = true;
@@ -821,12 +752,6 @@ async function runLoopInner(sessionId, run) {
// 把正确形状告诉模型,替它纠正包装习惯
output = chk.error;
isError = true;
} else if (session.phase === 'advising'
&& (tc.function.name === 'write_file' || tc.function.name === 'edit_file' || tc.function.name === 'copy_path')) {
// 顾问单入口硬约束:写类工具不在其 schema,但「名单外照跑」是全局策略(executeTool 全表),
// 幻觉调用会真写文件、绕过出口制造假承诺——阶段契约优先,挡下并指向 handoff。
output = 'Error: 顾问阶段不能写文件。任务书请通过 handoff 工具的 brief 参数提交。';
isError = true;
} else {
try {
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), run, cfg, db, vision,
@@ -881,19 +806,6 @@ async function runLoopInner(sessionId, run) {
image_url: imageRel ? '/api/sessions/' + encodeURIComponent(sessionId) + '/files/download?path=' + encodeURIComponent(imageRel) : undefined,
msg_id: toolMsgId,
});
// 阶段切换入口:advising 回合里 handoff 成功返回(brief 已由 handler 落盘 task.md)→ 标记待切换。
// 不在这里就地切:同批可能还有其它 tool_calls,其父 assistant 行若先被存档、
// 后落库的回执就成了无主孤儿行(上游拒收)——整批跑完再统一重建上下文。
if (!isError && tc.function.name === 'handoff') {
handoffDone = true;
}
}
if (handoffDone) {
// 顾问标题已由 toolHandoff 直写 sessions.title:广播同 maybeGenerateTitle 的 title 事件,
// 已开窗口刷详情页标题 + 重拉会话列表(finalize 的自动标题见非空即跳过,不会覆盖)。
const ht = db.prepare('SELECT title FROM sessions WHERE id = ?').get(sessionId);
if (ht && ht.title) bus.emit(sessionId, 'title', { title: ht.title });
enterExecuting(sessionId);
}
iter++;
}
@@ -1099,11 +1011,11 @@ function createSession(title, preferModelId, assistantType, user) {
const dir = taskDirOf(id);
fs.mkdirSync(dir, { recursive: true });
db.prepare(
"INSERT INTO sessions (id, title, status, phase, model_id, model_slot, last_model_id, held_at, assistant_type, user, created_at, updated_at) VALUES (?,?,'held','advising',?,?,?,?,?,?,?,?)"
"INSERT INTO sessions (id, title, status, model_id, model_slot, last_model_id, held_at, assistant_type, user, created_at, updated_at) VALUES (?,?,'held',?,?,?,?,?,?,?,?)"
).run(id, title || '', modelId, key.id, modelId, now(), assistantType || 'secretary', user || '', now(), now());
db.prepare('UPDATE model_pool SET last_used_at = ? WHERE id = ?').run(now(), key.id);
profile.freezeSnapshot(db, id); // 冻结画像快照:仅创建/清空时点注入,会话内恒定(见 user-profile.js)
// 新会话一律落 advising(顾问模式):先聊天判意图,任务书 task.md 落地才转 executing(见 enterExecuting)
// 新建会话默认走模型配置的 profile(未配 = 全量默认组合 + profile-default.txt),不再有顾问阶段
emitStatus(id);
const session = getSession(id);
return session;
@@ -1166,8 +1078,8 @@ function renameSession(sessionId, title) {
const t = String(title || '').trim();
if (!t) throw Object.assign(new Error('名称不能为空'), { status_code: 400 });
if (t.length > 100) throw Object.assign(new Error('名称不能超过 100 字'), { status_code: 400 });
// 手动改名即上锁:后续 handoff 的自动标题见 title_locked 即跳过,不许冲掉用户起的名字
//(maybeGenerateTitle 本就见非空即跳,无需看锁)。
// 手动改名即上锁:显式留痕「标题为用户所起」。自动标题(maybeGenerateTitle)本就见非空即跳,
// 锁不改现有行为,仅为后续可能覆写标题的逻辑留一道防线。
touch(sessionId, { title: t, title_locked: 1 });
log.info('task', sessionId + ' 重命名为「' + t + '」');
return { ok: true, title: t };
@@ -1439,8 +1351,6 @@ function wipeSessionTmp(sessionId) {
// 会话级 /tmp(宿主机即 <任务目录>/.tmp,执行容器 bind 成容器内 /tmp)一并清空:清空的语义是“从零开始”,
// 上一轮留下的临时产物不该带进新一轮;执行容器遇到不存在的 .tmp 会懒重建,无副作用。
// 状态收尾为 completed;此后再次发言从零开始,不再携带旧历史。执行中的会话不允许清空,需先「终止」。
// 阶段语义:清空是 executing 唯一回头路——回到 advising 重新规划(单会话只解决一个问题),
// 旧任务书 mv 进 .task-history/ 防污染(archiveTaskBrief);压缩不碰 phase,不在此列。
function clearSessionMessages(sessionId) {
const session = getSession(sessionId);
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
@@ -1455,7 +1365,6 @@ function clearSessionMessages(sessionId) {
}
runs.delete(sessionId);
db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
archiveTaskBrief(sessionId); // 旧任务书先归档(mv),新一轮 advising 不会被上一问题的约定污染
wipeSessionTmp(sessionId); // 会话级 /tmp 随清空一并抹掉(尽力而为,失败只记日志不阻断)
autoCompressProposed.delete(sessionId); // 历史清零,恢复自动压缩提议额度
// 标题随历史一并清零:旧标题描述的是已删除的对话,留着会让新对话文不对题;
@@ -1471,13 +1380,12 @@ function clearSessionMessages(sessionId) {
if (frags) log.info('task', sessionId + ' 清空连带删除日记碎片 ' + frags + ' 条');
}
const reset = { status: 'completed', completed_at: now(), cancelled_at: null, held_at: null,
title: null, title_locked: 0, phase: 'advising', journaled_at: null };
title: null, title_locked: 0, journaled_at: null };
if (isTaskHome) delete reset.journaled_at; // touch 会把 undefined 写成 NULL,这里直接不送这个键
touch(sessionId, reset);
profile.freezeSnapshot(db, sessionId); // 回 advising 重新规划:画像快照随新一轮重新冻结
profile.freezeSnapshot(db, sessionId); // 新一轮开始:画像快照随新一轮重新冻结
bus.emit(sessionId, 'done', { status: 'completed' });
bus.emit(sessionId, 'title', { title: null }); // 供其他打开同一会话的窗口同步清掉旧标题
bus.emit(sessionId, 'phase', { phase: 'advising' });
emitStatus(sessionId);
return { ok: true };
}
-3
View File
@@ -88,9 +88,6 @@
margin-bottom: 10px; background: #fff; color: var(--ink); resize: vertical;
}
#schedule-modal textarea:focus { border-color: var(--active); }
/* 会话阶段徽标(advising 顾问态的标题小图标;executing 不显;尺寸显式定,不依赖 .ic 默认值) */
.prof-badge { display: inline-flex; align-items: center; margin-right: 4px; opacity: .62; flex: none; }
.prof-badge .ic { width: 13px; height: 13px; color: var(--active); }
/* welcome 头像兼做「选择模型」入口(与聊天态的「选择模型」同一弹窗) */
.logo-badge { cursor: pointer; }
</style>
-1
View File
@@ -355,7 +355,6 @@
const s = detail.session;
state.sessionTitle = (s && s.title) || '';
state.sessionType = (s && s.assistant_type) || 'secretary'; // 顶部 icon 跟随会话类型
state.phase = s && s.phase || ''; // 会话阶段(advising/executing):头部徽标与 SSE status/phase 事件同源
state.status = (s && s.status) || '';
state.schedule = detail.schedule || null; // 定时任务状态条数据(随 updatePhaseBar 一并渲染)
state.toolCards = {};
+2 -19
View File
@@ -160,7 +160,6 @@
mode: 'secretary', // 新建会话默认助手类型(欢迎页已去掉模式切换,不再可变)
sessionType: 'secretary', // 当前会话的助手类型(建档时锁定,后续不随模式切换变更)
deepThink: false, // 深度思考开关(仅本地视觉状态,无后端参数)
phase: '', // 当前会话阶段(sessions.phase: advising=顾问 / executing=执行;徽标据此渲染)
pendingModel: '', // welcome 预选模型(ensureSession 建档时透传 model_id)
sessionId: null, // 当前会话
sessionTitle: '', // 当前会话标题
@@ -200,32 +199,16 @@
updateScrollBottomBtn();
}
// ---------- 会话阶段徽标 ----------
// 头部标题前小图标:advising(顾问:澄清需求/规划)才显示(tooltip 说明),
// executing 是主干状态不显示、减噪。原 profile 模式徽标机位改造而来(手动切换模式已移除)。
const PHASE_BADGES = {
advising: {
label: '顾问模式:澄清需求、规划任务;写定任务书后自动开始执行',
icon: '<svg viewBox="0 0 24 24" class="ic" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18h6"/><path d="M10 21h4"/><path d="M12 3a6 6 0 0 0-3.6 10.8c.7.6 1.1 1.4 1.1 2.2h5c0-.8.4-1.6 1.1-2.2A6 6 0 0 0 12 3z"/></svg>',
},
};
function phaseBadgeHtml(p) {
const b = PHASE_BADGES[p];
if (!b) return '';
return '<span class="prof-badge phase-' + esc(p) + '" title="' + esc(b.label) + '">' + b.icon + '</span>';
}
function renderHeader() {
const c = $('header-center');
// welcome(含刚 newChat)一律清空:newChat 会停在 welcome,不重刷会残留旧会话标题
if (state.view !== 'chat' || !state.sessionId) { c.innerHTML = ''; return; }
// 顶部只显会话阶段徽标(advising 才显)+ 标题;助手类型 icon 早已退位
// 顶部只显标题;助手类型 icon 早已退位(会话阶段徽标随 advising 一并移除)
const title = document.createElement('div');
title.className = 'header-title';
title.style.cursor = 'pointer';
title.title = '点击重命名';
title.innerHTML = phaseBadgeHtml(state.phase) +
'<span class="header-title-text">' + esc(state.sessionTitle || state.sessionId) + '</span>';
title.innerHTML = '<span class="header-title-text">' + esc(state.sessionTitle || state.sessionId) + '</span>';
title.addEventListener('click', renameSession); // 点标题重命名(同步 index)
c.innerHTML = '';
c.appendChild(title);
-3
View File
@@ -78,7 +78,6 @@
state.sessionId = null;
state.sessionTitle = '';
state.sessionType = 'secretary';
state.phase = '';
state.pendingModel = '';
state.streamEl = null;
state.streamText = '';
@@ -161,7 +160,6 @@
// 先从抽屉列表缓存取会话类型,让顶部 icon 立即正确;详情回来后由 renderDetail 纠正
const cached = (state.sessions || []).find(x => x.id === id);
state.sessionType = (cached && cached.assistant_type) || 'secretary';
state.phase = (cached && cached.phase) || ''; // 先从列表缓存取阶段徽标,renderDetail 回来后纠正
state.streamEl = null;
state.streamText = '';
state.streamWrap = null;
@@ -214,7 +212,6 @@
state.sessionType = 'secretary';
state.status = '';
state.schedule = null;
state.phase = '';
state.pendingModel = '';
state.attachments = [];
state.streamEl = null;
-9
View File
@@ -136,19 +136,10 @@
es.addEventListener('status', ev => {
const d = JSON.parse(ev.data);
state.status = d.status;
state.phase = d.phase || '';
renderHeader();
updatePhaseBar(d);
updateScrollBottomBtn(); // 状态切换同步右下角转圈(开始/结束干活)
});
// 阶段切换(advising↔executing):任务书落地自动转执行时给一句明确反馈;
// 回 advising(清空)由发起动作自带反馈,不重复弹。
es.addEventListener('phase', ev => {
const d = JSON.parse(ev.data);
state.phase = d.phase || '';
renderHeader();
if (state.phase === 'executing') toast('任务书已确认,进入执行模式');
});
es.addEventListener('assistant_delta', ev => {
const d = JSON.parse(ev.data);
removeTyping();
-1
View File
@@ -192,7 +192,6 @@ const HELP_TEXT = [
].join('\n');
const STATUS_TEXT = { active: '活跃中', held: '保持中', completed: '已完成', cancelled: '已终止' };
const PHASE_TEXT = { advising: '顾问', executing: '执行' };
function fmtTime(ts) {
if (!ts) return '--';
-1
View File
@@ -97,7 +97,6 @@ router.get('/:id/stream', (req, res) => {
bus.emit(session.id, 'status', {
session_id: session.id,
status: session.status,
phase: session.phase,
model_id: session.model_id,
});
});
+1 -1
View File
@@ -107,7 +107,7 @@ router.get('/status', wrap((req, res) => {
auth_enabled: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length),
running_sessions: engine.activeRuns(),
// 曾有的 model_profiles 可用名单字段已删:前端手动切换模式入口全部移除,名单再无消费方
//(组合只经模型配置 profile: <名> 引用,或 advising 阶段强制命中,见 engine.resolveProfileName)。
//(组合只经模型配置 profile: <名> 引用,见 engine.resolveProfileName)。
// 前端上传预处理参数(大图压缩阈值/尺寸/质量、大文件确认阈值),避免前端写死
upload: cfg.upload || {},
});
-3
View File
@@ -218,9 +218,6 @@ function tick() {
// 顺序不可调换:先存档、后投递。postUserMessage 的 held/空闲分支会同步起 runLoop,
// 存档晚一步,回合就会带着旧上下文开跑。
archiveHistory(db, t.session_id);
// 无人值守的是执行型任务:投递前强制 phase='executing'——新会话可能还停在 advising,
// 顾问 profile 会把半夜的 prompt 当白天聊天「引导澄清并等用户回答」,永远出不了活。
db.prepare("UPDATE sessions SET phase='executing', updated_at=? WHERE id=?").run(now, t.session_id);
const r = deliver(t.session_id, t.prompt);
db.prepare(
"UPDATE scheduled_tasks SET last_run_at=?, last_status='running', last_note=NULL, next_run_at=? WHERE session_id=?"
-71
View File
@@ -1,71 +0,0 @@
You are the planning advisor for this conversation, accessed via a web
interface. This session is in the ADVISING phase: your job is to answer
questions, judge the user's intent, and turn a vague request into a clear,
executable task brief. You do not do the actual work here.
Each conversation has its own working directory. Tool paths are relative to it
unless stated otherwise.
## How to behave
- Small talk, general questions, quick look-ups: answer normally and directly.
Do not push every message toward "a task".
- When the user clearly wants work done: first make the requirement precise —
goal, inputs, expected output, constraints — in a friendly, short way.
- Ask at most one or two questions per reply, and only about points that would
change the deliverable. For trivial choices, pick a sensible default and note
the assumption. Never interrogate: after two or three rounds, or as soon as
the picture is clear enough, stop asking.
## Producing the task brief
When work should start — the requirement is clear, the user asks to skip
planning, or clarification has stalled — call the `handoff` tool with a
`reason`, a `title` (in the user's language), and the full `brief`. This is the
only way to leave the advising phase; the system then switches the session
into execution mode and a full-capability agent continues from the brief
alone.
The brief must be self-contained: someone who has never seen this chat must be
able to do the job from it. For small requests a three-line brief is fine;
never inflate it. Suggested structure: short title / Goal / Scope &
constraints / What the deliverable must contain / Acceptance criteria /
Assumptions picked.
If key facts are still missing when you hand off, list them under a "Missing"
section — in the user's own words, without guessing or adding generic advice.
The executor will ask the user about these before starting. A skipped-planning
brief is a short requirements note, not a methodology document.
## What the executor can do
The executor is a full-capability agent in an isolated Linux container with a
session working directory. Broadly: file operations, shell commands with
internet access, data processing and SQLite storage, web data pages, document
conversion, media processing, email, and public download links.
{APP_SKILLS_SECTION}
The list above is a coarse guide, not a hard boundary — and you are not the
one who judges feasibility. The executor may achieve a request by combining
its tools, or by combining tools with the user's own environment (their
browser or device). When feasibility is in doubt, do not argue it out and do
not declare it impossible on the user's behalf — hand off and flag the
question in the brief. Doubt about *feasibility* goes to handoff; doubt about
*what the user wants* goes through normal clarification.
Prefer approaches that use existing capabilities. If unsure whether something
is feasible, say so or note it as a risk — never fake certainty in either
direction.
## What you must not do
- Do not carry out the task itself in this phase. Research that informs the
plan — reading files, fetching web — is fine; producing the deliverable is
not.
- Do not prescribe technical implementation. Describe *what* the result must
be and *how it will be judged*; never *how to build it*.
When in doubt about whether something is a requirement or an implementation
detail, ask: "Would a different executor using different tools still need
this?" If yes, it belongs in the brief. If no, leave it out.
-34
View File
@@ -140,40 +140,6 @@
}
}
},
{
"type": "function",
"function": {
"name": "handoff",
"description": "Hand off from the advising phase to the execution phase. Call this when the task brief is ready. The system stores your `brief` as the task brief and switches to execution. There are three cases:\n\n- ready: The requirement is clear enough to execute.\n- user_skip: The user explicitly asks to stop planning with you (\"just move on\", or similar) — this skips only the advising conversation, it never waives the user's later confirmations. Do not call this on tone or mood alone — only on explicit signals.\n- user_stuck: You have asked 2-3 rounds and the user is still not providing key information, and they seem to want to move on.\n\nWhen reason is not \"ready\", the `brief` must carry the user's own words plus every open question under a Missing section — the executor is required to ask the user these before acting. Do not invent a methodology or generic plan.",
"parameters": {
"type": "object",
"required": [
"reason",
"brief",
"title"
],
"properties": {
"reason": {
"type": "string",
"enum": [
"ready",
"user_skip",
"user_stuck"
],
"description": "Why the handoff is happening."
},
"brief": {
"type": "string",
"description": "The task brief content, in Markdown. Follow the structure described in your system prompt."
},
"title": {
"type": "string",
"description": "A concise title for this conversation, in the user's language (3-7 words, or 6-14 Chinese characters). Straight to the title: no quotes, no prefix like \"Title:\"."
}
}
}
}
},
{
"type": "function",
"function": {
-34
View File
@@ -1557,39 +1557,6 @@ function runLabHelp(args) {
return JSON.stringify(def.function, null, 2);
}
// handoff:顾问阶段唯一出口(advising 组合见 config.js)。brief 原样落盘任务目录根 task.md;
// title 直写 sessions.title(交接此刻顾问最懂这单任务,标题以此为准,finalize 的
// maybeGenerateTitle 见非空即跳过);批尾由 engine 广播 title 事件同步已开窗口。
// 切换不在此发生——executeTool 只落盘与回执,runLoopInner 在工具批尾接成功回执触发 enterExecuting
//(其读盘取快照作锚点,幂等防重切)。phase 守卫不可省:「名单外工具照跑」是全局策略,
// 执行期幻觉调用不得覆写修订中的 task.md;reason 枚举与 brief 非空也在此兑底(checkToolArgs 只查必填键)。
async function toolHandoff(ctx, args) {
const sess = ctx.db.prepare('SELECT phase, title_locked FROM sessions WHERE id = ?').get(ctx.sessionId);
if (!sess || sess.phase !== 'advising') return 'Error: 当前不在顾问阶段,handoff 仅在 advising 可用';
const reason = String((args && args.reason) || '');
if (['ready', 'user_skip', 'user_stuck'].indexOf(reason) < 0) {
return 'Error: reason 需为 ready / user_skip / user_stuck 之一';
}
const brief = typeof args.brief === 'string' ? args.brief : '';
if (!brief.trim()) return 'Error: brief 不能为空,任务书需完整带上(user_skip/user_stuck 至少含用户原话与 Missing 清单)';
// 标题清洗对齐 cleanTitle(engine 内函数,executor 反向引用会成环,此处同款口径):
// 压空白 + 截 60;引号剥除交给模型自觉(description 已明说),不做二次加工。
const title = String(args.title || '').replace(/\s+/g, ' ').trim().slice(0, 60);
if (!title) return 'Error: title 不能为空,给出一个概括任务的简洁标题';
const abs = path.join(ctx.taskDir, 'task.md');
await fsp.writeFile(abs, brief, 'utf8');
recordFile(ctx, abs); // 同步 files 元数据表(与 write_file 同轨,任务目录列表/清理逻辑一致)
// task.md 落盘成功后才改标题:切换半途失败不留「有名无书」的残局;
// 用户手动重命名过(title_locked,见 engine.renameSession)则尊重用户的名字,静默跳过。
if (!sess.title_locked) {
ctx.db.prepare('UPDATE sessions SET title = ?, updated_at = ? WHERE id = ?').run(title, Date.now(), ctx.sessionId);
}
// 同批多次 handoff:后写覆盖(last-wins),批尾的切换只发生一次(enterExecuting 幂等)。
// 回执只写事实:成功路径下本回执连同父行一起被存档、不会回到任何模型;
// 读者只有 enterExecuting 放弃/报错后继续 advising 的模型本身(据此自纠),无行为指令可带。
return '已接收交接(reason: ' + reason + '),本批工具跑完后系统将切换到执行阶段。';
}
// recall:长期记忆(工作日记)的回忆入口——纯记忆三 op。
// 日记按会话收口持久存储(memory.js),开场只注入最近 N 条;更早的条目由本工具按需取。
// 历史成果文件不再归日记管:浏览/导入走 list_directory / copy_path 的 @<会话id>/<路径> 记号
@@ -1627,7 +1594,6 @@ const HANDLERS = {
read_file: toolReadFile,
list_directory: toolListDirectory,
copy_path: toolCopyPath,
handoff: toolHandoff,
write_file: toolWriteFile,
edit_file: toolEditFile,
mint_public_link: toolMintPublicLink,
+2 -7
View File
@@ -241,8 +241,7 @@ function handleHook(body) {
// wxbot 会把 error 文案直接回给用户(IM 里「出错要出声」)。
// 媒体消息(inbox 带 media:{b64,kind,filename?},wxbot 已从 CDN 下好):统一落会话任务目录
// + 记 files 元数据表 → 按 web 上传同款拼「用户上传了文件:<名>」作正文走 handleSend。
// 渠道上下文(普通/媒体/带尾随文本的 /new 在消息入库前先幂等确保):微信会话直接落 executing
// 跳过顾问 handoff(与定时任务投递同理由:异步接入不能被顾问话术卡住),channel_note 把微信
// 渠道上下文(普通/媒体/带尾随文本的 /new 在消息入库前先幂等确保):channel_note 把微信
// 环境说明注入历史(UI 可见的 user 行,模型当普通消息看)——先于首条消息,AI 第一回合就看得到。
const MEDIA_MAX_BYTES = 20 * 1024 * 1024;
const MEDIA_KINDS = new Set(['image', 'video', 'file']);
@@ -266,13 +265,9 @@ const MEMORY_NOTE_HEAD = '# [CTX] memory\n\n'
function ensureChannelContext(s) {
if (!s) return;
if (s.phase !== 'executing') {
db.prepare("UPDATE sessions SET phase='executing', updated_at=? WHERE id=?").run(now(), s.id);
s.phase = 'executing';
}
if (!db.prepare("SELECT 1 FROM messages WHERE session_id = ? AND type = 'channel_note' LIMIT 1").get(s.id)) {
engine.saveMessage(s.id, { role: 'user', type: 'channel_note', content: CHANNEL_NOTE });
log.info('wechat', s.id + ' 渠道上下文注入(executing + channel_note)');
log.info('wechat', s.id + ' 渠道上下文注入(channel_note)');
}
// 开场日记:近几天长期记忆一次性写入,会话中途不补——与画像快照同「新会话冻结」语义,
// 轮换后新会话再带最新全文;无记忆/功能关闭时不写,省一条消息行也稳前缀缓存。