diff --git a/app/server/engine.js b/app/server/engine.js index 88015e4..3bfed5e 100644 --- a/app/server/engine.js +++ b/app/server/engine.js @@ -566,7 +566,6 @@ async function runLoopInner(sessionId, run) { const txt = String(m.content || ''); return m.role + (m.tool_calls ? '[calls]' : '') + (txt.includes('图片数据已省略') ? '[图已省]' : '') - + (txt.includes('每轮只能携带一张图片') ? '[图被限流]' : '') + (txt.includes('本回合已投递过') ? '[图重复读挡回]' : ''); }).join(' ')); } @@ -677,8 +676,6 @@ async function runLoopInner(sessionId, run) { // 执行工具 const vision = modelVision(session); let handoffDone = false; // 本批工具里是否有 handoff 成功返回(批量跑完统一切换,见循环尾注释) - // 本批(=本次模型调用可见范围)是否已放行过一张图;随 while 每轮迭代重置。 - let imgThisTurn = false; for (const tc of msgRow.tool_calls) { if (run.cancelled) break; const id = tc.id; @@ -720,21 +717,16 @@ async function runLoopInner(sessionId, run) { outText = String(output == null ? '' : output); } if (run.cancelled && !isError) outText = (outText ? outText + '\n' : '') + '(用户已终止任务)'; - // 死循环护栏(实测:多图同时进上下文时部分上游只认一张;叠加催读文案会让模型整轮重读同一批图、 - // 每轮都签新图烧 token 直到迭代耗尽): - // ① 每次模型调用最多携带一张图:同批后续图回执降级为文字,让模型下一轮单独再读,逐轮收敛; - // ② 同回合同一张图只投递一次:已投递过的再读只回文字提示(run 随回合销毁,新回合自动重置额度)。 + // 死循环护栏:同回合内同一张图只投递一次——上游能认多图(探针实测同消息双外链全对), + // 不再按批次限流;但模型若因惯性叙事反复重读同一文件,每轮都签新图就是纯烧 token, + // 故已投递过的图再读只回文字提示(run 随回合销毁,新回合自动重置,追问重看不受影响)。 if (imageRel) { if (!run.imgDelivered) run.imgDelivered = new Set(); if (run.imgDelivered.has(imageRel)) { outText += '\n[该图片本回合已投递过,不再重复携带;若你未看到它,请直接告知用户,勿反复重读同一文件]'; imageRel = null; - } else if (imgThisTurn) { - outText += '\n[每轮只能携带一张图片,本张未投递:请在下一轮单独 read_file 本文件查看]'; - imageRel = null; } else { run.imgDelivered.add(imageRel); - imgThisTurn = true; } } log.debug('tool', sessionId + ' ' + tc.function.name + (isError ? ' 失败: ' : ' 完成: ') + outText); diff --git a/app/server/llm.js b/app/server/llm.js index 01a434a..a542fed 100644 --- a/app/server/llm.js +++ b/app/server/llm.js @@ -128,9 +128,13 @@ function cachedDecodeBlocks(session, row) { // 大量 OpenAI 兼容上游会整批忽略或只认批次最后一张,模型看不到图却见回执写着 // 「已回传」,会反复 read_file 补看(死循环烧 token,见多模态回退复盘); // 故回执降级为纯文本,图块现签成 image_url(mintUrl 公网链回调)后统一并入 -// 该批回执之后的一条 user 消息(user 角色各家通吃),每张图前配一行对应回执文字; +// 该批之后的一条 user 消息(user 角色各家通吃):逐图说明文字全部置顶、图块按回执顺序紧随 +//(对齐官方示例排布;探针实测 DS 对交替排布也兼容,取低风险形态), +// 并附「先逐张简述再继续任务」指令——兼作送达自检,破弱模型的“没收到”惯性叙事; // 签不到(base_url 未配等)降级为文字占位,绝不把 image_ref 这种非标准块发上游。 -// 省 token:图块仅在其位于最后一条 assistant 消息之后(模型尚未对它回复)时携带; +// 省 token:图块保留到最后一条「收尾回复」(无 tool_calls 的 assistant)之前; +// 中间轮只发 tool_calls 不算看过,图继续携带——14:33 实测 pt 证明图已进上下文而模型 +// 仍自述没看到(弱模型行为不可靠),行为鲁棒优先于极致省钱;更早的视为已消费, // 之前的视为已消费,发请求时替换为文字标记(措辞不再催促重读)。DB 始终存全量: // UI 历史照常渲染图片,模型如需重看可再次 read_file(新回执在尾部,会重新携带图片)。 // 压缩摘要相关行(见 engine.runLoopInner / summarizeContext): @@ -162,10 +166,13 @@ function buildMessages(session, language, mintUrl, profile, withProfile) { // tool 回执按 tool_call_id 索引:给 errAck 行拼错误提示时取执行时挡下的原因 const toolRowById = new Map(); for (const row of history) if (row.role === 'tool' && row.tool_call_id) toolRowById.set(row.tool_call_id, row); + // 「已消费」分界 = 最后一条给出收尾回复(无 tool_calls)的 assistant:模型只发 + // tool_calls 的中间轮不算已阅图,图继续随请求携带直到它真正答复过一次。 + // errAck / archived 不发模型,不算回复:它们之前的图不算被消费。 let lastAssistant = -1; for (let i = history.length - 1; i >= 0; i--) { - // errAck / archived 不发模型,不算「模型已回复」:它们之前的图不算被消费,下次仍携带 - if (history[i].role === 'assistant' && history[i].type !== 'errAck' && history[i].type !== 'archived') { lastAssistant = i; break; } + const r = history[i]; + if (r.role === 'assistant' && r.type !== 'errAck' && r.type !== 'archived' && !r.tool_calls) { lastAssistant = i; break; } } const dropToolCallIds = new Set(); // 旧版 summarize_request 「已答复」判定的前置信息:最后一次「回合收尾回复」(无 tool_calls 的 assistant)的位置。 @@ -178,7 +185,8 @@ function buildMessages(session, language, mintUrl, profile, withProfile) { // 未消费图片的暂存区:tool 回执降级为纯文本,图块收集到这里, // 循环结束后合并成一条 user 消息发送(顺序约束:天然落在该批全部回执之后、 // 且是模型下一次的直接输入,assistant→tool 回执的紧邻约束不被打断)。 - const pendingImages = []; + const pendingImages = []; // 待投递的图块(按回执顺序;签不到时不占位) + const pendingLabels = []; // 每图一行「对应回执」说明,合并进首条文字块(text 置顶、图在后) let imgSeq = 0; history.forEach((row, i) => { // archived:UI 可见,但不进入模型上下文(节省 token) @@ -226,17 +234,25 @@ function buildMessages(session, language, mintUrl, profile, withProfile) { content = blocks.filter(b => b && b.type === 'text').map(b => b.text).join('\n') + '\n[图片数据已省略:本图已随上一条回执发送过,不再重复携带;若你当时未能识别其内容,请直接告知用户,勿反复重读同一文件]'; } else if (row.role === 'tool') { - // 未消费的图:回执只留文字,图块挪进批次后的 user 合并消息(见 pendingImages) + // 未消费的图:回执只留文字,图块挪进批次后的 user 合并消息(见 pendingImages/Labels) const texts = blocks.filter(b => b && b.type === 'text').map(b => b.text); content = texts.join('\n'); + const label = (texts[0] || 'read_file 图片回传').split('\n')[0]; for (const b of blocks) { if (!b || (b.type !== 'image_ref' && b.type !== 'image_url')) continue; - // 每张图配一行对应回执说明(回执首行含文件名与压缩信息),模型能对上号 - pendingImages.push({ type: 'text', text: '[图片 ' + (++imgSeq) + ',对应回执] ' + ((texts[0] || 'read_file 图片回传').split('\n')[0]) }); - if (b.type === 'image_url') { pendingImages.push(b); continue; } // 旧库内联 data: URL 原样 + const seq = ++imgSeq; + if (b.type === 'image_url') { // 旧库内联 data: URL 原样 + pendingLabels.push('[图片 ' + seq + '] ' + label); + pendingImages.push(b); + continue; + } const url = mintUrl ? mintUrl(b.rel) : null; - pendingImages.push(url ? { type: 'image_url', image_url: { url } } - : { type: 'text', text: '[图片外链不可用:未能取得图片内容,请直接告知用户,勿反复重读同一文件]' }); + if (url) { + pendingLabels.push('[图片 ' + seq + '] ' + label); + pendingImages.push({ type: 'image_url', image_url: { url } }); + } else { + pendingLabels.push('[图片 ' + seq + '] ' + label + '(外链不可用,未取得像素:请直接告知用户,勿反复重读同一文件)'); + } } } else { // user 行(粘贴附件/旧形态):image_url 块(data: URL)原样;image_ref → 现签公网外链 @@ -254,11 +270,16 @@ function buildMessages(session, language, mintUrl, profile, withProfile) { messages.push({ role: row.role, content }); } }); - // 该批未消费图片合并发送:一条 user 消息带全部图块,逐图前置对应回执标签 - if (pendingImages.length) { + // 该批未消费图片合并发送:单条 text 置顶列出逐图对应说明,图块按编号顺序紧随; + // 「先简述每张图再继续」兼作送达自检——模型描述得出来 = 像素真到了;描述不出 = 真没到, + // 不会再像 14:33 那样带着图却沿“没收到”的叙事惯性重读。 + if (pendingImages.length || pendingLabels.length) { messages.push({ role: 'user', - content: [{ type: 'text', text: '[系统] 以上工具回执对应的图片内容如下(read_file 回传,按回执顺序):' }] + content: [{ type: 'text', + text: '[系统提示] 以下不是用户新输入,是上面这批 tool 回执对应的图片(read_file 回传):\n' + + pendingLabels.join('\n') + + (pendingImages.length ? '\n请按编号顺序逐张简述每张图片里有什么(表明像素确实送达),然后继续完成用户的任务。' : '') }] .concat(pendingImages), }); } diff --git a/app/server/tools/definitions.json b/app/server/tools/definitions.json index 9742bbc..8d71d92 100644 --- a/app/server/tools/definitions.json +++ b/app/server/tools/definitions.json @@ -202,7 +202,7 @@ "type": "function", "function": { "name": "read_file", - "description": "Reads the content of a file.\n\nText files: each returned line is prefixed with a line number right-aligned in a 6-character field, followed by a tab, then the line content.\n\nLarge text files (roughly over 16 KB) are not returned in full: you get an outline listing top-level symbols (or Markdown headings) with line numbers instead. The outline IS a successful response — do NOT retry the same call without a line range; use the outline line numbers with `start_line` / `end_line` to read specific sections. If no outline can be extracted, a first-1KB excerpt is returned instead. Supplying `start_line` or `end_line` disables outline mode.\n\nImage files (PNG, JPEG, WebP, GIF, BMP, TIFF) are returned as visual content you can analyze directly, but only if the current model supports vision; otherwise a text placeholder is returned — that placeholder is not an error. The tool result itself carries a text notice only; the actual image pixels arrive in a separate user message right after the batch of tool results, each image preceded by a label naming the read_file result it belongs to. At most ONE image arrives per round: when several images are read in one batch only the first carries pixels and the rest come back as text asking you to read_file them individually next round — so read images one at a time when you need several, never re-read an image already delivered in this turn, and if pixels never arrive tell the user instead of retrying. Very large images (roughly over 50 MB) are skipped, and images may be downscaled (long edge ~2000 px, re-encoded as JPEG) before being returned.\n\nBinary files are not returned as text; a short notice is returned instead. Text files over 32 MB cannot be read by this tool — use `terminal` (grep -n / head / sed -n).", + "description": "Reads the content of a file.\n\nText files: each returned line is prefixed with a line number right-aligned in a 6-character field, followed by a tab, then the line content.\n\nLarge text files (roughly over 16 KB) are not returned in full: you get an outline listing top-level symbols (or Markdown headings) with line numbers instead. The outline IS a successful response — do NOT retry the same call without a line range; use the outline line numbers with `start_line` / `end_line` to read specific sections. If no outline can be extracted, a first-1KB excerpt is returned instead. Supplying `start_line` or `end_line` disables outline mode.\n\nImage files (PNG, JPEG, WebP, GIF, BMP, TIFF) are returned as visual content you can analyze directly, but only if the current model supports vision; otherwise a text placeholder is returned — that placeholder is not an error. The tool result itself carries a text notice only; the actual image pixels arrive in a separate user message right after the batch of tool results: that message lists per-image labels matching each image to its read_file receipt, then the image blocks in receipt order, and asks you to briefly describe each image before continuing. Never re-read an image already delivered in the current turn; if pixels never arrive, tell the user instead of retrying. Very large images (roughly over 50 MB) are skipped, and images may be downscaled (long edge ~2000 px, re-encoded as JPEG) before being returned.\n\nBinary files are not returned as text; a short notice is returned instead. Text files over 32 MB cannot be read by this tool — use `terminal` (grep -n / head / sed -n).", "parameters": { "type": "object", "required": [ diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index af03ebf..b9c6df4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -296,7 +296,7 @@ stateDiagram-v2 - `lastIncludedId` 跟踪本轮已纳入模型请求的最新消息 id;流式期间到达的新 user 消息靠它在下一轮迭代时自动带上。 - **errAck 机制**:工具参数结构性错误(JSON 非法/缺必填)→ 整条 assistant 标 `type='errAck'`,关联 tool 回执一并丢弃,发请求时由 user 错误提示替代(`llm.buildMessages`)—— 防止模型模仿自己的坏样本死循环。 - **archived/summary 机制**(上下文压缩):`type='archived'` 的消息 UI 照常展示但不再发模型;`type='summary'` 是压缩后的"上下文起点"。压缩回合**不插入任何指令消息**:由 `engine.summarizeContext` 在内存 run 上标 `summarizing`,`runLoopInner` 据此走 `llm.compressMessages`:沿用默认 system prompt + 正常历史 messages,末尾追加一条 user(`server/templates/compress-prompt.txt` 原文,参考标题回合的拼法),且不传 tools;回合内首条无 tool_calls 的收尾回复即摘要。(`llm.buildMessages` 仍保留旧库 `summarize_request` 行的处理,仅为历史数据兼容。) -- **图片(多模态)**:`messages.content` 列是 TEXT,含图时存 `{"__blocks__":[content...]}` 哨兵 JSON。新版 `read_file` 读图:sharp 压缩产物落任务目录 `.imgcache/`(前端文件列表隐带点的项),库里只存 `image_ref` 轻量块;`buildMessages` 发送前经调用方传入的 `mintUrl` 回调现签成公网外链(同 `mint_public_link` 那套 `GET /p/`)成 `image_url` 块,base64 不进 DB 也不进请求体;签不到降级为文字占位。**图不塞在 tool 回执里发**(tool 角色带 `image_url` 是非标准形态,大量 OpenAI 兼容上游整批忽略或只认批次最后一张,模型看不到图会反复 read_file 补看成死循环):回执降级为纯文本,未消费的图统一并入该批回执之后的一条 `user` 消息,每张图前配一行对应回执文字标签;旧库/用户粘贴附件的 `data:` URL 块原样透传。图块**只保留最后一条 assistant 之后的**(`lastAssistant` 判定),之前的换成"已省略"文字描述(措辞不催促重读);**每次模型调用最多携带一张图**——改 user 合并形态后实测多图仍只认最后一张(上游硬限制,换形态绕不过),故 engine 按批次限流:一批里只放行第一张图,其余降级为文字让模型下一轮单独重读(逐轮收敛),叠加同回合同图只投递一次;发送前 `log.debug('req', 发送形态...)` 打每轮图块计数,一眼区分发送侧漏拼与上游吞图。UI 渲染走带 cookie 的会话内下载路由,历史永不裂图。 +- **图片(多模态)**:`messages.content` 列是 TEXT,含图时存 `{"__blocks__":[content...]}` 哨兵 JSON。新版 `read_file` 读图:sharp 压缩产物落任务目录 `.imgcache/`(前端文件列表隐带点的项),库里只存 `image_ref` 轻量块;`buildMessages` 发送前经调用方传入的 `mintUrl` 回调现签成公网外链(同 `mint_public_link` 那套 `GET /p/`)成 `image_url` 块,base64 不进 DB 也不进请求体;签不到降级为文字占位。**图不塞在 tool 回执里发**(tool 角色带 `image_url` 是非标准形态,大量 OpenAI 兼容上游整批忽略或只认批次最后一张,模型看不到图会反复 read_file 补看成死循环):回执降级为纯文本,未消费的图统一并入该批之后的一条 `user` 消息(逐图对应说明合并置顶为一段文字、图块按回执顺序紧随——对齐官方示例排布;探针实测 DS 对交替排布也兼容,取低风险形态),并附「先逐张简述每图内容再继续任务」指令兼作送达自检;旧库/用户粘贴附件的 `data:` URL 块原样透传。图块**保留到最后一条收尾 assistant(无 tool_calls)之前**(`lastAssistant` 判定)——只发 tool_calls 的中间轮不算已阅、图继续携带(实测过图已进上下文而模型仍自述没看到的行为,鲁棒优先于极致省 token);更早的换成"已省略"文字描述(措辞不催促重读);同回合同一图只投递一次(`run.imgDelivered` 去重,再读同图只回文字提示;多图同请求经探针实测可行,曾按批限"每轮一张"已撤);发送前 `log.debug('req', 发送形态...)` 打每轮图块计数,一眼区分发送侧漏拼与上游吞图。UI 渲染走带 cookie 的会话内下载路由,历史永不裂图。 - **key 共享并发,无租约**:`model_pool.is_busy`/`current_session_id` 已废弃不再读写(旧库残留列,启动时清零);同一 key 可被多个会话同时绑定并发 looping(上游 key 本身支持多并发)。held 不再自动到期,顶部「保持中 · 模型」持续展示,唯一出口是手动「断开」或换绑。 - **task_brief(任务书锚点,advising→executing 切换)**:runLoopInner 工具批跑完后,若 advising 回合内有 `handoff` 成功返回(brief 已由 handler 原样落盘根 task.md 并记 files 表;批量末尾统一切,防父 assistant 先存档、后落库回执成孤儿行被上游拒收;同批多次 handoff 后写覆盖 last-wins),`enterExecuting` 当场重建上下文:全史标 `archived` → 插一条 `type='task_brief'` user 行(内容 = task.md 磁盘快照,非引用)→ phase='executing' + SSE `phase`/`status` 事件;下一迭代重读历史 + 重解 profile,天然切默认组合、同回合开工。压缩不碰 phase(task_brief 与其它历史一样会被后续压缩存档,漂移可控:压缩本就由用户主导)。 - **profile(prompt+tools 组合)**:顶层 `model_profiles` 定义多套组合,`platforms[].models[].profile` 引用(见 §5.8)——这是唯一的引用来源:运行期手动切换已全部移除(消息级 profile 参数、`sessions.profile` 会话绑定均废弃,列保留不读写);`advising` 例外,不走引用、由 phase 强制命中。名单外工具被调用不拦(`checkToolArgs` 查不到 def 不报错,`executeTool` 全表照跑),但阶段契约类例外:advising 内 `write_file`/`edit_file` 在批内挡下、`handoff` 在 handler 里带 phase 守卫;tools schema 只活在请求体不进历史,所以切换不脏化旧消息。压缩回合同样跟随(小模型会话点压缩不会回退到默认大模板)。 @@ -767,7 +767,7 @@ sequenceDiagram 4. **session.id 序号不复用** —— `genTaskId` 取历史最大 + `meta.task_seq` 取大;删会话后序号不回收。 5. **held 的语义** —— held = 「回合已收尾,绑定持续展示」,无排队/租约含义、不会自动到期;completed = 手动「断开」,cancelled = 手动终止;三态 UI 仍需区分,但都不影响模型可用性(key 共享)。 6. **errAck 误判** —— 弱模型会把参数多包一层 `{"arguments":{...}}`,`unwrapToolArgs` 自动解包;`checkToolArgs` 只看 required 字段是否在顶层。 -7. **图片上下文省钱与防循环** —— `lastAssistant` 之前的图发请求时被换成文字描述(DB 存全量,UI 历史重渲染仍能看图;要看原图可 `read_file` 重读,新回执会重新投递)。两条铁律(线上死循环实测复盘):① tool 回执夹图会被兼容差的上游静默吞掉,必须走批次后 `user` 合并消息;② 改成 user 形态后多图仍只认最后一张(上游硬限制),所以每次模型调用最多携带一张图(engine 按批限流、同回合同图去重),一切"请重新读取"式催读文案必须删掉。发送形态看 `log.debug('req', 发送形态...)`。 +7. **图片上下文省钱与防循环** —— `lastAssistant` 之前的图发请求时被换成文字描述(DB 存全量,UI 历史重渲染仍能看图;要看原图可 `read_file` 重读,新回执会重新投递)。两条铁律(线上死循环实测复盘):① tool 回执夹图会被兼容差的上游静默吞掉,必须走批次后 `user` 合并消息;② 上游对 user 合并形态(单消息多图、公网外链、attachment 响应头、自签 https)经探针矩阵实测全部兼容——"多张看不见"的真凶是 tool 夹图时代与弱模型行为惯性,不是多图限制;对策 = 同回合同图去重 + 不催促重读文案 + 合并消息「先逐张简述再继续」送达自检。诊断三源交叉:`log.debug('req', 发送形态...)` 看拼没拼上图、`public-file 外部取用` 日志看上游拉没拉、usage.pt 增量(每图数百~1024 tok)看图进没进上下文。 8. **SSE 被 nginx-proxy 缓冲** —— 必须 `proxy_buffering off`;否则 `assistant_delta` 攒到响应结束才一次性下发,体感卡死。 9. **cookie 兜底(APK 场景)** —— WebView 杀进程后 cookie 不一定落盘,登录响应回 `token` 让前端存 localStorage,下次冷启动调 `/api/login_restore` 恢复。 10. **MCP session 过期** —— 第一次 `tools/call` 可能 400 + 含 "session",`mcp.js` 自动重 initialize 后重试一次;日志会打 warn。