优化任务文件窗口显示
This commit is contained in:
+25
-11
@@ -4,6 +4,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { buildMessages, callModel, encodeBlocks, compressMessages, titleMessages } = require('./llm');
|
||||
const { executeTool, resolveInTask } = require('./tools/executor');
|
||||
const publicFiles = require('./public-files');
|
||||
const mcp = require('./mcp');
|
||||
const log = require('./log');
|
||||
|
||||
@@ -513,10 +514,20 @@ async function runLoopInner(sessionId, run) {
|
||||
// 压缩回合(run.summarizing = 由「压缩」按钮发起、尚未产出摘要):
|
||||
// 沿用默认 system prompt + 正常历史,末尾追加一条压缩指令 user(见 llm.compressMessages);
|
||||
// 且不传 tools,模型只能输出摘要文本。
|
||||
// 发送前为历史里的 image_ref 块现签公网外链(GET /p/<id>,同 mint_public_link):
|
||||
// 每次请求重签,回合内多轮迭代/重试永不过期;DB 只存几十字符的 rel,base64 不进库不进请求体。
|
||||
// base_url 未配/mint 异常时返回 null,buildMessages 降级为文字占位。
|
||||
const mintImageUrl = (rel) => {
|
||||
const pl = cfg.public_link || {};
|
||||
if (!pl.base_url) return null;
|
||||
try {
|
||||
return pl.base_url + '/p/' + publicFiles.mint({ sessionId: sessionId, rel, ttlMs: pl.ttl_ms });
|
||||
} catch (_) { return null; }
|
||||
};
|
||||
const compressing = !!run.summarizing;
|
||||
const messages = compressing
|
||||
? compressMessages(session, (cfg.agent || {}).language)
|
||||
: buildMessages(session, (cfg.agent || {}).language);
|
||||
? compressMessages(session, (cfg.agent || {}).language, mintImageUrl)
|
||||
: buildMessages(session, (cfg.agent || {}).language, mintImageUrl);
|
||||
// 内置工具 + 启动时发现的 MCP 工具,一起随 system prompt 发给模型(压缩回合不发)
|
||||
const tools = compressing ? [] : TOOL_DEFINITIONS.concat(mcp.toolDefinitions());
|
||||
|
||||
@@ -645,30 +656,33 @@ async function runLoopInner(sessionId, run) {
|
||||
isError = true;
|
||||
}
|
||||
}
|
||||
// 工具可返回 {text, image_data_url}(read_file 读图且模型支持 vision):
|
||||
// 落库时把图片以 image_url 内容块拼进 tool 消息(哨兵 JSON,见 llm.js encodeBlocks),
|
||||
// buildMessages 发请求前还原为 OpenAI 内容块数组。
|
||||
// 工具可返回 {text, image_rel}(read_file 读图且模型支持 vision,压缩产物在 .imgcache/):
|
||||
// 落库时以 image_ref 内容块拼进 tool 消息(哨兵 JSON,见 llm.js encodeBlocks),
|
||||
// buildMessages 发请求前现签成公网外链的 image_url 块;前端工具卡走带 cookie 的下载路由渲染。
|
||||
let outText;
|
||||
let imageDataUrl = null;
|
||||
if (output && typeof output === 'object' && output.image_data_url) {
|
||||
let imageRel = null;
|
||||
if (output && typeof output === 'object' && output.image_rel) {
|
||||
outText = String(output.text || '');
|
||||
imageDataUrl = String(output.image_data_url);
|
||||
imageRel = String(output.image_rel);
|
||||
} else {
|
||||
outText = String(output == null ? '' : output);
|
||||
}
|
||||
if (run.cancelled && !isError) outText = (outText ? outText + '\n' : '') + '(用户已终止任务)';
|
||||
log.debug('tool', sessionId + ' ' + tc.function.name + (isError ? ' 失败: ' : ' 完成: ') + outText);
|
||||
const toolContent = imageDataUrl
|
||||
const toolContent = imageRel
|
||||
? encodeBlocks([
|
||||
{ type: 'text', text: outText },
|
||||
{ type: 'image_url', image_url: { url: imageDataUrl } },
|
||||
{ type: 'image_ref', rel: imageRel },
|
||||
])
|
||||
: outText;
|
||||
// 先落库再广播:回执带上消息行 id(msg_id),前端工具卡据此挂「删除本条」按钮
|
||||
const toolMsgId = saveMessage(sessionId, { role: 'tool', tool_call_id: id, name: tc.function.name, content: toolContent, is_error: isError });
|
||||
bus.emit(sessionId, 'tool_result', {
|
||||
tool_call_id: id, name: tc.function.name, content: outText.slice(0, 20000),
|
||||
is_error: isError, image_url: imageDataUrl || undefined, msg_id: toolMsgId,
|
||||
is_error: isError,
|
||||
// 实时工具卡预览图:带 cookie 的会话内下载路由(与历史重渲染同源),非 base64
|
||||
image_url: imageRel ? '/api/sessions/' + encodeURIComponent(sessionId) + '/files/download?path=' + encodeURIComponent(imageRel) : undefined,
|
||||
msg_id: toolMsgId,
|
||||
});
|
||||
}
|
||||
iter++;
|
||||
|
||||
+15
-6
@@ -95,7 +95,11 @@ function cachedDecodeBlocks(session, row) {
|
||||
}
|
||||
|
||||
// 将 DB 消息行转为 OpenAI messages 数组(不含 system,由调用方拼接)。
|
||||
// 省 token:image_url 块仅在其位于最后一条 assistant 消息之后(模型尚未对它回复)时保留;
|
||||
// 图片两种形态:旧库/用户粘贴附件的 image_url 块(data: URL)原样透传;
|
||||
// 新版 read_file 读图存的是 image_ref 块({rel},指向任务目录 .imgcache/ 产物),
|
||||
// 发送前用 mintUrl(rel)(engine 传入的公网链现签回调)换成 image_url 外链块,
|
||||
// 签不到(base_url 未配等)降级为文字占位,绝不把 image_ref 这种非标准块发上游。
|
||||
// 省 token:图块仅在其位于最后一条 assistant 消息之后(模型尚未对它回复)时保留;
|
||||
// 之前的视为已消费,发请求时替换为文字标记。DB 始终存全量:UI 历史照常渲染图片,
|
||||
// 模型如需重看可再次 read_file(新消息在尾部,会重新携带图片)。
|
||||
// 压缩摘要相关行(见 engine.runLoopInner / summarizeContext):
|
||||
@@ -109,7 +113,7 @@ function cachedDecodeBlocks(session, row) {
|
||||
// 关联 tool 回执按 id 一并跳过(否则会留下无 tool_call 配对的孤儿 tool 消息,上游拒收);
|
||||
// 改以一条 user 错误提示替代,让模型看到原因后重新生成工具调用 ——
|
||||
// 坏样本留在上下文里只会被模型继续模仿,反复报同一个错。
|
||||
function buildMessages(session, language) {
|
||||
function buildMessages(session, language, mintUrl) {
|
||||
const messages = [{ role: 'system', content: systemPromptText(language) }];
|
||||
const history = session.history;
|
||||
// 行被删除后清理残留的图片解析缓存条目(只增不清会缓慢泄漏;条数不会超过现存行数)
|
||||
@@ -171,7 +175,7 @@ function buildMessages(session, language) {
|
||||
}
|
||||
// errAck 轮的 tool 回执:随该轮一起丢弃,避免无主 tool 消息
|
||||
if (row.role === 'tool' && dropToolCallIds.has(row.tool_call_id)) return;
|
||||
// tool/user 行:含图哨兵 JSON 还原为内容块(解析结果按行 id 缓存);已消费的图剥掉 base64,只留文字描述 + 标记
|
||||
// tool/user 行:含图哨兵 JSON 还原为内容块(解析结果按行 id 缓存);已消费的图只留文字描述 + 标记
|
||||
const blocks = cachedDecodeBlocks(session, row);
|
||||
let content = row.content || '';
|
||||
if (blocks) {
|
||||
@@ -179,7 +183,12 @@ function buildMessages(session, language) {
|
||||
content = blocks.filter(b => b && b.type === 'text').map(b => b.text).join('\n') +
|
||||
'\n[图片数据已省略:模型此前已识别过本图;如需重新查看请再次调用 read_file]';
|
||||
} else {
|
||||
content = blocks;
|
||||
// 未消费:image_ref → 现签公网外链(每次请求重签,不过期);其余块(含旧 data: URL)原样
|
||||
content = blocks.map(b => {
|
||||
if (!b || b.type !== 'image_ref') return b;
|
||||
const url = mintUrl ? mintUrl(b.rel) : null;
|
||||
return url ? { type: 'image_url', image_url: { url } } : { type: 'text', text: '[图片外链不可用:请重新读取]' };
|
||||
});
|
||||
}
|
||||
}
|
||||
if (row.role === 'tool') {
|
||||
@@ -195,8 +204,8 @@ function buildMessages(session, language) {
|
||||
//(与 buildMessages 同取舍:archived 不发、旧摘要/工具轮照常),末尾追加一条 user
|
||||
//(compress-prompt.txt 原文,历史就在它前面的 messages 里,不再填占位符)。
|
||||
// 调用方(engine.runLoopInner 的 compressing 分支)需同时不传 tools。
|
||||
function compressMessages(session, language) {
|
||||
const messages = buildMessages(session, language);
|
||||
function compressMessages(session, language, mintUrl) {
|
||||
const messages = buildMessages(session, language, mintUrl);
|
||||
messages.push({ role: 'user', content: COMPRESS_PROMPT_TEMPLATE });
|
||||
return messages;
|
||||
}
|
||||
|
||||
@@ -199,7 +199,7 @@
|
||||
<div class="files-panel" id="files-panel" aria-label="任务文件">
|
||||
<div class="files-panel-header">
|
||||
<div class="files-drag-handle" id="files-drag-handle" aria-label="拖拽调整高度"></div>
|
||||
<span class="files-panel-title">任务文件<span class="files-panel-size" id="files-panel-size" title="当前目录下全部文件总大小(含隐藏的 .tmp/.venv)"></span></span>
|
||||
<span class="files-panel-title">任务文件<span class="files-panel-size" id="files-panel-size" title="当前目录下全部文件总大小"></span></span>
|
||||
<label class="file-upload" title="上传文件" aria-label="上传文件">
|
||||
<input type="file" id="file-input" multiple hidden>
|
||||
<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
|
||||
|
||||
@@ -188,10 +188,15 @@
|
||||
if (typeof content === 'string' && content.startsWith('{"__blocks__":')) {
|
||||
try {
|
||||
const blocks = JSON.parse(content).__blocks__ || [];
|
||||
const ref = blocks.find(b => b.type === 'image_ref');
|
||||
const img = blocks.find(b => b.type === 'image_url');
|
||||
return {
|
||||
text: blocks.filter(b => b.type === 'text').map(b => (b.text || '').replace(/,图片见同条消息的 image_url 内容块/g, '')).join('\n'),
|
||||
imageUrl: img && img.image_url && img.image_url.url || null,
|
||||
// 新版存 .imgcache/ 相对路径:渲染走带 cookie 的会话内下载路由(不过期不裂图);
|
||||
// 旧库里的 base64 image_url 块照常直接用
|
||||
imageUrl: ref
|
||||
? '/api/sessions/' + encodeURIComponent(state.sessionId) + '/files/download?path=' + encodeURIComponent(ref.rel)
|
||||
: (img && img.image_url && img.image_url.url || null),
|
||||
};
|
||||
} catch (_) { /* 解析失败按原文显示 */ }
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
const panel = $('files-panel');
|
||||
if (open) {
|
||||
filesCurDir = ''; // 每次弹出回到根目录
|
||||
filesShowHidden = false; // 隐藏文件彩蛋态不跨次记忆,每次打开从干净视图开始
|
||||
applyFilesPanelH(); // 沿用上次拖拽高度(会话内),无则用 CSS 默认
|
||||
loadFiles();
|
||||
// 弹出面板时收起软键盘,避免顶起布局
|
||||
@@ -127,6 +128,7 @@
|
||||
let filesTreeRoot = null; // 最近一次拉取构建的目录树(单层列表渲染与全选/有效性计算都基于它)
|
||||
let filesDirSizes = new Map(); // 目录路径('' = 根) → 其下文件递归总字节;按未过滤原始列表聚合(含隐藏的 .tmp/.venv)
|
||||
let filesCurDir = ''; // 当前浏览目录(相对任务根;'' = 根)。面包屑 + 单层列表的游标
|
||||
let filesShowHidden = false; // 彩蛋:点面板标题旁总大小文本切换 dot 项显隐(后端 ?hidden=1,连 .tmp/.venv 一起放出)
|
||||
|
||||
const dirSelKey = p => DIR_SEL_PREFIX + p;
|
||||
const isDirSelKey = k => k.startsWith(DIR_SEL_PREFIX);
|
||||
@@ -352,7 +354,7 @@
|
||||
if (!node) { filesCurDir = ''; node = filesNodeAt(''); } // 当前目录已被删除 → 退回根
|
||||
const sizeEl = $('files-panel-size');
|
||||
if (!node) { el.innerHTML = ''; if (sizeEl) sizeEl.textContent = ''; return; }
|
||||
// 标题旁总大小:按未过滤的聚合表取当前目录递归总量(.tmp/.venv 隐藏但计数)
|
||||
// 标题旁总大小:按未过滤的聚合表取当前目录递归总量(关彩蛋时服务端不返回 dot 项;开彩蛋时含 .imgcache/.tmp/.venv 全计)
|
||||
if (sizeEl) {
|
||||
const total = filesDirSizes.get(filesCurDir) || 0;
|
||||
sizeEl.textContent = total > 0 ? fmtSize(total) : '';
|
||||
@@ -392,9 +394,11 @@
|
||||
filesTreeRoot = null;
|
||||
updateFilesFooter();
|
||||
try {
|
||||
const files = await req('GET', '/api/sessions/' + state.sessionId + '/files?dirs=1');
|
||||
// 会话级 .tmp(executor 的共享 /tmp 落盘处)与 .venv(Python 虚拟环境)不属于任务产物:列表/选中/下载里隐藏,但计入总大小
|
||||
const shown = files.filter(f => !/^(\.tmp|\.venv)(\/|$)/.test(String(f.filename)));
|
||||
// 彩蛋开启时后端连 dot 项一起列,且不再滤 .tmp/.venv(全量放出)
|
||||
const hiddenQ = filesShowHidden ? '&hidden=1' : '';
|
||||
const files = await req('GET', '/api/sessions/' + state.sessionId + '/files?dirs=1' + hiddenQ);
|
||||
// 会话级 .tmp(executor 的共享 /tmp 落盘处)与 .venv(Python 虚拟环境)不属于任务产物:默认隐藏(老后端兼容兑底;新版关彩蛋时服务端已不返回 dot 项)
|
||||
const shown = filesShowHidden ? files : files.filter(f => !/^(\.tmp|\.venv)(\/|$)/.test(String(f.filename)));
|
||||
// 目录标记行不参与选中/全选/计数,只用来铺树(空文件夹可见)
|
||||
filesAllPaths = shown.filter(f => !(f.dir === true || /\/$/.test(String(f.filename)))).map(f => f.filename);
|
||||
// 重建目录树后只渲染当前目录这一层(后端已按时间倒序,组内再排一次防旧排序缓存)
|
||||
@@ -597,6 +601,13 @@
|
||||
renderFilesDir();
|
||||
});
|
||||
|
||||
// 彩蛋:点面板标题旁的总大小文本 = 切换隐藏文件(dot 项含 .tmp/.venv)显隐。
|
||||
// 故意不加任何光标/文案提示,也不限层级(子目录里点同样生效)。
|
||||
$('files-panel-size').addEventListener('click', () => {
|
||||
filesShowHidden = !filesShowHidden;
|
||||
loadFiles();
|
||||
});
|
||||
|
||||
// 批量下载:选中项含文件夹(含全选后整目录被覆盖的情况)时,整个选择交给后端打包成
|
||||
// 一个 zip 一次下载;纯文件选择保持逐文件直链下载。zip 同样走签名直链(与单文件同链路)。
|
||||
async function bulkZipDownload(paths) {
|
||||
|
||||
@@ -80,7 +80,8 @@ router.get('/:id/files', function (req, res) {
|
||||
const session = engine.getSession(req.params.id);
|
||||
if (!session) return res.status(404).json({ error: '会话不存在' });
|
||||
// ?dirs=1:附带目录标记行,前端任务文件面板用它展示空文件夹(默认不附,老消费者不受影响)
|
||||
res.json(listTaskFiles(engine.taskDirOf(session.id), { dirs: req.query.dirs === '1' }));
|
||||
// ?hidden=1:连 . 开头的文件/目录一起列(含 .tmp/.venv,面板彩蛋「点总大小文本」时用)
|
||||
res.json(listTaskFiles(engine.taskDirOf(session.id), { dirs: req.query.dirs === '1', hidden: req.query.hidden === '1' }));
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: String(err && err.message || err) });
|
||||
}
|
||||
|
||||
@@ -43,11 +43,13 @@ function getMessage(req, res) {
|
||||
//(filename 以 '/' 结尾 + dir:true),使不含任何文件的空夹子也能被前端展示。
|
||||
function listTaskFiles(dir, opts) {
|
||||
const wantDirs = !!(opts && opts.dirs);
|
||||
const wantHidden = !!(opts && opts.hidden); // 勾选「显示隐藏文件」时连同 . 开头的文件/目录一起列(含 .imgcache)
|
||||
const out = [];
|
||||
(function rec(d, rel) {
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { return; }
|
||||
for (const e of entries) {
|
||||
if (!wantHidden && e.name.startsWith('.')) continue; // 默认隐藏点开头项(如 .imgcache/ 读图压缩产物缓存)
|
||||
const abs = path.join(d, e.name);
|
||||
const relPath = rel ? rel + '/' + e.name : e.name;
|
||||
if (e.isDirectory()) {
|
||||
|
||||
@@ -88,8 +88,9 @@ function truncate(text, max) {
|
||||
const AUTO_OUTLINE_SIZE = 16384;
|
||||
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff', '.tif']);
|
||||
|
||||
// read_file 读图(仅当会话绑定的模型 vision: true):sharp 压缩后转 base64 data URL,
|
||||
// 由 engine 拼成下一轮请求里 tool 消息的 image_url 内容块。
|
||||
// read_file 读图(仅当会话绑定的模型 vision: true):sharp 压缩后落盘到任务目录 .imgcache/,
|
||||
// 返回 {text, image_rel};engine 拼成 image_ref 内容块落库,llm.buildMessages 发请求前
|
||||
// 现签成公网外链(GET /p/<id>)进 image_url 块,base64 不再进 DB/请求体。
|
||||
const IMG_MAX_INPUT_BYTES = 50 * 1024 * 1024; // 与上传上限一致
|
||||
const IMG_MAX_SIDE = 2000; // 长边压缩阈值(px)
|
||||
const IMG_JPEG_QUALITY = 80;
|
||||
@@ -139,10 +140,10 @@ function outlineWrapper(outlineText) {
|
||||
'For example, to read a function shown as [L100-150], use start_line: 100 and end_line: 150.';
|
||||
}
|
||||
|
||||
// 用 sharp 压缩(按 EXIF 摆正、长边 ≤2000px、JPEG 质量 80)并转 base64 data URL。
|
||||
// 成功返回 {text, image_data_url},engine 侧拼成 tool 消息的多模态内容块;
|
||||
// 用 sharp 压缩(按 EXIF 摆正、长边 ≤2000px、JPEG 质量 80)并落盘 .imgcache/。
|
||||
// 成功返回 {text, image_rel};产物文件名带源文件指纹(mtime+size),同图重复读复用同一份不增殖。
|
||||
// sharp 缺失或解码失败时退回纯文本提示,不让整个工具回合报错。
|
||||
async function readImageAsBlocks(abs, rel, size) {
|
||||
async function readImageAsBlocks(ctx, abs, rel, size) {
|
||||
let sharp;
|
||||
try { sharp = require('sharp'); }
|
||||
catch (_) { return '[图片文件] ' + rel + '(' + size + ' 字节)。服务端未安装 sharp,无法压缩回传图片内容。'; }
|
||||
@@ -152,10 +153,19 @@ async function readImageAsBlocks(abs, rel, size) {
|
||||
.resize({ width: IMG_MAX_SIDE, height: IMG_MAX_SIDE, fit: 'inside', withoutEnlargement: true })
|
||||
.jpeg({ quality: IMG_JPEG_QUALITY })
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
let st = null;
|
||||
try { st = await fsp.stat(abs); } catch (_) {}
|
||||
const stem = path.basename(rel).replace(/\.[^.]+$/, '').replace(/[^\w.\-\u4e00-\u9fff]/g, '_').slice(0, 60);
|
||||
const cacheRel = '.imgcache/' + (stem || 'img') + '-' + size + '-' + Math.round(st ? st.mtimeMs : 0) + '.jpg';
|
||||
const outAbs = path.join(ctx.taskDir, cacheRel);
|
||||
if (!fs.existsSync(outAbs)) {
|
||||
await fsp.mkdir(path.dirname(outAbs), { recursive: true });
|
||||
await fsp.writeFile(outAbs, r.data);
|
||||
}
|
||||
return {
|
||||
text: '[图片文件] ' + rel + '(原 ' + size + ' 字节,已压缩为 ' + r.info.width + '×' + r.info.height +
|
||||
' JPEG ' + r.data.length + ' 字节)',
|
||||
image_data_url: 'data:image/jpeg;base64,' + r.data.toString('base64'),
|
||||
image_rel: cacheRel,
|
||||
};
|
||||
} catch (err) {
|
||||
return '[图片文件] ' + rel + '(' + size + ' 字节),图片解码/压缩失败:' + (err && err.message || err);
|
||||
@@ -176,7 +186,7 @@ async function toolReadFile(ctx, args) {
|
||||
if (st.size > IMG_MAX_INPUT_BYTES) {
|
||||
return '[图片文件] ' + rel + '(' + st.size + ' 字节)过大(上限 ' + IMG_MAX_INPUT_BYTES + ' 字节),已跳过回传。';
|
||||
}
|
||||
return await readImageAsBlocks(abs, rel, st.size);
|
||||
return await readImageAsBlocks(ctx, abs, rel, st.size);
|
||||
}
|
||||
if (isProbablyBinary(abs)) return '[二进制文件,跳过文本读取] ' + relOf(ctx.taskDir, abs);
|
||||
const text = await fsp.readFile(abs, 'utf8');
|
||||
@@ -754,7 +764,7 @@ const HANDLERS = {
|
||||
};
|
||||
|
||||
// ctx: {sessionId, taskDir, run, cfg, db, vision}
|
||||
// 返回值一般为字符串;read_file 读图且 ctx.vision 为 true 时返回 {text, image_data_url}。
|
||||
// 返回值一般为字符串;read_file 读图且 ctx.vision 为 true 时返回 {text, image_rel}。
|
||||
// 内置工具优先;未命中时交给 MCP 注册表(启动时发现的服务工具)。
|
||||
async function executeTool(baseCtx, name, args) {
|
||||
const handler = HANDLERS[name];
|
||||
|
||||
+8
-5
@@ -130,9 +130,11 @@ async function main() {
|
||||
.map(m => { try { return JSON.parse(m.content); } catch (_) { return null; } })
|
||||
.find(j => j && Array.isArray(j.__blocks__));
|
||||
ok(!!imgTool && imgTool.__blocks__.some(b =>
|
||||
b.type === 'image_url' && String(b.image_url && b.image_url.url).startsWith('data:image/jpeg;base64,')),
|
||||
'tool 消息含压缩后的 image_url 内容块',
|
||||
b.type === 'image_ref' && String(b.rel).startsWith('.imgcache/')),
|
||||
'tool 消息含压缩图的 image_ref 内容块(外链发送时现签,库里不存 base64)',
|
||||
imgTool ? JSON.stringify(imgTool.__blocks__.map(b => b.type)) : '无多模态块');
|
||||
const cacheInPanel = await api('GET', '/api/sessions/' + si.id + '/files');
|
||||
ok(!cacheInPanel.some(f => String(f.filename).startsWith('.imgcache/')), '.imgcache 不进前端文件列表');
|
||||
|
||||
// ---- 2.8 释放后新消息优先回绑上次模型(last_model_id)----
|
||||
console.log('\n[2.8] 优先回绑');
|
||||
@@ -227,15 +229,16 @@ async function main() {
|
||||
ok(fpath.includes('g.txt'), 'find_path 命中', fpath);
|
||||
const esc = await executeTool(ctx, 'read_file', { path: '../outside.txt' }).catch(e => 'ERR:' + e.message);
|
||||
ok(String(esc).includes('越界'), 'read_file 拒绝越界', String(esc));
|
||||
// read_file 读图:非 vision → 文本提示;vision → {text, image_data_url}(依赖 sharp)
|
||||
// read_file 读图:非 vision → 文本提示;vision → {text, image_rel}(依赖 sharp,产物落 .imgcache/)
|
||||
const unitPng = await require('sharp')({ create: { width: 4, height: 4, channels: 3, background: { r: 10, g: 120, b: 200 } } }).png().toBuffer();
|
||||
fs.writeFileSync(path.join(ctx.taskDir, 'pic.png'), unitPng);
|
||||
const imgNoVision = await executeTool(ctx, 'read_file', { path: 'pic.png' });
|
||||
ok(typeof imgNoVision === 'string' && imgNoVision.includes('不支持视觉识别'), 'read_file 非 vision 图片返回文本提示', String(imgNoVision).slice(0, 80));
|
||||
const ctxVision = Object.assign({}, ctx, { vision: true });
|
||||
const imgVision = await executeTool(ctxVision, 'read_file', { path: 'pic.png' });
|
||||
ok(imgVision && typeof imgVision === 'object' && String(imgVision.image_data_url).startsWith('data:image/jpeg;base64,'),
|
||||
'read_file vision 图片返回压缩 data URL', imgVision && imgVision.text ? String(imgVision.text).slice(0, 90) : String(imgVision).slice(0, 90));
|
||||
ok(imgVision && typeof imgVision === 'object' && String(imgVision.image_rel).startsWith('.imgcache/'),
|
||||
'read_file vision 图片返回压缩产物 image_rel', imgVision && imgVision.text ? String(imgVision.text).slice(0, 90) : String(imgVision).slice(0, 90));
|
||||
ok(fs.existsSync(path.join(ctx.taskDir, imgVision.image_rel)), '压缩产物已落盘 .imgcache/');
|
||||
|
||||
// ---- 8. 配置读写 API(阶段 2)----
|
||||
console.log('\n[8] 配置读写');
|
||||
|
||||
@@ -248,7 +248,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;发请求时还原为 OpenAI `image_url` 块,且**只保留最后一条 assistant 之后的图**(`lastAssistant` 判定)—— 之前的图剥 base64 改成"已省略"文字描述,省 token;DB 始终存全量供 UI 重渲染。
|
||||
- **图片(多模态)**:`messages.content` 列是 TEXT,含图时存 `{"__blocks__":[content...]}` 哨兵 JSON。新版 `read_file` 读图:sharp 压缩产物落任务目录 `.imgcache/`(前端文件列表隐带点的项),库里只存 `image_ref` 轻量块;`buildMessages` 发送前经调用方传入的 `mintUrl` 回调现签成公网外链(同 `mint_public_link` 那套 `GET /p/<id>`)填入 `image_url` 块,base64 不进 DB 也不进请求体;签不到降级为文字占位。旧库/用户粘贴附件的 `data:` URL 块原样透传。图块**只保留最后一条 assistant 之后的**(`lastAssistant` 判定),之前的换成"已省略"文字描述;UI 渲染走带 cookie 的会话内下载路由,历史永不裂图。
|
||||
- **保持租约**(`holdSweeper`):sweeper_ms 巡检(默认 10s);held 会话无观看者 idle_release_ms 释放(默认 3 分钟),有观看者 active_max_ms 强制释放(默认 30 分钟)。active 闲置(绑了模型但无 run 在跑、无未回应消息)按相同租约处理。
|
||||
|
||||
### 5.2 `llm.js` —— 上游调用
|
||||
@@ -257,7 +257,7 @@ stateDiagram-v2
|
||||
|---|---|
|
||||
| `systemPromptText(language)` | 拼模板 + 技能列表 + 语言指令;进程内缓存(`_promptTextCache`) |
|
||||
| `setSkillListText(text)` | 技能列表变更后清缓存,强制重拼 |
|
||||
| `buildMessages(session, lang)` | DB 行 → OpenAI messages 数组;处理 summary/archived/errAck/图片消费 |
|
||||
| `buildMessages(session, lang, mintUrl?)` | DB 行 → OpenAI messages 数组;处理 summary/archived/errAck/图片消费;`image_ref` 块用 `mintUrl` 现签成公网 `image_url` 外链 |
|
||||
| `forEachSSEData(res, onEvent, onMeta, onBadData)` | 通用 SSE 帧解析(空行分隔,data: 行 JSON.parse,注释行走 onMeta) |
|
||||
| `callModel(cfg, modelId, messages, tools, opts)` | 一次模型调用;`opts.deepThink` 启用时合并 `thinking_params`;返回 `{content, reasoning, tool_calls, finish_reason, usage, aborted, sseFrames}` |
|
||||
|
||||
@@ -283,7 +283,7 @@ stateDiagram-v2
|
||||
|
||||
| 工具 | 实现要点 |
|
||||
|---|---|
|
||||
| `read_file` | 走 `resolveInTask` 防路径穿越;图像(PNG/JPEG/WebP/GIF/BMP/TIFF)按 vision 能力走 `sharp` 压缩回传 `image_data_url`(长边 ≤ 2000px,JPEG q=0.85);大文本/二进制给 outline;行号前缀格式 "`<6位右对齐行号>\\t<原文>`"(`edit_file` 用) |
|
||||
| `read_file` | 走 `resolveInTask` 防路径穿越;图像(PNG/JPEG/WebP/GIF/BMP/TIFF)按 vision 能力走 `sharp` 压缩后落盘 `.imgcache/` 并回传 `image_rel`(长边 ≤ 2000px,JPEG q=80;文件名带源文件 mtime+size 指纹,重读复用不增殖),发送前由 `llm.buildMessages` 现签成公网外链;大文本/二进制给 outline;行号前缀格式 "`<6位右对齐行号>\\t<原文>`"(`edit_file` 用) |
|
||||
| `write_file` / `edit_file` | `edit_file` 用模糊定位(Zed 风格):先精确匹配,失败后用 Levenshtein DP 找最相似行;`old_text`/`new_text` 协议见 `definitions.json` |
|
||||
| `list_directory` / `create_directory` / `delete_path` / `move_path` / `copy_path` / `find_path` / `grep` | 标准文件操作,全部 `resolveInTask` 约束;`grep` 走 `ripgrep`(`rg`)优先 |
|
||||
| `terminal` | **唯一一个走 executor 的内置工具**(当 `rexec.isRemote(cfg)`);本地分支用 `spawn` + `detached` + 进程组 kill;远端分支 `rexec.run` SSE 收流,结果套上超时/截断/取消注解后 `truncate(text, cfg.terminal.max_output_chars)` 返回 |
|
||||
|
||||
Reference in New Issue
Block a user