From 4051fcdd5c1f3e6d74c6d4f09526e46ec6aac190 Mon Sep 17 00:00:00 2001 From: kicer Date: Thu, 10 Sep 2026 08:12:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B8=85=E7=90=86=EF=BC=9A=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E5=85=A8=E9=83=A8=E6=B3=A8=E5=85=A5=E5=9E=8B=E6=B6=88=E6=81=AF?= =?UTF-8?q?=EF=BC=88=E4=BC=9A=E8=AF=9D=E4=B8=8A=E4=B8=8B=E6=96=87/?= =?UTF-8?q?=E9=99=84=E4=BB=B6=E7=B3=BB=E7=BB=9F=E9=80=9A=E7=9F=A5/?= =?UTF-8?q?=E5=BC=80=E5=A7=8B=E6=89=A7=E8=A1=8C=E6=8C=87=E4=BB=A4=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 会话上下文:删 sessionContextContent/ensureSessionContext/loadHistoryForModel/modelDisplayName 及 bindToSession、runLoopInner、createSession 三处注入;存档/hasUserSince/hasPendingUser 去掉 session_context 特判;SSE 请求历史改用 loadHistory 直取;server.js prompt dump 去掉第 3 部分 - 附件通知:删 routes/messages.js 的 composeWithAttachments/fmtSize 与 POST 路由的 attachments 拼接,正文原样入库、content 必填;前端 send() 不再随 body 传 attachments,无文字时拦截并提示(附件仅上传任务目录);parseUploadNotice 保留兼容旧库行 - 开始执行:删 START_EXECUTION_MESSAGE、engine.startExecution、POST /:id/start 路由与导出(v2 前端本无入口) - 注释与 README 同步清理 --- app/README.md | 1 - app/server/config.js | 2 +- app/server/engine.js | 107 ++-------------------------------- app/server/llm.js | 4 +- app/server/public/index.html | 10 +++- app/server/public/js/tasks.js | 3 +- app/server/routes/messages.js | 34 ++--------- app/server/server.js | 9 +-- 8 files changed, 22 insertions(+), 148 deletions(-) diff --git a/app/README.md b/app/README.md index a1ec38c..c48c9a2 100644 --- a/app/README.md +++ b/app/README.md @@ -47,7 +47,6 @@ npm test # 启动 mock 上游 + 真实 server 的端到端冒烟测 ## 提示词与工具 schema System prompt 完全静态(所有会话共用,利于上游前缀缓存),在 `server/templates/system-prompt.txt` 直接编辑;工具定义在 `server/tools/definitions.json`。改完重启服务。 -动态会话信息(日期、任务目录、模型显示名)不拼入 prompt,而是新建会话时作为首条 user 消息自动发送(带 `session_context` 标记,不会单独触发模型回复),见 `engine.js` 的 `sessionContextContent`。 ## 关键行为速查 diff --git a/app/server/config.js b/app/server/config.js index ed60f44..caa16f8 100644 --- a/app/server/config.js +++ b/app/server/config.js @@ -114,7 +114,7 @@ function normalizePlatforms(rawPlatforms) { models.push({ id: String(m.id), display_name: m.display_name ? String(m.display_name) : String(m.id), // 缺省 = id - vision: m.vision === true, // 支持时 read_file 读图会回传图片,会话上下文会告知 AI + vision: m.vision === true, // 支持时 read_file 读图会回传图片内容 enable: m.enable !== false, // 选填,默认启用;禁用后不进模型池,不参与分配/绑定(重启生效) // 选填:模型特有的请求体参数对象。发往上游时整体合并进 body 顶层。 extra_params: (m.extra_params && typeof m.extra_params === 'object' && !Array.isArray(m.extra_params)) ? m.extra_params : {}, diff --git a/app/server/engine.js b/app/server/engine.js index f0bcd99..d0e3e62 100644 --- a/app/server/engine.js +++ b/app/server/engine.js @@ -9,15 +9,6 @@ const log = require('./log'); const TOOL_DEFINITIONS = require('./tools/definitions.json'); -const START_EXECUTION_MESSAGE = - '我说完了,你可以开始干活了。先把我上面说的需求整理成 task.md 文件写入任务目录,然后按照 task.md 开始执行。'; - -// 会话上下文消息标记:动态信息(日期/任务目录/模型显示名)不再拼入 system prompt, -// 而是作为首条 user 消息发给模型,跟着会话走;它不单独触发模型回合。 -// 注入时机 = 模型绑定就绪:手动选择模型后立即注入;自动派发则在首次回复前注入, -// 避免未绑定模型时产生“尚未绑定/未知”占位(见 ensureSessionContext)。 -const SESSION_CONTEXT_NAME = 'session_context'; - let cfg, db, bus; const runs = new Map(); // session_id -> {cancelled, procs:Set, abortController, looping:boolean} @@ -185,11 +176,6 @@ function freeModel() { return db.prepare('SELECT * FROM model_pool WHERE is_busy = 0 ORDER BY id').get(); } -function modelDisplayName(modelId) { - const row = db.prepare('SELECT display_name FROM model_pool WHERE id = ?').get(modelId); - return row ? row.display_name : modelId; -} - // 会话绑定的模型是否支持 vision(图片回传);决定 read_file 读图行为(见 tools/executor.js)。 function modelVision(session) { const m = session.model_id && (cfg.models || []).find(x => x.id === session.model_id); @@ -238,19 +224,16 @@ function bindToSession(sessionId, modelId) { const pending = hasPendingUser(sessionId); bindModel(s, model, pending ? 'active' : 'held'); emitStatus(sessionId); - // 手动选好模型后立即注入/刷新会话上下文(换绑时更新为当前模型,避免陈旧信息) - ensureSessionContext(sessionId); log.info('model', sessionId + ' 手动绑定模型 ' + model.id); if (pending) runLoop(sessionId); return { ok: true, model_id: model.id }; } // 是否还有待回应的新用户消息(最后一条非 tool 消息是 user)。 -// 会话上下文消息(role=user 但带 SESSION_CONTEXT_NAME 标记)不算待回应消息。 function hasPendingUser(sessionId) { const rows = loadHistory(sessionId); for (let i = rows.length - 1; i >= 0; i--) { - if (rows[i].role === 'tool' || rows[i].name === SESSION_CONTEXT_NAME) continue; + if (rows[i].role === 'tool') continue; return rows[i].role === 'user'; } return false; @@ -420,8 +403,6 @@ function finalize(sessionId, run) { } async function runLoopInner(sessionId, run) { - // 能到这里说明模型已绑定:先注入/刷新会话上下文(内容随当前模型与当天日期更新) - ensureSessionContext(sessionId); let iter = 0; // 已纳入模型请求的最大消息 id;用于判断是否有尚未被回应的新 user 消息 // (不能用“最后一条非 tool 消息是 user”判断:流式输出期间到达的消息会排在 assistant 之前而被漏掉) @@ -430,7 +411,7 @@ async function runLoopInner(sessionId, run) { while (!run.cancelled && iter < maxIter) { const session = getSession(sessionId); if (!session || session.status !== 'active' || !session.model_id) break; - session.history = loadHistoryForModel(sessionId); + session.history = loadHistory(sessionId); for (const m of session.history) if (m.id > lastIncludedId) lastIncludedId = m.id; // 压缩回合(run.summarizing = 由「压缩」按钮发起、尚未产出摘要): // 只发一条 system(压缩模板,{{conversation}} 占位符已填入完整历史纯文本) @@ -517,14 +498,13 @@ async function runLoopInner(sessionId, run) { //(前端重渲染成摘要卡片;也是模型上下文的起点),并把之前的消息存档: // type='archived' 行 UI 照常展示,但 buildMessages 不再发给模型—— // 后续对话从这条摘要开始,旧历史不再烧 token。 - // session_context 行不存档:它是环境信息,始终随新回合发送(loadHistoryForModel 置顶)。 // 旧摘要行(多轮压缩)一并存档:被新摘要覆盖替代,不再进上下文。 run.summarizing = null; if ((msgRow.content || '').trim()) { db.prepare("UPDATE messages SET type = 'summary' WHERE id = ?").run(assistantId); const n = db.prepare( "UPDATE messages SET type = 'archived' WHERE session_id = ? AND id < ?" + - " AND (type IS NULL OR type != 'archived') AND (name IS NULL OR name != 'session_context')" + " AND (type IS NULL OR type != 'archived')" ).run(sessionId, assistantId).changes; log.info('msg', sessionId + ' 压缩摘要 ' + assistantId + ' 落库,存档之前 ' + n + ' 条消息(不再发给模型)'); } @@ -661,8 +641,8 @@ async function streamAssistant(sessionId, run, session, messages, tools) { function hasUserSince(sessionId, sinceId) { const r = db.prepare( - "SELECT COUNT(*) AS c FROM messages WHERE session_id = ? AND role = 'user' AND id > ? AND (name IS NULL OR name <> ?)" - ).get(sessionId, sinceId, SESSION_CONTEXT_NAME); + "SELECT COUNT(*) AS c FROM messages WHERE session_id = ? AND role = 'user' AND id > ?" + ).get(sessionId, sinceId); return r.c > 0; } @@ -728,63 +708,6 @@ function unwrapToolArgs(tools, name, raw) { function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } // ---------- 对外 API ---------- -// 会话上下文动态信息:作为首条 user 消息发给模型(同时展示在聊天里),跟会话走; -// 在模型绑定就绪后注入/刷新(ensureSessionContext),不随未绑定会话提前产生。 -function sessionContextContent(session) { - const d = new Date(); - const pad = n => String(n).padStart(2, '0'); - const dateStr = d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()); - const model = session.model_id - ? modelDisplayName(session.model_id) - : '尚未绑定(排队中,绑定后自动开始处理)'; - // vision 能力随会话上下文告知 AI:支持时 read_file 读图会回传图片内容,不支持时只能拿到文件信息 - const bound = session.model_id && cfg.models.find(m => m.id === session.model_id); - const visionLine = bound - ? (bound.vision ? '支持(read_file 读图会返回压缩后的图片内容)' : '不支持(read_file 读图只能拿到文件信息)') - : '未知'; - return [ - '【会话上下文】由系统自动注入,无需回复本消息', - '- 当前日期:' + dateStr, - '- 任务目录:' + taskDirOf(session.id), - '- 当前模型:' + model, - '- 图片(vision):' + visionLine, - ].join('\n'); -} - -// 让会话恰好保有一条反映「当前绑定模型/当天日期」的会话上下文消息: -// - 未绑定模型时不注入(避免产生“尚未绑定(排队中…)/未知”这类占位信息); -// - 已有则就地更新内容(换绑模型或跨天后保持准确,id 与位置不变); -// - 没有则补一条(存储位置无严格要求:发给模型前统一置顶,见 loadHistoryForModel)。 -function ensureSessionContext(sessionId) { - const s = getSession(sessionId); - if (!s || !s.model_id) return; - const content = sessionContextContent(s); - const rows = loadHistory(sessionId); - let ctxIdx = -1; - for (let i = rows.length - 1; i >= 0; i--) { - if (rows[i].name === SESSION_CONTEXT_NAME) { ctxIdx = i; break; } - } - if (ctxIdx >= 0) { - const row = rows[ctxIdx]; - if (row.content !== content) { - db.prepare('UPDATE messages SET content = ?, created_at = ? WHERE id = ?') - .run(content, now(), row.id); - } - return; - } - saveMessage(sessionId, { role: 'user', name: SESSION_CONTEXT_NAME, content }); -} - -// 加载给模型看的历史:会话上下文消息固定放最前(只保留最新一条), -// 避免它落在真实用户消息之后、或残留旧上下文时误导模型。 -function loadHistoryForModel(sessionId) { - const rows = loadHistory(sessionId); - const ctxRows = rows.filter(r => r.name === SESSION_CONTEXT_NAME); - if (!ctxRows.length) return rows; - return [ctxRows[ctxRows.length - 1]] - .concat(rows.filter(r => r.name !== SESSION_CONTEXT_NAME)); -} - function createSession(title, preferModelId, assistantType, user) { const id = genTaskId(); const dir = taskDirOf(id); @@ -805,10 +728,8 @@ function createSession(title, preferModelId, assistantType, user) { enqueue(id); dispatchQueued(); } - // 已绑定模型(选中的空闲模型 / 自动派发立即拿到模型)才注入会话上下文; - // 仍在排队未绑定时不注入占位消息,等绑定后由 ensureSessionContext 补上。 + // 已绑定模型(选中的空闲模型 / 自动派发立即拿到模型)时保持 held,等首条消息再开跑。 const session = getSession(id); - ensureSessionContext(id); return session; } @@ -853,15 +774,6 @@ function postUserMessage(sessionId, content, opts) { return { message_id: messageId, delivered: after && after.status === 'active' ? 'live' : 'queued' }; } -function startExecution(sessionId) { - const session = getSession(sessionId); - if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 }); - touch(sessionId, { phase: 'execution' }); - const ret = postUserMessage(sessionId, START_EXECUTION_MESSAGE); - bus.emit(sessionId, 'phase', { phase: 'execution' }); - return ret; -} - function stop(sessionId) { const session = getSession(sessionId); if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 }); @@ -971,9 +883,6 @@ function summarizeContext(sessionId) { // 清空会话的对话内容:删除该会话的全部消息记录,但保留会话本身与任务目录文件。 // 状态收尾为 completed(释放模型占用、移出等待队列);此后再次发言从零开始, // 不再携带旧历史。执行中的会话不允许清空,需先「终止」。 -// 清空后不自动重建会话上下文:此时通常未绑定模型,预置只会产生“尚未绑定/未知”占位。 -// 待用户选择模型(bindToSession)或再次发言并自动绑定模型(runLoop 入口)时, -// 由 ensureSessionContext 注入当时的有效信息。 function clearSessionMessages(sessionId) { const session = getSession(sessionId); if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 }); @@ -1060,7 +969,6 @@ module.exports = { activeRuns, createSession, postUserMessage, - startExecution, stop, releaseHold, renameSession, @@ -1074,12 +982,9 @@ module.exports = { loadHistory, saveMessage, queuePosition, - modelDisplayName, - sessionContextContent, recordModelUsage, modelUsageStats, dispatchQueued, bindToSession, TOOL_DEFINITIONS, - START_EXECUTION_MESSAGE, }; diff --git a/app/server/llm.js b/app/server/llm.js index a44a5a8..891f8e1 100644 --- a/app/server/llm.js +++ b/app/server/llm.js @@ -22,7 +22,7 @@ function historyTranscript(session) { const blocks = decodeBlocks(content); if (blocks) content = blocks.map(b => (b && b.type === 'text' ? b.text : '[图片]')).join('\n'); if (row.role === 'user') { - lines.push(row.name === 'session_context' ? '[环境信息]\n' + content : '[用户] ' + content); + lines.push('[用户] ' + content); } else if (row.role === 'assistant') { const parts = []; if (content) parts.push('[AI] ' + content); @@ -52,8 +52,6 @@ function compressPromptText(conversation) { } // system prompt 完全静态:所有会话共用同一份内容,利于上游前缀缓存。 -// 动态会话信息(日期/任务目录/模型显示名)不再拼入 system prompt, -// 而是在新建会话时作为首条 user 消息发送,见 engine.js 的 sessionContextContent。 function buildSystemPrompt() { return SYSTEM_PROMPT_TEMPLATE; } diff --git a/app/server/public/index.html b/app/server/public/index.html index 92e8059..9bee67e 100644 --- a/app/server/public/index.html +++ b/app/server/public/index.html @@ -532,7 +532,8 @@ }); // ---------- 消息渲染 ---------- - // 服务端把附件说明拼在正文前(【系统通知】用户上传了文件:...),此处拆开单独展示 📎 行 + // 旧消息兼容:早期服务端把附件说明拼在正文前(【系统通知】用户上传了文件:...),此处拆开单独展示 📎 行; + // 新版已不再生成这种行,仅历史会话渲染时命中。 function parseUploadNotice(content) { const m = /^【系统通知】用户上传了文件:([^\n]*)(?:\n([\s\S]*))?$/.exec(content || ''); if (!m) return { text: content || '', files: null }; @@ -1409,7 +1410,11 @@ async function send() { const ta = $('msg-input'); const content = ta.value.trim(); - if (!content && !state.attachments.length) return; + // 附件仅上传到任务目录,不再随正文拼通知行:没有文字就不发(避免产生空消息)。 + if (!content) { + if (state.attachments.length) toast('附件需随一条文字消息发送'); + return; + } const pending = state.attachments.slice(); state.attachments = []; @@ -1422,7 +1427,6 @@ let atts = []; if (pending.length) atts = await uploadFiles(id, pending); const body = { content, deepThink: !!state.deepThink }; - if (atts.length) body.attachments = atts; const sent = await req('POST', '/api/sessions/' + id + '/messages', body); appendUserMsg(content, atts.map(a => a.name), sent && sent.message_id); diff --git a/app/server/public/js/tasks.js b/app/server/public/js/tasks.js index 07e78b0..eae93b4 100644 --- a/app/server/public/js/tasks.js +++ b/app/server/public/js/tasks.js @@ -979,8 +979,7 @@ const ui = { try { await req('DELETE', '/api/sessions/' + id + '/messages'); toast('会话内容已清空,文件已保留'); - // 服务端已把会话收尾为 completed 并清空消息(不再预置会话上下文): - // 重新拉取详情即为干净起点;选择模型或再次发言后服务端会注入当时的会话上下文 + // 服务端已把会话收尾为 completed 并清空消息:重新拉取详情即为干净起点 const detail = await req('GET', '/api/sessions/' + id); await renderDetail(detail); loadSessions(); diff --git a/app/server/routes/messages.js b/app/server/routes/messages.js index 965a907..eeb4b01 100644 --- a/app/server/routes/messages.js +++ b/app/server/routes/messages.js @@ -15,44 +15,18 @@ function wrap(fn) { }; } -// 附件提示词:用户带附件发消息时,服务端在正文前拼一行系统通知, -// 与消息一并落库(历史重建时 AI 能看到)。格式: -// 【系统通知】用户上传了文件:a.png(大小 1.2 MB)、b.txt(大小 3 KB) -// <用户原文> -function fmtSize(n) { - n = Number(n) || 0; - if (n < 1024) return n + ' B'; - if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB'; - if (n < 1024 * 1024 * 1024) return (n / 1024 / 1024).toFixed(1) + ' MB'; - return (n / 1024 / 1024 / 1024).toFixed(2) + ' GB'; -} -function composeWithAttachments(content, attachments) { - if (!Array.isArray(attachments) || !attachments.length) return content; - const list = attachments.slice(0, 20).map(a => - String(a && a.name || 'file').slice(0, 200) + '(大小 ' + fmtSize(a && a.size) + ')' - ).join('、'); - const notice = '【系统通知】用户上传了文件:' + list; - return content ? notice + '\n' + content : notice; -} - +// 附件上传只写任务目录文件(见 routes/files.js),消息正文原样入库,不再拼接任何通知行。 router.post('/:id/messages', wrap((req, res) => { const content = String((req.body && req.body.content) || '').trim(); - // 附件告知:正文前拼【系统通知】行(见 composeWithAttachments 注释);纯附件消息(无正文)也合法。 - const attachments = Array.isArray(req.body && req.body.attachments) && (req.body.attachments || []).length - ? req.body.attachments : null; - const full = composeWithAttachments(content, attachments); - if (!full) return res.status(400).json({ error: 'content 与 attachments 不能同时为空' }); + if (!content) return res.status(400).json({ error: 'content 不能为空' }); // deepThink:是否启用模型该「深度思考」参数(thinking_params 合并进上游请求体) const deepThink = !!(req.body && req.body.deepThink); - const r = engine.postUserMessage(req.params.id, full, { deepThink }); + const r = engine.postUserMessage(req.params.id, content, { deepThink }); log.info('msg', (req.user || '-') + ' ' + req.params.id + ' 用户消息(' + (r && r.delivered || '?') + '):' + - full.slice(0, 60).replace(/\s+/g, ' ')); + content.slice(0, 60).replace(/\s+/g, ' ')); res.json(r); })); -router.post('/:id/start', wrap((req, res) => { - res.json(engine.startExecution(req.params.id)); -})); router.post('/:id/stop', wrap((req, res) => { res.json(engine.stop(req.params.id)); diff --git a/app/server/server.js b/app/server/server.js index 75cef15..98c40ea 100644 --- a/app/server/server.js +++ b/app/server/server.js @@ -81,20 +81,15 @@ app.get('/api/health', (req, res) => res.json({ ok: true, time: Date.now() })); const PORT = process.env.PORT || cfg.port; // 启动成功后把模型实际收到的各部分 dump 到文件方便人工核对(data_root 默认 ./data, -// 宿主机对应 /data/prompt.txt,已被 gitignore)。包含三部分: +// 宿主机对应 /data/prompt.txt,已被 gitignore)。包含两部分: // 1) system 消息:模板 + 可用技能段落 + 语言指令(进程内恒定,仅技能增删时变); -// 2) tools 数组:内置 definitions.json + 启动时发现的 MCP 工具,与每次请求的 tools 字段一致; -// 3) 会话上下文:每会话首条 user 消息(随日期/任务目录/绑定模型/vision 动态生成), -// 启动时无真实会话,用占位会话 id + 首个启用模型渲染一份示例。 +// 2) tools 数组:内置 definitions.json + 启动时发现的 MCP 工具,与每次请求的 tools 字段一致。 function dumpPromptBundle() { const file = path.join(cfg.data_root, 'prompt.txt'); const tools = engine.TOOL_DEFINITIONS.concat(mcp.toolDefinitions()); - const sampleModel = (cfg.models || []).find(m => m.enable !== false); - const sessionCtx = engine.sessionContextContent({ id: '', model_id: sampleModel && sampleModel.id }); const parts = [ '# ===== 1. System Prompt(system 消息,进程内恒定)=====\n\n' + llm.systemPromptText((cfg.agent || {}).language), '\n\n# ===== 2. Tools(' + tools.length + ' 个:内置 + MCP,随每次请求的 tools 字段发送)=====\n\n' + JSON.stringify(tools, null, 2), - '\n\n# ===== 3. Session Context(每会话首条 user 消息,按日期/任务目录/绑定模型动态生成;此处为示例)=====\n\n' + sessionCtx, ]; fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, parts.join(''), 'utf8');