1810 lines
93 KiB
JavaScript
1810 lines
93 KiB
JavaScript
// 工具执行器(内置工具)。所有文件路径强制解析到任务目录内(防路径穿越)。
|
||
// 工具名与参数 schema 来自 definitions.json;MCP 工具不在这里,见 ../mcp.js。
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const net = require('net'); // fetch SSRF 防护:IP 字面量/解析结果判私网
|
||
const dns = require('dns').promises; // 同上:主机名 → IP 后统一判定
|
||
const fsp = require('fs').promises;
|
||
const { spawn } = require('child_process');
|
||
const mcp = require('../mcp');
|
||
const skills = require('./skills');
|
||
const Database = require('better-sqlite3'); // db 工具:会话目录下的 data.db(同步 API,与单进程模型契合)
|
||
const TurndownService = require('turndown'); // fetch 工具:HTML→Markdown 用真解析器(内置 htmlparser2,容错截断/畸形文档)
|
||
const rexec = require('../remote-exec');
|
||
const publicFiles = require('../public-files');
|
||
const scheduler = require('../scheduler'); // 只依赖 log/cron-parser/time.js,不成环(engine→executor→scheduler 单向)
|
||
const profile = require('../user-profile'); // profile 工具的数据面(仅 llm/log 依赖,无环)
|
||
const memory = require('../memory'); // recall 工具的数据面(日记翻阅;仅依赖 time.js,无环)
|
||
// lab 的 help 伪工具要读全量定义:与 engine 同路径 require → node 缓存同一对象,单一事实源。
|
||
const BUILTIN_TOOL_DEFS = require('./definitions.json');
|
||
|
||
// ---------- 路径沙箱 ----------
|
||
// 文件工具的可见范围(AGENT_FILE_SCOPE,默认 session):
|
||
// session = 锁在会话目录。与 executor 容器里的物理视图一致,是服务器形态。
|
||
// workspace= 放宽到 workspace_root。本地桌面端形态(不起 executor、单机单用户):
|
||
// AI 要能操作你指定的整个工作目录,而不是它的一个子目录。
|
||
// 纯 env 接线与 EXECUTOR_URL/ASR_URL 同类:这是部署形态,不是平台配置。
|
||
const WIDE_SCOPE = String(process.env.AGENT_FILE_SCOPE || '').trim().toLowerCase() === 'workspace';
|
||
|
||
function resolveInTask(taskDir, p, rootDir) {
|
||
if (typeof p !== 'string' || !p.trim()) throw new Error('路径不能为空');
|
||
const taskRoot = path.resolve(taskDir);
|
||
let abs;
|
||
if (path.isAbsolute(p)) {
|
||
abs = path.normalize(p);
|
||
// /tmp → <taskDir>/.tmp:与 executor 容器的 bind 对齐(容器内 /tmp 即会话 .tmp,
|
||
// terminal 写 /tmp/x,core 侧实体在 <taskDir>/.tmp/x)。先 normalize 再重写,
|
||
// 重写后仍走下方越界校验,无穿越风险。
|
||
// workspace 形态【不重写】:本地 terminal 是真 spawn,写的就是本机 /tmp,
|
||
// 两边必须指向同一处——否则 AI 自己刚写到 /tmp 的文件,自己 read_file 读不到。
|
||
if (!WIDE_SCOPE) {
|
||
if (abs === '/tmp') abs = path.join(taskRoot, '.tmp');
|
||
else if (abs.startsWith('/tmp/')) abs = path.join(taskRoot, '.tmp', abs.slice(5));
|
||
}
|
||
} else {
|
||
// 相对路径永远相对会话目录(AI 的 cwd 就在那里),不随 rootDir 漂移。
|
||
abs = path.resolve(taskRoot, p);
|
||
}
|
||
const root = path.resolve(rootDir || taskRoot);
|
||
const inRoot = abs === root || abs.startsWith(root + path.sep);
|
||
// workspace 形态额外放行本机 /tmp:AI 与 terminal 共用的临时区。
|
||
const inTmp = WIDE_SCOPE && (abs === '/tmp' || abs.startsWith('/tmp/'));
|
||
if (!inRoot && !inTmp) {
|
||
throw new Error((rootDir ? '路径越界(只允许工作目录内操作):' : '路径越界(只允许任务目录内操作):') + p);
|
||
}
|
||
return abs;
|
||
}
|
||
|
||
// 工具层允许的根:session 形态 = 会话目录;workspace 形态 = workspace_root。
|
||
// 只给「业务工具」用;路由层(文件 API/公网短链/data-page)与 @历史会话仍按会话目录校验。
|
||
function fsRoot(ctx) {
|
||
// 手选工作目录的会话:AI 的一切文件操作都在这个真实目录里(本地端,不建 task-* 子目录)。
|
||
// 优先于 WIDE_SCOPE 的 workspace_root 兜底。
|
||
if (ctx.workDir) return ctx.workDir;
|
||
if (!WIDE_SCOPE) return ctx.taskDir;
|
||
return (ctx.cfg && ctx.cfg.workspace_root) || ctx.taskDir;
|
||
}
|
||
|
||
function relOf(taskDir, abs) {
|
||
return path.relative(path.resolve(taskDir), abs) || '.';
|
||
}
|
||
|
||
// 展示用路径:会话目录内保持相对(跟以前一致,省 token);
|
||
// 宽根模式下文件可能在会话目录外,那就回绝对路径——否则模型看到的是
|
||
// ../../../../tmp/x 这种既难读、又容易被它当成会话内路径去二次拼接的名字。
|
||
function dispPath(ctx, abs) {
|
||
const rel = relOf(ctx.taskDir, abs);
|
||
if (rel === '..' || rel.startsWith('..' + path.sep)) return abs;
|
||
return rel;
|
||
}
|
||
|
||
// ---------- 跨会话路径:@<会话id>/<rel>(历史只读,「看一眼」可过墙,「字节落地」只走 copy_path) ----------
|
||
// 背景:terminal 在远端 executor 容器里跑(compose:wrapper 启动即 unmount host-tasks),
|
||
// 别的会话目录在 shell 物理视图里根本不存在;core 进程内的文件工具又被 resolveInTask
|
||
// 锁死本会话。跨会话只有这一个解析口子,同用户校验单点在此(承自 recall 旧 files/link,
|
||
// 那两个 op 是 ls/mint 的沙箱外克隆,已整删——克隆会漂移:link 漏抄 mint 的 realpath 防线)。
|
||
// 接受 @ 的三个入口都是只读语义:list_directory(列举)、read_file(读文本进上下文)、
|
||
// copy_path 的 source_path(导入)。写侧 write_file / edit_file / copy_path 目标一律显式拒绝,
|
||
// 否则 '@task-x/y' 会被 resolveInTask 当相对路径、在本会话里造出字面 '@task-x' 目录。
|
||
const PAST_RE = /^@([^\s/]+)(?:\/([\s\S]*))?$/;
|
||
function resolvePastPath(ctx, p) {
|
||
const m = PAST_RE.exec(p);
|
||
if (!m) throw new Error('@ 路径格式: @<session-id>/<rel>, 如 @task-20260929-003/out.png');
|
||
const sid = m[1];
|
||
const rel = m[2] || '.';
|
||
if (!/^task-[0-9A-Za-z_\-]+$/.test(sid)) throw new Error('@ 后需会话 id, 形如 task-YYYYMMDD-NNN: ' + sid);
|
||
const s = ctx.db.prepare('SELECT id, user, title, work_dir FROM sessions WHERE id = ?').get(sid);
|
||
if (!s) throw new Error('会话不存在: ' + sid);
|
||
const me = ctx.db.prepare('SELECT user FROM sessions WHERE id = ?').get(ctx.sessionId);
|
||
if (String(s.user || '') !== String((me && me.user) || '')) throw new Error('无权访问该会话: ' + sid);
|
||
// 目标会话若手选了工作目录,@<会话> 也必须指向那个真实目录,而不是 workspace_root/<id>。
|
||
const wd = String(s.work_dir || '');
|
||
const root = String((ctx.cfg && ctx.cfg.workspace_root) || '');
|
||
const dir = wd || (root ? path.join(root, sid) : '');
|
||
if (!dir) throw new Error('workspace_root 未配置');
|
||
return { sid: sid, title: s.title || sid, dir: dir, abs: resolveInTask(dir, rel) };
|
||
}
|
||
|
||
// list_directory 单层展示上限 / copy_path 单次导入预算(文件数 + 字节)
|
||
const LIST_MAX_ENTRIES = 200;
|
||
const COPY_MAX_FILES = 200;
|
||
const COPY_MAX_BYTES = 200 * 1048576;
|
||
|
||
// 目录源先整趟预算:计数、累字节、遇符号链接即拒(防沿链接跳出源目录把 core 文件系统拽进任务目录)。
|
||
async function walkCopyBudget(srcAbs) {
|
||
let n = 0; let bytes = 0;
|
||
const stack = [srcAbs];
|
||
while (stack.length) {
|
||
const d = stack.pop();
|
||
const entries = await fsp.readdir(d, { withFileTypes: true });
|
||
for (const e of entries) {
|
||
const abs = path.join(d, e.name);
|
||
if (e.isSymbolicLink()) {
|
||
throw new Error('源含符号链接, 拒绝拷贝: ' + path.relative(srcAbs, abs));
|
||
}
|
||
if (e.isDirectory()) stack.push(abs);
|
||
else if (e.isFile()) {
|
||
n++; bytes += (await fsp.stat(abs)).size;
|
||
if (n > COPY_MAX_FILES || bytes > COPY_MAX_BYTES) {
|
||
throw new Error('源过大, 上限 ' + COPY_MAX_FILES + ' 文件 / ' + Math.round(COPY_MAX_BYTES / 1048576) + ' MB');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return { files: n, bytes: bytes };
|
||
}
|
||
|
||
function isProbablyBinary(abs) {
|
||
let fd;
|
||
try {
|
||
fd = fs.openSync(abs, 'r');
|
||
const buf = Buffer.alloc(8192);
|
||
const bytes = fs.readSync(fd, buf, 0, buf.length, null);
|
||
if (bytes === 0) return false;
|
||
const slice = buf.slice(0, bytes);
|
||
return slice.includes(0);
|
||
} catch (_) {
|
||
return true;
|
||
} finally {
|
||
if (fd !== undefined) try { fs.closeSync(fd); } catch (_) {}
|
||
}
|
||
}
|
||
|
||
function truncate(text, max) {
|
||
if (text.length <= max) return text;
|
||
return text.slice(0, max) + '\n...(输出已截断,共 ' + text.length + ' 字符)';
|
||
}
|
||
|
||
// ---------- 各工具实现 ----------
|
||
|
||
// 对齐 Zed:整读时文件字节数超过该阈值则返回大纲(outline),而非截断内容。
|
||
const AUTO_OUTLINE_SIZE = 16384;
|
||
// 全文读/编辑的硬上限:超过即拒绝整读进内存(OOM 防护,st.size 在 read 前就有),引导走 terminal。
|
||
const TEXT_FULL_READ_CAP = 32 * 1024 * 1024;
|
||
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff', '.tif']);
|
||
|
||
// read_file 读图(仅当会话绑定的模型 vision: true):sharp 压缩后落盘到任务目录 .imgcache/,
|
||
// 返回 {text, image_rel};engine 拼成 image_ref 内容块落库,llm.buildMessages 发请求前
|
||
// 现签成公网外链(GET /p/<id>)进 image_url 块,base64 不再进 DB/请求体。
|
||
// text 一律是 imageReceipt 生成的 JSON 对象(字段契约见下),不是散文:
|
||
// 这份回执会被三层改写(executor 产出 / engine 同回合去重 / llm 签外链失败降级),
|
||
// 散文回执让模型只能靠语义猜「到底有没有图」,历史事故是反复 read_file 补看烧 token。
|
||
const IMG_MAX_INPUT_BYTES = 50 * 1024 * 1024; // 与上传上限一致
|
||
const IMG_MAX_SIDE = 2000; // 长边压缩阈值(px)
|
||
const IMG_JPEG_QUALITY = 80;
|
||
|
||
// 简化版符号大纲(Zed 用 tree-sitter,这里用正则提取常见语言的顶层符号 + Markdown 标题)。
|
||
// 返回 "# File outline ..." 文本;无法提取时返回 null(调用方回退到首 1KB)。
|
||
const OUTLINE_RES = [
|
||
/^\s*(?:export\s+default\s+|export\s+|default\s+|pub(?:\([^)]*\))?\s+)?(?:pub\s+)?(?:async\s+)?(?:function|fn|func|def|sub)\s+\*?([A-Za-z0-9_]+)/,
|
||
/^\s*(?:export\s+)?(?:default\s+)?(?:pub(?:\([^)]*\))?\s+)?(?:pub\s+)?(?:abstract\s+|final\s+|open\s+|sealed\s+|data\s+|implicit\s+)*(?:class|struct|trait|interface|enum|impl|namespace|module|type|record|union)\s+([A-Za-z0-9_<>,\[\] ]{1,60}?)(?:\s*[{:<(]|\s*$)/,
|
||
/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z0-9_]+)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z0-9_]+\s*=>)/,
|
||
];
|
||
function buildOutline(absPath, text) {
|
||
const ext = path.extname(absPath).toLowerCase();
|
||
const lines = text.split('\n');
|
||
const items = [];
|
||
if (ext === '.md' || ext === '.markdown' || ext === '.rst') {
|
||
for (let i = 0; i < lines.length; i++) {
|
||
const m = /^(#{1,6})\s+(.*)$/.exec(lines[i]);
|
||
if (m) items.push({ depth: m[1].length - 1, name: m[2].trim().slice(0, 80), line: i + 1 });
|
||
}
|
||
} else {
|
||
for (let i = 0; i < lines.length; i++) {
|
||
for (const re of OUTLINE_RES) {
|
||
const m = re.exec(lines[i]);
|
||
if (m) {
|
||
const indent = (/^[ \t]*/.exec(lines[i])[0] || '').length;
|
||
items.push({ depth: Math.min(8, Math.floor(indent / 2)), name: m[1].trim(), line: i + 1 });
|
||
break;
|
||
}
|
||
}
|
||
if (items.length >= 500) break;
|
||
}
|
||
}
|
||
if (!items.length) return null;
|
||
const body = items.map(it => ' '.repeat(it.depth) + it.name + ' [L' + it.line + ']').join('\n');
|
||
return '# File outline for ' + absPath + '\n\n' + body +
|
||
'\n\nShowing symbols 1-' + items.length + ' (total symbols: ' + items.length + ')\n';
|
||
}
|
||
|
||
// Zed 同款的大纲包裹文案(模型对该格式有既成预期)。
|
||
function outlineWrapper(outlineText) {
|
||
return 'SUCCESS: File outline retrieved. This file is too large to read all at once, so the outline below shows the file\'s structure with line numbers.\n\n' +
|
||
'IMPORTANT: Do NOT retry this call without line numbers - you will get the same outline.\n' +
|
||
'Instead, use the line numbers below to read specific sections by calling this tool again with start_line and end_line parameters.\n\n' +
|
||
outlineText + '\n' +
|
||
'NEXT STEPS: To read a specific symbol\'s implementation, call read_file with the same path plus start_line and end_line from the outline above.\n' +
|
||
'For example, to read a function shown as [L100-150], use start_line: 100 and end_line: 150.';
|
||
}
|
||
|
||
// read_file 图片回执的统一信封。字段是模型唯一可判定的事实,回执不再写中文句子:
|
||
// ok 调用本身是否成功(ok=true + image_attached=false 是合法形态:同回合重复读被去重)
|
||
// path 模型请求的路径(@ 历史形原样保留);投递产物路径只在服务端内部用,不回执
|
||
// image_attached 服务端是否产出了图块、会随本批回执之后的那条 user 消息投递(≠上游已收到)
|
||
// reason 仅 image_attached=false 时有值,稳定枚举(no_vision / too_large / past_session /
|
||
// decode_failed / sharp_missing / already_delivered / link_unavailable)——
|
||
// 模型按它分支,不要读 hint 猜。注意:重放省略像素不属于回执事件,不写 reason。
|
||
// retryable 重试同一调用是否有意义(图片这条路上恒 false:同样的字节只会得到同样的结果)
|
||
// width/height 实际投递的像素尺寸;source_width/height + resized 只在确实缩放过时出现
|
||
// hint 一句人话补充,仅供解释,不承载判定
|
||
function imageReceipt(o) {
|
||
const out = { ok: o.ok === true, tool: 'read_file', kind: 'image', path: o.path, image_attached: o.image_attached === true };
|
||
for (const k of ['reason', 'retryable', 'width', 'height', 'format', 'bytes_in', 'bytes_out',
|
||
'resized', 'source_width', 'source_height', 'hint']) {
|
||
if (o[k] !== undefined) out[k] = o[k];
|
||
}
|
||
return JSON.stringify(out);
|
||
}
|
||
|
||
// 用 sharp 压缩(按 EXIF 摆正、长边 ≤2000px、JPEG 质量 80)并落盘 .imgcache/。
|
||
// 成功返回 {text, image_rel},失败返回 {text}(text 都是 imageReceipt 的 JSON)。
|
||
// 产物文件名带源文件指纹(mtime+size),同图重复读复用同一份不增殖。
|
||
// 无收益守卫(与浏览器端压缩同款):重编码 JPEG 反而 ≥ 原图时不落盘,image_rel 直指原文件。
|
||
// sharp 缺失或解码失败时只回执原因,不让整个工具回合报错。
|
||
async function readImageAsBlocks(ctx, abs, rel, size) {
|
||
let sharp;
|
||
try { sharp = require('sharp'); }
|
||
catch (_) {
|
||
return {
|
||
text: imageReceipt({
|
||
ok: false, path: rel, image_attached: false, reason: 'sharp_missing', retryable: false, bytes_in: size,
|
||
hint: '服务端未安装 sharp,无法压缩回传图片内容',
|
||
}),
|
||
};
|
||
}
|
||
// 源尺寸只读文件头(metadata 不解码像素);EXIF orientation 5-8 表示显示时旋转 90°,
|
||
// 宽高要交换才与模型最终看到的画面一致(sharp 的 rotate() 会真的转)。
|
||
let src = null;
|
||
try {
|
||
const m = await sharp(abs).metadata();
|
||
if (m && m.width && m.height) {
|
||
const swap = Number(m.orientation) >= 5;
|
||
src = { w: swap ? m.height : m.width, h: swap ? m.width : m.height, format: m.format || null };
|
||
}
|
||
} catch (_) { src = null; }
|
||
try {
|
||
const r = await sharp(abs)
|
||
.rotate()
|
||
.resize({ width: IMG_MAX_SIDE, height: IMG_MAX_SIDE, fit: 'inside', withoutEnlargement: true })
|
||
.jpeg({ quality: IMG_JPEG_QUALITY })
|
||
.toBuffer({ resolveWithObject: true });
|
||
if (r.data.length >= size) {
|
||
// 低内容熵图(截图/线稿/纯色)JPEG 重编码可能比原图还大:不产出缓存,外链直接指向原文件
|
||
return {
|
||
text: imageReceipt({
|
||
ok: true, path: rel, image_attached: true,
|
||
width: src ? src.w : undefined, height: src ? src.h : undefined,
|
||
format: src && src.format ? src.format : undefined,
|
||
bytes_in: size, bytes_out: size, resized: false,
|
||
hint: '压缩无收益,按原图回传',
|
||
}),
|
||
image_rel: rel,
|
||
};
|
||
}
|
||
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);
|
||
}
|
||
const receipt = {
|
||
ok: true, path: rel, image_attached: true,
|
||
width: r.info.width, height: r.info.height, format: 'jpeg',
|
||
bytes_in: size, bytes_out: r.data.length,
|
||
resized: src ? (r.info.width !== src.w || r.info.height !== src.h) : undefined,
|
||
};
|
||
if (src) { receipt.source_width = src.w; receipt.source_height = src.h; }
|
||
return { text: imageReceipt(receipt), image_rel: cacheRel };
|
||
} catch (err) {
|
||
return {
|
||
text: imageReceipt({
|
||
ok: false, path: rel, image_attached: false, reason: 'decode_failed', retryable: false, bytes_in: size,
|
||
hint: '图片解码/压缩失败:' + (err && err.message || err),
|
||
}),
|
||
};
|
||
}
|
||
}
|
||
|
||
async function toolReadFile(ctx, args) {
|
||
const p = typeof args.path === 'string' ? args.path.trim() : '';
|
||
const isPast = p.startsWith('@');
|
||
let abs; let disp;
|
||
if (isPast) {
|
||
// 历史会话只读「看一眼」:形状/存在/同用户/沙箱校验全在 resolvePastPath,与另两个 @ 入口同源。
|
||
// 字节不落本会话 → terminal/grep/edit_file 看不见它;图片在此拒绝(见下),要干活仍须 copy_path。
|
||
const past = resolvePastPath(ctx, p);
|
||
abs = past.abs;
|
||
const inner = relOf(past.dir, abs);
|
||
disp = inner === '.' ? '@' + past.sid : '@' + past.sid + '/' + inner;
|
||
} else {
|
||
abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||
// 本会话沿用绝对路径做展示(大纲/首 1KB 头,历史行为不变);历史会话只暴露 @<sid>/<rel> 形,
|
||
// 不把别的会话的 workspace_root 绝对路径喂进上下文。
|
||
disp = abs;
|
||
}
|
||
let st;
|
||
try { st = await fsp.stat(abs); }
|
||
catch (_) { throw new Error('文件不存在:' + p); }
|
||
if (st.isDirectory()) throw new Error(p + ' 是目录不是文件,用 list_directory 查看。');
|
||
if (IMAGE_EXTS.has(path.extname(abs).toLowerCase())) {
|
||
if (isPast) {
|
||
// 不做「偷偷复制」:图片要出现在模型视野里,字节必须落到本会话才能签外链(engine 的
|
||
// mintImageUrl 与前端下载路由都以当前 taskDir 为根),那本质已是一次导入——与其藏进
|
||
// .imgcache 不进文件表,不如让模型明确知道历史图片必须先 copy_path。
|
||
return {
|
||
text: imageReceipt({
|
||
ok: false, path: disp, image_attached: false, reason: 'past_session', retryable: false, bytes_in: st.size,
|
||
hint: '历史会话图片不支持直接读取:先 copy_path(source_path 用这个 @ 路径)导入本会话,再 read_file——导入后图片、terminal、mint 全量生效',
|
||
}),
|
||
};
|
||
}
|
||
const rel = relOf(ctx.taskDir, abs);
|
||
if (!ctx.vision) {
|
||
return {
|
||
text: imageReceipt({
|
||
ok: false, path: rel, image_attached: false, reason: 'no_vision', retryable: false, bytes_in: st.size,
|
||
hint: '当前模型不支持视觉识别,无法回传图片像素;请基于文件名/大小作答,或直接告知用户',
|
||
}),
|
||
};
|
||
}
|
||
if (st.size > IMG_MAX_INPUT_BYTES) {
|
||
return {
|
||
text: imageReceipt({
|
||
ok: false, path: rel, image_attached: false, reason: 'too_large', retryable: false, bytes_in: st.size,
|
||
hint: '超过回传上限 ' + IMG_MAX_INPUT_BYTES + ' 字节;可先用 terminal 缩小(如 ImageMagick)再读',
|
||
}),
|
||
};
|
||
}
|
||
return await readImageAsBlocks(ctx, abs, rel, st.size);
|
||
}
|
||
if (isProbablyBinary(abs)) return '[二进制文件,跳过文本读取] ' + (isPast ? disp : relOf(ctx.taskDir, abs));
|
||
if (st.size > TEXT_FULL_READ_CAP) {
|
||
return '(文件过大:' + Math.round(st.size / 1048576) + ' MB,超过 read_file 全文读取上限 '
|
||
+ (TEXT_FULL_READ_CAP / 1048576) + ' MB,拒绝整读;请用 terminal 的 grep -n / head / sed -n 定位阅读)';
|
||
}
|
||
const text = await fsp.readFile(abs, 'utf8');
|
||
if (!text) return '(空文件)';
|
||
let lines = text.split('\n');
|
||
// CRLF 文件显示层剥去行尾 \r:模型拿到的行更干净;edit_file 精确/模糊匹配与 CRLF 归一不受影响。
|
||
if (text.includes('\r\n')) lines = lines.map(l => (l.endsWith('\r') ? l.slice(0, -1) : l));
|
||
const total = lines.length;
|
||
const startLine = Math.max(1, args.start_line || 1);
|
||
let endLine = args.end_line || total;
|
||
if (startLine > total) return '(文件共 ' + total + ' 行,start_line 超出范围)';
|
||
// 显式拒绝而非 slice 出空串静默返回:空串会让模型误判文件为空/工具坏了而换路重试。
|
||
if (endLine < startLine) throw new Error('end_line 必须 >= start_line(got start_line=' + startLine + ', end_line=' + args.end_line + ')');
|
||
// 对齐 Zed:未指定范围且文件超过 16KB 时返回大纲;提取不到大纲则回退回首 1KB。
|
||
if (!args.start_line && !args.end_line && Buffer.byteLength(text, 'utf8') > AUTO_OUTLINE_SIZE) {
|
||
const outline = buildOutline(disp, text);
|
||
if (outline) return outlineWrapper(outline);
|
||
let head = text.slice(0, 1024);
|
||
try { while (Buffer.byteLength(head, 'utf8') > 1024) head = head.slice(0, -1); } catch (_) {}
|
||
return outlineWrapper('# First 1KB of ' + disp + ' (file too large to show full content, and no outline available)\n\n' + head);
|
||
}
|
||
lines = lines.slice(startLine - 1, Math.min(endLine, total));
|
||
return lines.map((l, i) => String(startLine + i).padStart(6, ' ') + '\t' + l).join('\n');
|
||
}
|
||
|
||
// 对齐 Zed list_directory 的输出格式:
|
||
// # Folders:
|
||
// <dir>/<name>
|
||
//
|
||
// # Files:
|
||
// <dir>/<name>
|
||
// 本会话路径:条目相对任务目录(同旧版)。'@<sid>/<rel>' 历史模式:条目带 '@<sid>/' 全形前缀,
|
||
// 可直接抄进 copy_path 的 source_path——列得出来就导得进来。隐藏项('.' 开头的 .imgcache/
|
||
// .task-history/.tmp 等内部态)不列;确切知道名字时仍可直接把它喂给 copy_path。
|
||
async function toolListDirectory(ctx, args) {
|
||
const p = typeof args.path === 'string' ? args.path.trim() : '';
|
||
let abs; let prefix;
|
||
if (p.startsWith('@')) {
|
||
const past = resolvePastPath(ctx, p);
|
||
abs = past.abs;
|
||
const inner = relOf(past.dir, abs);
|
||
prefix = '@' + past.sid + (inner === '.' ? '/' : '/' + inner + '/');
|
||
} else {
|
||
abs = resolveInTask(ctx.taskDir, p || '.', fsRoot(ctx));
|
||
const inner = relOf(ctx.taskDir, abs);
|
||
prefix = inner === '.' ? '' : inner + '/';
|
||
}
|
||
let entries;
|
||
try {
|
||
entries = await fsp.readdir(abs, { withFileTypes: true });
|
||
} catch (e) {
|
||
if (e.code === 'ENOENT') throw new Error('目录不存在: ' + p);
|
||
throw e;
|
||
}
|
||
const dirs = []; const files = [];
|
||
for (const e of entries) {
|
||
if (e.name.startsWith('.')) continue;
|
||
(e.isDirectory() ? dirs : files).push(prefix + e.name);
|
||
}
|
||
dirs.sort(); files.sort();
|
||
const total = dirs.length + files.length;
|
||
if (total === 0) return '目录为空';
|
||
const shownDirs = dirs.slice(0, LIST_MAX_ENTRIES);
|
||
const shownFiles = files.slice(0, LIST_MAX_ENTRIES - shownDirs.length);
|
||
const sections = [];
|
||
if (shownDirs.length) sections.push('# Folders:\n' + shownDirs.join('\n'));
|
||
if (shownFiles.length) sections.push('# Files:\n' + shownFiles.join('\n'));
|
||
let out = sections.join('\n\n');
|
||
if (shownDirs.length + shownFiles.length < total) out += '\n\n...(' + total + ' entries total, truncated)';
|
||
return out;
|
||
}
|
||
|
||
// copy_path:普通复制 + 历史成果的唯一「落地」进口。源可 '@<sid>/<rel>'(同用户校验在 resolvePastPath);
|
||
// 目标永不接受 @——历史只读、写只进本会话。「导入后文件即本地」仍是完整能力的前提:
|
||
// terminal/grep 检索、edit_file 修改、vision 回图、mint 外链都只对本地文件生效(read_file 可只读
|
||
// 窥看历史文本,但不落盘,替代不了导入)。撞名拒绝覆盖(保用户现作)。
|
||
async function toolCopyPath(ctx, args) {
|
||
const sp = String(args.source_path || '').trim();
|
||
const dp = String(args.destination_path || '').trim();
|
||
if (!sp || !dp) throw new Error('source_path 与 destination_path 都必填');
|
||
if (dp.startsWith('@')) throw new Error('destination_path 不支持 @ (历史只读)');
|
||
const root = fsRoot(ctx);
|
||
const dst = resolveInTask(ctx.taskDir, dp, root);
|
||
if (path.resolve(dst) === path.resolve(root)) throw new Error('destination_path 不能是任务目录本身');
|
||
let src;
|
||
if (sp.startsWith('@')) {
|
||
const past = resolvePastPath(ctx, sp);
|
||
src = past.abs;
|
||
} else {
|
||
src = resolveInTask(ctx.taskDir, sp, root);
|
||
}
|
||
if (path.resolve(src) === path.resolve(dst)) throw new Error('源与目标相同');
|
||
let lst;
|
||
try {
|
||
lst = await fsp.lstat(src);
|
||
} catch (_) {
|
||
throw new Error('源不存在: ' + sp);
|
||
}
|
||
if (lst.isSymbolicLink()) throw new Error('源是符号链接: ' + sp);
|
||
let budget = null;
|
||
if (lst.isFile()) {
|
||
if (lst.size > COPY_MAX_BYTES) throw new Error('源文件超限: ' + Math.round(lst.size / 1048576) + ' MB, 上限 ' + Math.round(COPY_MAX_BYTES / 1048576) + ' MB');
|
||
} else if (lst.isDirectory()) {
|
||
budget = await walkCopyBudget(src);
|
||
} else {
|
||
throw new Error('源不是文件或目录: ' + sp);
|
||
}
|
||
let exists = true;
|
||
try { await fsp.stat(dst); } catch (_) { exists = false; }
|
||
if (exists) throw new Error('目标已存在, 拒绝覆盖: ' + dispPath(ctx, dst));
|
||
await fsp.mkdir(path.dirname(dst), { recursive: true });
|
||
await fsp.cp(src, dst, { recursive: true });
|
||
recordFile(ctx, dst); // 文件表只记普通文件(目录自然跳过),供前端/微信附件展示
|
||
const sizeNote = budget ? ' (' + budget.files + ' files, ' + Math.round(budget.bytes / 1024) + ' KB)' : '';
|
||
return '已复制 ' + sp + ' -> ' + dispPath(ctx, dst) + sizeNote;
|
||
}
|
||
|
||
async function toolWriteFile(ctx, args) {
|
||
if (String(args.path || '').trim().startsWith('@')) throw new Error('write_file 不支持 @ 路径(历史只读;要改旧成果先 copy_path 导入本会话)');
|
||
const abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||
// 纵深防御:引擎 checkToolArgs 已把 null 判缺,但直调 executor(测试等)不经过它;
|
||
// 旧版 `?? ''` 会把 null 洗成空串静默清空已有文件,这里显式拒绝。
|
||
if (args.content == null) throw new Error('write_file 缺少参数 content(写空文件请显式传空字符串 "")');
|
||
let st = null;
|
||
try { st = await fsp.stat(abs); } catch (_) {}
|
||
if (st && st.isDirectory()) throw new Error('无法写入:路径是目录 ' + args.path);
|
||
await fsp.mkdir(path.dirname(abs), { recursive: true });
|
||
await fsp.writeFile(abs, String(args.content), 'utf8');
|
||
recordFile(ctx, abs);
|
||
const nbytes = Buffer.byteLength(String(args.content), 'utf8');
|
||
const rel = dispPath(ctx, abs);
|
||
// 区分新建/覆盖:「原 M 字节」是给模型的止损信号(盲覆盖大文件时能立刻察觉)。
|
||
return st
|
||
? '已覆盖文件 ' + rel + '(' + nbytes + ' 字节,原 ' + st.size + ' 字节)'
|
||
: '已创建文件 ' + rel + '(' + nbytes + ' 字节)';
|
||
}
|
||
|
||
// ---------- edit_file 匹配(对齐 Zed edit_session/streaming_fuzzy_matcher 的终止态语义) ----------
|
||
// Zed 常量:替换代价 1,插入(buffer 多余行)3,删除(query 行未命中)10;模糊相似阈值 0.8。
|
||
const COST_REP = 1, COST_INS = 3, COST_DEL = 10, FUZZY_THRESHOLD = 0.8;
|
||
const FUZZY_DP_CELL_LIMIT = 8_000_000; // 超大文件跳过 DP,退回逐行 trim 扫描
|
||
|
||
// normalized Levenshtein 相似度(1 - lev/max_len),先做长度粗筛。
|
||
// DP 工作集复用模块级 buffer:lineSimilarity 无递归/无重入(单线程下安全),
|
||
// 避免 fuzzyLocate m×n 内层每格新建两个 typed array(触顶时是千万次临时分配)。
|
||
let simPrev = null, simCurr = null;
|
||
function lineSimilarity(a, b) {
|
||
if (a === b) return 1;
|
||
const la = a.length, lb = b.length, max = Math.max(la, lb);
|
||
if (max === 0) return 1;
|
||
if (1 - Math.abs(la - lb) / max < FUZZY_THRESHOLD) return 0;
|
||
if (!simPrev || simPrev.length < lb + 1) {
|
||
simPrev = new Int32Array(lb + 1);
|
||
simCurr = new Int32Array(lb + 1);
|
||
}
|
||
let prev = simPrev, curr = simCurr; // 下面的交换只换局部引用,不动模块级变量
|
||
for (let j = 0; j <= lb; j++) prev[j] = j;
|
||
for (let i = 1; i <= la; i++) {
|
||
curr[0] = i;
|
||
const ca = a.charCodeAt(i - 1);
|
||
for (let j = 1; j <= lb; j++) {
|
||
const cost = ca === b.charCodeAt(j - 1) ? 0 : 1;
|
||
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
|
||
}
|
||
const t = prev; prev = curr; curr = t;
|
||
}
|
||
return 1 - prev[lb] / max;
|
||
}
|
||
|
||
function diagCost(trimOld, trimCur) {
|
||
if (trimOld === trimCur) return 0;
|
||
if (lineSimilarity(trimOld, trimCur) >= FUZZY_THRESHOLD) return COST_REP;
|
||
return COST_DEL + COST_INS;
|
||
}
|
||
|
||
function lineNumberOf(text, idx) {
|
||
let n = 1;
|
||
for (let i = 0; i < idx; i++) if (text.charCodeAt(i) === 10) n++;
|
||
return n;
|
||
}
|
||
|
||
// 全局 DP 对齐(query 行 × buffer 行,逐行 trim 比较)。
|
||
// 返回 { startRow, endRow };找不到返回 null;多个同分候选返回 { ambiguous: [rows] }。
|
||
function fuzzyLocate(curLines, oldLinesTrim) {
|
||
const m = oldLinesTrim.length, n = curLines.length;
|
||
const curTrim = new Array(n);
|
||
for (let c = 0; c < n; c++) curTrim[c] = curLines[c].trim();
|
||
const W = n + 1;
|
||
const INF = Number.POSITIVE_INFINITY;
|
||
let dpPrev = new Float64Array(W), dpCur = new Float64Array(W);
|
||
const dir = new Uint8Array((m + 1) * W); // bit1=diag bit2=up(删 query 行) bit4=left(跳过 buffer 行)
|
||
for (let c = 0; c < W; c++) { dpPrev[c] = c * COST_INS; dir[c] = 4; }
|
||
for (let r = 1; r <= m; r++) {
|
||
dpCur[0] = dpPrev[0] + COST_DEL; dir[r * W] = 2;
|
||
const qt = oldLinesTrim[r - 1];
|
||
for (let c = 1; c <= n; c++) {
|
||
const d = dpPrev[c - 1] + diagCost(qt, curTrim[c - 1]);
|
||
const u = dpPrev[c] + COST_DEL;
|
||
const l = dpCur[c - 1] + COST_INS;
|
||
let best = d, bits = 1;
|
||
if (u < best) { best = u; bits = 2; }
|
||
if (l < best) { best = l; bits = 4; }
|
||
dpCur[c] = best; dir[r * W + c] = bits;
|
||
}
|
||
const t = dpPrev; dpPrev = dpCur; dpCur = t;
|
||
}
|
||
// 末行最小代价的所有列 → 逐列回溯成候选,按 (startRow,endRow) 去重。
|
||
let min = INF;
|
||
for (let c = 1; c <= n; c++) if (dpPrev[c] < min) min = dpPrev[c];
|
||
if (!isFinite(min)) return null;
|
||
const seen = new Set(); const candidates = [];
|
||
for (let c0 = 1; c0 <= n; c0++) {
|
||
if (dpPrev[c0] !== min) continue;
|
||
let r = m, c = c0;
|
||
const pairs = [];
|
||
while (r > 0 && c > 0) {
|
||
const bits = dir[r * W + c];
|
||
if (bits & 1) {
|
||
if (diagCost(oldLinesTrim[r - 1], curTrim[c - 1]) <= COST_REP) pairs.push(c - 1);
|
||
r--; c--;
|
||
} else if (bits & 2) { r--; }
|
||
else { c--; }
|
||
}
|
||
if (!pairs.length) continue;
|
||
// 升序排列并要求连续:不连续区间说明 DP 在中间跳过了无关的 buffer 行(left/13 代价 diag 路径),
|
||
// 整段 splice 会静默删掉这些行——这类候选直接丢弃(上层报找不到,模型补上下文重试)。
|
||
pairs.sort((a, b) => a - b);
|
||
let contiguous = true;
|
||
for (let k = 1; k < pairs.length; k++) {
|
||
if (pairs[k] !== pairs[k - 1] + 1) { contiguous = false; break; }
|
||
}
|
||
if (!contiguous) continue;
|
||
const startRow = pairs[0], endRow = pairs[pairs.length - 1];
|
||
const span = endRow - startRow + 1;
|
||
const ratio = pairs.length / Math.max(span, m);
|
||
if (ratio < FUZZY_THRESHOLD) continue;
|
||
const key = startRow + ':' + endRow;
|
||
if (seen.has(key)) continue;
|
||
seen.add(key);
|
||
candidates.push({ startRow, endRow });
|
||
}
|
||
if (!candidates.length) return null;
|
||
if (candidates.length > 1) return { ambiguous: candidates.map(x => x.startRow + 1) };
|
||
return candidates[0];
|
||
}
|
||
|
||
function indentOf(l) { return /^[ \t]*/.exec(l)[0]; }
|
||
|
||
// 按“缓冲行缩进 - query 行缩进”的差值重排 new_text 缩进(空白行不动)。
|
||
function applyReindent(newLines, delta, ch) {
|
||
if (delta === 0) return newLines;
|
||
return newLines.map(l => {
|
||
if (!l.trim()) return l;
|
||
const ind = indentOf(l);
|
||
const n = Math.max(0, ind.length + delta);
|
||
if (n <= ind.length) return ' '.repeat(n) + l.slice(ind.length);
|
||
return ind + ch.repeat(n - ind.length) + l.slice(ind.length);
|
||
});
|
||
}
|
||
|
||
// 应用单条 edit;失败抛错(含 edit 序号)。对齐 Zed:先精确(含重叠计数,≥2 歧义),
|
||
// 再模糊;匹配区间不含行尾换行;new_text 末尾换行仅当缓冲区该位置后有 \n 时吃掉一个。
|
||
function applyEdit(text, edit, i) {
|
||
const tag = 'edit #' + (i + 1);
|
||
const old_text = edit.old_text, new_text = edit.new_text == null ? '' : String(edit.new_text);
|
||
if (!old_text) throw new Error(tag + ': old_text 不能为空');
|
||
// 尾部行尾换行不计入匹配区间(Zed trailing_line_ending_len)。
|
||
let pat = String(old_text);
|
||
if (pat.endsWith('\r\n')) pat = pat.slice(0, -2);
|
||
else if (pat.endsWith('\n')) pat = pat.slice(0, -1);
|
||
if (!pat) pat = String(old_text);
|
||
// 1) 精确匹配(含重叠)
|
||
const hits = [];
|
||
let from = 0;
|
||
while (hits.length < 2) {
|
||
const idx = text.indexOf(pat, from);
|
||
if (idx < 0) break;
|
||
hits.push(idx); from = idx + 1;
|
||
}
|
||
if (hits.length >= 2) {
|
||
throw new Error(tag + ': old_text 在文件中匹配到多处(第 ' + hits.map(h => lineNumberOf(text, h)).join(', ') +
|
||
' 行附近)。请在 old_text 中包含更多上下文以唯一定位。');
|
||
}
|
||
const newLinesRaw = new_text.split('\n');
|
||
if (hits.length === 1) {
|
||
// 精确匹配:原样替换,不重排缩进(Zed first_line_delta=0,精确下 rest 差值必然 0)。
|
||
const idx = hits[0];
|
||
let repl = new_text;
|
||
// 尾换行摘除:匹配区间后紧跟 \n(或 CRLF 的 \r\n)时吃掉 new_text 的一个尾换行。
|
||
const after = text.charAt(idx + pat.length);
|
||
const afterCRLF = after === '\r' && text.charAt(idx + pat.length + 1) === '\n';
|
||
if (afterCRLF) {
|
||
// 尾随 \r\n 要整对切;只切 \n 会在拼接处留下孤立的 \r
|
||
if (repl.endsWith('\r\n')) repl = repl.slice(0, -2);
|
||
else if (repl.endsWith('\n')) repl = repl.slice(0, -1);
|
||
} else if (after === '\n' && repl.endsWith('\n')) {
|
||
repl = repl.slice(0, -1);
|
||
}
|
||
// CRLF 文件:新内容里的行尾统一成 \r\n。
|
||
if (text.includes('\r\n')) repl = repl.replace(/\r?\n/g, '\r\n');
|
||
// 空 new_text 的整行删除:区间恰好行对齐(前邻行首/换行、后随换行)时把尾随行尾一并吃掉,
|
||
// 对齐 Zed 空 new_text=删零行(否则 JS 语义会留下一个空行)。
|
||
if (repl === '' && (after === '\n' || afterCRLF) &&
|
||
(idx === 0 || text.charAt(idx - 1) === '\n' || text.charAt(idx - 1) === '\r')) {
|
||
return text.slice(0, idx) + text.slice(idx + pat.length + (afterCRLF ? 2 : 1));
|
||
}
|
||
return text.slice(0, idx) + repl + text.slice(idx + pat.length);
|
||
}
|
||
// 2) 模糊匹配(逐行 trim)
|
||
const curLines = text.split('\n');
|
||
const oldLines = pat.split('\n');
|
||
const oldTrim = oldLines.map(l => l.trim());
|
||
let loc = null;
|
||
let usedFallback = false;
|
||
if (oldLines.length * curLines.length <= FUZZY_DP_CELL_LIMIT) {
|
||
loc = fuzzyLocate(curLines, oldTrim);
|
||
} else {
|
||
usedFallback = true;
|
||
// 超大文件降级:逐行 trim 首次命中(旧行为)。
|
||
for (let s = 0; s + oldLines.length <= curLines.length; s++) {
|
||
let ok2 = true;
|
||
for (let j = 0; j < oldLines.length; j++) {
|
||
if (curLines[s + j].trim() !== oldTrim[j]) { ok2 = false; break; }
|
||
}
|
||
if (ok2) { loc = { startRow: s, endRow: s + oldLines.length - 1 }; break; }
|
||
}
|
||
}
|
||
if (!loc) {
|
||
throw new Error(tag + ': 在文件中找不到 old_text(可能已被之前的 edit 修改)。' + (usedFallback
|
||
? '文件过大,本次仅走了降级匹配(逐行 trim 精确相等、无相似度容忍):请核对 old_text 与原文是否逐字一致,或改用 read_file 按行号定位后用 terminal 的 sed 编辑,不要以同一文本反复重试。'
|
||
: '请重新 read_file 获取最新内容后再试。'));
|
||
}
|
||
if (loc.ambiguous) {
|
||
throw new Error(tag + ': old_text 模糊匹配到多处(第 ' + loc.ambiguous.join(', ') +
|
||
' 行附近)。请在 old_text 中包含更多上下文以唯一定位。');
|
||
}
|
||
const { startRow, endRow } = loc;
|
||
// 空 new_text=整行删除:对齐 Zed "".lines() 的零行语义(JS ''.split('\n') 是 1 个空行,会留白);
|
||
// new_text='\n' 仍是「替换为一个空行」,语义不合并。
|
||
let newLines = new_text === '' ? [] : newLinesRaw;
|
||
// 匹配区间后紧跟换行时,吃掉 new_text 的尾换行(防止吞掉行尾)。
|
||
const hasNewlineAfter = endRow < curLines.length - 1 || text.endsWith('\n');
|
||
if (hasNewlineAfter && newLines.length > 1 && newLines[newLines.length - 1] === '') {
|
||
newLines = newLines.slice(0, -1);
|
||
}
|
||
// 缩进差值重排(以首条匹配行为基准)。
|
||
const bufInd = indentOf(curLines[startRow]);
|
||
const qInd = indentOf(oldLines[0]);
|
||
const delta = bufInd.length - qInd.length;
|
||
if (delta !== 0) newLines = applyReindent(newLines, delta, bufInd.includes('\t') ? '\t' : ' ');
|
||
// CRLF 文件:新增行补齐 \r。
|
||
if (text.includes('\r\n')) newLines = newLines.map(l => (l.endsWith('\r') || l === '' ? l : l + '\r'));
|
||
curLines.splice(startRow, endRow - startRow + 1, ...newLines);
|
||
return curLines.join('\n');
|
||
}
|
||
|
||
// 对齐 Zed:edits 顺序应用到内存态;若第 N 条失败,前 N-1 条仍保存落盘,
|
||
// 错误信息告知模型已应用了多少、需重新 read_file。
|
||
async function toolEditFile(ctx, args) {
|
||
if (String(args.path || '').trim().startsWith('@')) throw new Error('edit_file 不支持 @ 路径(历史只读;要改旧成果先 copy_path 导入本会话)');
|
||
const abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||
let st;
|
||
try { st = await fsp.stat(abs); }
|
||
catch (_) { throw new Error('文件不存在:' + args.path); }
|
||
if (st.isDirectory()) throw new Error('无法编辑:路径是目录 ' + args.path);
|
||
// 同 read_file 的 OOM 防护:edit_file 也要全量读入,超限拒操作。
|
||
if (st.size > TEXT_FULL_READ_CAP) throw new Error('文件超过 ' + (TEXT_FULL_READ_CAP / 1048576) + 'MB 全文读取上限,edit_file 拒绝操作;请用 terminal 的 sed 等工具编辑');
|
||
const edits = args.edits || [];
|
||
let text = await fsp.readFile(abs, 'utf8');
|
||
const original = text;
|
||
let applied = 0;
|
||
let failure = null;
|
||
for (let i = 0; i < edits.length; i++) {
|
||
try { text = applyEdit(text, edits[i], i); applied++; }
|
||
catch (err) { failure = err; break; }
|
||
}
|
||
if (text !== original) {
|
||
await fsp.writeFile(abs, text, 'utf8');
|
||
recordFile(ctx, abs);
|
||
}
|
||
if (failure) {
|
||
throw new Error(failure.message + (applied > 0
|
||
? '(前 ' + applied + ' 处编辑已应用并保存,文件已变化,请重新 read_file 后再继续)'
|
||
: '(文件未改动)'));
|
||
}
|
||
return '已成功应用 ' + applied + ' 处编辑到 ' + dispPath(ctx, abs);
|
||
}
|
||
|
||
// 对齐 Zed select_terminal_output_lines:head/tail 各自取行;同时给时中间空一行;不去重叠;0 合法。
|
||
function selectOutput(text, head, tail) {
|
||
const hasH = typeof head === 'number' && isFinite(head);
|
||
const hasT = typeof tail === 'number' && isFinite(tail);
|
||
if (!hasH && !hasT) return text;
|
||
const lines = text.split('\n');
|
||
const parts = [];
|
||
if (hasH) parts.push(lines.slice(0, Math.max(0, Math.floor(head))).join('\n'));
|
||
if (hasT) parts.push(lines.slice(Math.max(0, lines.length - Math.floor(tail))).join('\n'));
|
||
return parts.join('\n\n');
|
||
}
|
||
|
||
// terminal:spawn + 进程组 kill + 超时 + 输出截断
|
||
// 通用终端输出 UI 卡片通道:命令行尾部的 ::ui_card {json}:: 标记行 → 从模型面剥离,整块交 ctx.onCard
|
||
// (与 MCP 回包 ui_card 块同一协议,见 mcp.js:任何命令行都可产卡,不限 officecli 封装层)。
|
||
// JSON 解析失败/无 action/ctx 不带 onCard 时标记行原样保留(宁可见不丢数据)。
|
||
function drainUiCards(text, ctx) {
|
||
if (!text || text.indexOf('::ui_card ') < 0) return text;
|
||
const keep = [];
|
||
for (const line of String(text).split('\n')) {
|
||
const m = /^::ui_card (\{.*\})::$/.exec(line.trim());
|
||
let card = null;
|
||
if (m) { try { card = JSON.parse(m[1]); } catch (_) { card = null; } }
|
||
if (card && typeof card === 'object' && card.action && ctx && typeof ctx.onCard === 'function') {
|
||
try { ctx.onCard(Object.assign({}, card, { from: 'terminal' })); } catch (_) { /* 卡片是增强,不影响工具结果 */ }
|
||
continue;
|
||
}
|
||
keep.push(line);
|
||
}
|
||
return keep.join('\n');
|
||
}
|
||
|
||
async function toolTerminal(ctx, args) {
|
||
const cfg = ctx.cfg;
|
||
const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms;
|
||
const maxChars = cfg.terminal.max_output_chars;
|
||
let cwd = ctx.taskDir;
|
||
if (args.cd) cwd = resolveInTask(ctx.taskDir, args.cd, fsRoot(ctx));
|
||
if (!fs.existsSync(cwd)) throw new Error('工作目录不存在:' + cwd);
|
||
|
||
// 配了 executor.url(或 env EXECUTOR_URL):命令交给远端 agent-executor 执行,文本拼回与本地完全一致。
|
||
if (rexec.isRemote(cfg)) {
|
||
const r = await rexec.run(cfg, { command: args.command, cwd, timeout_ms: timeout, run: ctx.run });
|
||
r.out = drainUiCards(r.out, ctx);
|
||
let text = selectOutput(r.out.replace(/\n+$/, ''), args.head_lines, args.tail_lines);
|
||
if (r.killed_by === 'timeout') {
|
||
text += (text ? '\n' : '') + '(命令超时 ' + timeout + 'ms,已终止;这是超时不是命令本身失败)';
|
||
} else if (r.killed_by === 'cancelled') {
|
||
text += (text ? '\n' : '') + '(用户终止任务,进程被 kill)';
|
||
} else {
|
||
text += (text ? '\n' : '') + '[exit code: ' + r.code + ']';
|
||
}
|
||
if (r.truncated) text += '\n(输出超长,已在 executor 侧截断)';
|
||
return truncate(text || '(无输出)', maxChars);
|
||
}
|
||
|
||
return new Promise((resolve) => {
|
||
const child = spawn('/bin/sh', ['-c', args.command], { cwd, detached: true, env: process.env });
|
||
ctx.run.procs.add(child);
|
||
let out = '';
|
||
let killedBy = null; // 'timeout' | 'cancelled'
|
||
let settled = false;
|
||
|
||
const timer = setTimeout(() => {
|
||
killedBy = 'timeout';
|
||
killGroup(child);
|
||
}, timeout);
|
||
|
||
const onData = (d) => { out += d.toString(); };
|
||
child.stdout.on('data', onData);
|
||
child.stderr.on('data', onData);
|
||
|
||
const finish = (code, extra) => {
|
||
if (settled) return;
|
||
settled = true;
|
||
clearTimeout(timer);
|
||
clearInterval(cancelCheck);
|
||
ctx.run.procs.delete(child);
|
||
// head_lines/tail_lines:对齐 Zed,在原始输出上选段(之前被完全忽略)。
|
||
let text = selectOutput(drainUiCards(out, ctx).replace(/\n+$/, ''), args.head_lines, args.tail_lines);
|
||
if (killedBy === 'timeout') {
|
||
// 超时/终止不是“执行失败”,不报 exit code(避免 -1 误导模型)。
|
||
text += (text ? '\n' : '') + '(命令超时 ' + timeout + 'ms,已终止;这是超时不是命令本身失败)';
|
||
} else if (killedBy === 'cancelled') {
|
||
text += (text ? '\n' : '') + '(用户终止任务,进程被 kill)';
|
||
} else {
|
||
text += (text ? '\n' : '') + '[exit code: ' + code + ']';
|
||
}
|
||
if (extra) text += '\n' + extra;
|
||
resolve(truncate(text || '(无输出)', maxChars));
|
||
};
|
||
child.on('error', err => finish(-1, 'spawn 失败:' + err.message));
|
||
child.on('close', code => finish(killedBy ? -1 : (code === null ? -1 : code)));
|
||
|
||
const cancelCheck = setInterval(() => {
|
||
if (ctx.run.cancelled) { killedBy = 'cancelled'; killGroup(child); }
|
||
}, 200);
|
||
});
|
||
}
|
||
|
||
function killGroup(child) {
|
||
if (!child.pid) return;
|
||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) {
|
||
try { child.kill('SIGKILL'); } catch (__) {}
|
||
}
|
||
}
|
||
|
||
// fetch:抓取并转 Markdown。超时/取消覆盖到 body 读取完成(非仅响应头);
|
||
// 流式读取至多 cfg.fetch.max_bytes 字节(下载上限,宽松);按响应 charset 解码(gbk 等依赖内置 full-icu)。
|
||
// 返回上限与下载解耦(cfg.fetch.max_chars/max_chars_hard):超窗尾部拼 offset 续读提示,
|
||
// 全文缓在 ctx.run 上(回合级),续读不重抓。SSRF 防护:主机名解析结果含私网即拒,重定向逐跳复查。
|
||
// undici 网络错误的 message 恒为 "fetch failed",真因窝在 err.cause 里——不解包模型分不清
|
||
// 域名已死/被拒连/TLS 问题(评审实测:只能靠另跑 curl 才能诊断)。常见码翻成中文直述。
|
||
const FETCH_NET_ERRORS = {
|
||
ENOTFOUND: '域名无法解析(ENOTFOUND,域名可能已不存在)',
|
||
EAI_AGAIN: 'DNS 暂时不可用(EAI_AGAIN,可稍后重试)',
|
||
ECONNREFUSED: '连接被拒绝(ECONNREFUSED,端口未监听)',
|
||
ECONNRESET: '连接被对端重置(ECONNRESET,多为服务端/中间设备拒服务)',
|
||
ETIMEDOUT: '连接超时(ETIMEDOUT)',
|
||
EHOSTUNREACH: '主机不可达(EHOSTUNREACH)',
|
||
ENETUNREACH: '网络不可达(ENETUNREACH)',
|
||
EPIPE: '管道断裂(EPIPE)',
|
||
EPROTO: '协议错误(EPROTO)',
|
||
};
|
||
function describeFetchError(err) {
|
||
const c = err && err.cause;
|
||
const code = c && c.code ? String(c.code).toUpperCase() : '';
|
||
const msg = (c && c.message) ? String(c.message) : String((err && err.message) || err);
|
||
if (FETCH_NET_ERRORS[code]) return FETCH_NET_ERRORS[code];
|
||
if (/self.?signed|certificate|CERT_|UNABLE_TO_/i.test(code + ' ' + msg)) return 'TLS 证书校验失败:' + msg;
|
||
return msg + (code ? '(' + code + ')' : '');
|
||
}
|
||
|
||
function isTextualContentType(ct) {
|
||
if (!ct) return true; // 未声明:先按文本读,读完用 NUL 字节兜底判定
|
||
if (ct.startsWith('text/')) return true;
|
||
if (/^application\/(?:[\w.-]+\+)?(?:json|xml|yaml|x-ndjson|ndjson)\b/.test(ct)) return true;
|
||
if (/^application\/(?:javascript|ecmascript|xhtml\+xml)\b/.test(ct)) return true;
|
||
return false;
|
||
}
|
||
|
||
// ---------- fetch 的 SSRF 防护 ----------
|
||
// 私网/保留地址判定(IPv4:回环/私有/链路本地含云元数据 169.254.169.254/CGNAT/基准测试/文档段/组播及保留;
|
||
// IPv6:未指定/回环/v4-mapped/ULA fc00::/7/链路本地 fe80::/10/组播)。
|
||
function isPrivateIp(ip) {
|
||
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
|
||
if (v4) {
|
||
const a = Number(v4[1]), b = Number(v4[2]);
|
||
if (a === 0 || a === 10 || a === 127) return true;
|
||
if (a === 100 && b >= 64 && b <= 127) return true;
|
||
if (a === 169 && b === 254) return true;
|
||
if (a === 172 && b >= 16 && b <= 31) return true;
|
||
if (a === 192 && (b === 0 || b === 168)) return true;
|
||
if (a === 198 && (b === 18 || b === 19 || b === 51)) return true;
|
||
if (a === 203 && b === 113) return true;
|
||
if (a >= 224) return true;
|
||
return false;
|
||
}
|
||
const s = String(ip).toLowerCase();
|
||
const mapped = s.replace(/^::ffff:/, '');
|
||
if (mapped.includes('.')) return isPrivateIp(mapped);
|
||
if (s === '::' || s === '::1') return true;
|
||
if (/^f[cd][0-9a-f]{2}:/.test(s)) return true;
|
||
if (/^fe[89ab][0-9a-f]:/.test(s)) return true;
|
||
if (/^ff/.test(s)) return true;
|
||
return false;
|
||
}
|
||
|
||
// 主机名 → 全部解析结果逐个判,任一私网即拒(不能假定 undici 会连哪一条记录)。
|
||
// 残余风险:本函数解析后 undici 建连时还会再解析一次,DNS 重绑定理论上可绕过;
|
||
// 目标是拦住直球打内网与重定向借刀这两类主要路径,不承诺硬边界。fetchUserError 标记:
|
||
// 这类已直述清楚的错误不走 describeFetchError 再包一层。
|
||
async function assertFetchTargetAllowed(u, allowPrivate) {
|
||
const host = u.hostname.replace(/^\[|\]$/g, ''); // IPv6 字面量带方括号(URL.hostname 保留)
|
||
if (!host) throw Object.assign(new Error('URL 无主机名:' + u.href), { fetchUserError: true });
|
||
let ips;
|
||
if (net.isIP(host)) ips = [host];
|
||
else {
|
||
let recs;
|
||
try { recs = await dns.lookup(host, { all: true, verbatim: true }); }
|
||
catch (e) { throw Object.assign(new Error('无法解析主机 ' + host + (e && e.code ? '(' + e.code + ')' : '')), { fetchUserError: true }); }
|
||
ips = recs.map(r => r.address);
|
||
}
|
||
if (!allowPrivate && ips.some(isPrivateIp)) {
|
||
throw Object.assign(new Error('SSRF 防护:目标解析到回环/私有/内网地址(' + host + ' → ' + ips.join(', ') + '),拒绝抓取;' +
|
||
'确需抓内网服务请在 config 配 fetch.allow_private: true'), { fetchUserError: true });
|
||
}
|
||
}
|
||
|
||
// ---------- fetch 的回合级缓存 ----------
|
||
// 返回窗截断时把转换后全文挂到 ctx.run(随 run 消亡,不跨轮污染):offset 续读纯本地切片,
|
||
// 不重走网络。键为请求 URL(归一化后);LRU 保留 3 条,每条 ≤ max_bytes,内存上限个位数 MB。
|
||
function fetchCacheGet(run, key) {
|
||
const c = run && run.fetchCache;
|
||
if (!c) return null;
|
||
const e = c.get(key);
|
||
if (e) { c.delete(key); c.set(key, e); } // 命中挪到最近使用端
|
||
return e || null;
|
||
}
|
||
function fetchCacheSet(run, key, entry) {
|
||
if (!run) return;
|
||
if (!run.fetchCache) run.fetchCache = new Map();
|
||
run.fetchCache.set(key, entry);
|
||
while (run.fetchCache.size > 3) run.fetchCache.delete(run.fetchCache.keys().next().value);
|
||
}
|
||
|
||
// 从全文切 [off, off+maxOut) 窗。窗外的元信息统一收进「空行 + --- 分隔线 + 单行方括号」块,
|
||
// 与正文视觉断开;只陈述事实(截断位置、续读游标),用法教学归工具描述,这里不重复。
|
||
// 字节级截断(truncated)时本地「全文」本身就不完整,如实告知末尾缺失,避免模型无限续读。
|
||
function fetchWindow(text, off, maxOut, truncated, maxBytes) {
|
||
let out = '';
|
||
const notes = [];
|
||
if (off >= text.length) {
|
||
notes.push('offset=' + off + ' 超出全文 ' + text.length + ' 字符');
|
||
} else {
|
||
const end = Math.min(text.length, off + maxOut);
|
||
out = text.slice(off, end);
|
||
if (end < text.length) notes.push('全文 ' + text.length + ' 字符,续读 offset=' + end);
|
||
}
|
||
if (truncated) notes.push('源响应体截断于 ' + maxBytes + ' 字节,尾部缺失');
|
||
if (!notes.length) return out;
|
||
// 前置空行:防“HTTP 200\n---”被 Markdown 解析成 setext 标题。
|
||
return out + '\n\n---\n[' + notes.join(' · ') + ']';
|
||
}
|
||
|
||
function charsetOf(ct) {
|
||
const m = /charset\s*=\s*["']?([\w-]+)/i.exec(ct || '');
|
||
return m ? m[1].toLowerCase() : '';
|
||
}
|
||
|
||
// 流式读到 maxBytes 即停;超限 reader.cancel() 主动断开,不再继续下载。
|
||
async function readBodyLimited(stream, maxBytes) {
|
||
const reader = stream.getReader();
|
||
const chunks = [];
|
||
let total = 0;
|
||
let truncated = false;
|
||
try {
|
||
for (;;) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
if (total + value.byteLength > maxBytes) {
|
||
if (maxBytes > total) chunks.push(value.subarray(0, maxBytes - total));
|
||
truncated = true;
|
||
break;
|
||
}
|
||
chunks.push(value);
|
||
total += value.byteLength;
|
||
}
|
||
} finally {
|
||
if (truncated) { try { await reader.cancel(); } catch (_) {} }
|
||
}
|
||
return { buf: Buffer.concat(chunks.map(c => Buffer.from(c))), truncated };
|
||
}
|
||
|
||
async function toolFetch(ctx, args) {
|
||
if (ctx.run.cancelled) throw new Error('已终止');
|
||
let url = String(args.url || '').trim();
|
||
if (!url) throw new Error('fetch 缺少参数 url');
|
||
// 对齐 Zed normalize_url:缺 scheme 时默认补 https://;非 http(s) scheme 仍拒绝。
|
||
if (!/^https?:\/\//i.test(url)) {
|
||
if (/^[a-z0-9+.-]+:\/\//i.test(url)) throw new Error('只支持 http/https URL:' + url);
|
||
url = 'https://' + url;
|
||
}
|
||
const fcfg = (ctx.cfg && ctx.cfg.fetch) || {};
|
||
const timeoutMs = fcfg.timeout_ms || 30000;
|
||
const maxBytes = fcfg.max_bytes || 1024 * 1024;
|
||
// 返回窗与下载上限解耦:下载不进上下文可宽松,返回收紧。模型显式传 max_chars 时夹在硬帽内,
|
||
// 非法值(0/负数/NaN)退回默认。
|
||
const hard = fcfg.max_chars_hard || 64000;
|
||
const want = Math.floor(Number(args.max_chars));
|
||
const maxOut = want > 0 ? Math.min(want, hard) : (fcfg.max_chars || 12000);
|
||
const off = Math.max(0, Math.floor(Number(args.offset)) || 0);
|
||
|
||
// 续读/重复抓:命中回合缓存直接本地切片,不再碰网络(回合内页面陈旧可接受,缓存续读场景)。
|
||
const hit = fetchCacheGet(ctx.run, url);
|
||
if (hit) {
|
||
return truncate('HTTP ' + hit.status + '\n' +
|
||
fetchWindow(hit.text, off, maxOut, hit.byteTruncated, maxBytes), 1024 * 1024);
|
||
}
|
||
|
||
const ctrl = new AbortController();
|
||
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
||
// 与 toolTerminal 同模式:等待中用户取消也能 abort 掉进行中的请求/读流。
|
||
const cancelWatch = setInterval(() => { if (ctx.run.cancelled) ctrl.abort(); }, 200);
|
||
try {
|
||
// redirect:'manual' + 逐跳 SSRF 校验:自动跟随会让外站 302 直接把我们带进内网(SSRF 主路径)。
|
||
let res = null;
|
||
let cur = url;
|
||
for (let hop = 0; ; hop++) {
|
||
await assertFetchTargetAllowed(new URL(cur), !!fcfg.allow_private);
|
||
res = await fetch(cur, {
|
||
signal: ctrl.signal,
|
||
redirect: 'manual',
|
||
headers: { 'User-Agent': 'Mozilla/5.0 (agent-app)' },
|
||
});
|
||
const loc = res.headers.get('location');
|
||
if (!loc || res.status < 300 || res.status >= 400) break; // 非跳转:本跳即终答
|
||
if (hop >= 5) throw Object.assign(new Error('重定向次数超过上限(5 次):' + url), { fetchUserError: true });
|
||
let next;
|
||
try { next = new URL(loc, cur); }
|
||
catch (_) { throw Object.assign(new Error('重定向 Location 非法:' + loc), { fetchUserError: true }); }
|
||
if (next.protocol !== 'http:' && next.protocol !== 'https:') {
|
||
throw Object.assign(new Error('重定向目标不是 http/https:' + next.href), { fetchUserError: true });
|
||
}
|
||
cur = next.href;
|
||
}
|
||
const ct = (res.headers.get('content-type') || '').toLowerCase();
|
||
// 非文本:不读 body,直接回报元信息(避免二进制白下载 + 乱码)。
|
||
if (!isTextualContentType(ct)) {
|
||
const len = Number(res.headers.get('content-length')) || 0;
|
||
return 'HTTP ' + res.status + '\n[非文本响应] content-type=' + ct +
|
||
(len ? ',' + len + ' 字节' : '') + ',未读取内容。';
|
||
}
|
||
if (!res.body) return 'HTTP ' + res.status + '\n(无响应体)';
|
||
|
||
const { buf, truncated } = await readBodyLimited(res.body, maxBytes);
|
||
// content-type 未声明的兜底:前 8KB 含 NUL 判为二进制(与 read_file 的 isProbablyBinary 同口径)。
|
||
if (!ct && buf.subarray(0, 8192).includes(0)) {
|
||
return 'HTTP ' + res.status + '\n[非文本响应] content-type 未声明,body 疑似二进制(' + buf.length + ' 字节),未返回内容。';
|
||
}
|
||
// 按 charset 解码;未知/非法编码名退回 UTF-8,不抛错。
|
||
const charset = charsetOf(ct);
|
||
let text;
|
||
if (!charset || charset === 'utf-8' || charset === 'utf8') {
|
||
text = buf.toString('utf8');
|
||
} else {
|
||
try { text = new TextDecoder(charset, { fatal: false }).decode(buf); }
|
||
catch (_) { text = buf.toString('utf8'); }
|
||
}
|
||
let body;
|
||
if (ct.includes('html')) {
|
||
// DOM 树内存约为原始字节的 3–5 倍:超解析硬帽不再做 DOM 解析,降级轻量剥标签——脏但别空手而归。
|
||
body = buf.length > HTML_PARSE_HARD_CAP
|
||
? '---\n[超解析硬帽 ' + HTML_PARSE_HARD_CAP + ' 字节,降级剥标签]\n\n' + fallbackStripHtml(text)
|
||
: htmlToMarkdown(text, cur); // base=重定向终址:链接绝对化的根
|
||
} else {
|
||
body = text;
|
||
}
|
||
// 字节截断可能切在多字节字符中间,尾部的 U+FFFD 是噪音,去掉。
|
||
if (truncated) body = body.replace(/\uFFFD+$/, '');
|
||
const win = fetchWindow(body, off, maxOut, truncated, maxBytes);
|
||
// 窗后本地还有未读内容才缓存(续读场景);一窗吃下全文的不值得存。
|
||
if (off + maxOut < body.length) {
|
||
fetchCacheSet(ctx.run, url, { status: res.status, text: body, byteTruncated: truncated });
|
||
}
|
||
// engine 不截工具结果;上面的返回窗是主闸门,这行 1MB 字符只是最后兜底。
|
||
return truncate('HTTP ' + res.status + '\n' + win, 1024 * 1024);
|
||
} catch (err) {
|
||
if (err && err.fetchUserError) throw err; // SSRF/重定向等已直述清楚的错误,不再套一层
|
||
// 超时与取消都表现为 signal.aborted(body 读流阶段的报错形态不定,按信号判定最稳)。
|
||
if (ctrl.signal.aborted) {
|
||
if (ctx.run.cancelled) throw new Error('已终止');
|
||
throw new Error('fetch 超时(' + timeoutMs + 'ms):' + url);
|
||
}
|
||
throw new Error('fetch 失败:' + describeFetchError(err));
|
||
} finally {
|
||
clearTimeout(timer);
|
||
clearInterval(cancelWatch);
|
||
}
|
||
}
|
||
|
||
// ---------- HTML → Markdown 转换(turndown:真 DOM 解析器) ----------
|
||
// 为什么不再用正则剥标签:截断的 HTML 让正则方案必然漏——缺 </script> 时 [\s\S]*?<\/\1>
|
||
// 整体失配,半截 JS 源码会当正文漏出;未闭合的开标签残片同理穿过 <[^>]+> 掉进正文。
|
||
// turndown 内置 htmlparser2 按容错规则建树:EOF 前的残文统一归进 script 节点、随节点丢弃。
|
||
// 剥壳/标题/链接绝对化全走 DOM 谓词,不碰字符串;实体解码由解析器完成(decodeEntities 表删)。
|
||
// DOM 树内存约为原始字节的 3–5 倍:响应体超解析硬帽时不做 DOM 解析,降级轻量剥标签(脏但不空手而归)。
|
||
const HTML_PARSE_HARD_CAP = 10 * 1024 * 1024;
|
||
|
||
// 页面外壳标签:正文密度低于信噪比门槛,整块丢。head 不在列——title 子节点还要靠它产出
|
||
// 首行标题,其余 head 子节点(meta/link/base/style/script)已各自在列。
|
||
const HTML_CHROME_TAGS = new Set([
|
||
'script', 'style', 'noscript', 'svg', 'template', 'nav', 'header', 'footer', 'aside',
|
||
'form', 'iframe', 'button', 'input', 'select', 'textarea', 'label', 'meta', 'link', 'base',
|
||
]);
|
||
// class/id 启发式限定块级容器:不限标签会连坐删掉 <p class="comment-text"> 这类正文。
|
||
// 子串匹配保留旧版口径(navbar/comments/ad-slot 等变体都命中),接受误杀换召回。
|
||
const HTML_CHROME_CONTAINERS = new Set(['div', 'section', 'article', 'ul', 'ol', 'main']);
|
||
const HTML_CHROME_CLASS_ID =
|
||
/nav|menu|sidebar|breadcrumb|comment|footer|related|banner|promo|advert|popup|share|subscribe|masthead|cookie|social|toolbar/i;
|
||
|
||
// turndown 的 htmlparser2 不规格化属性名大小写(CLASS= 在 attribs 里就是 CLASS),且 domhandler
|
||
// 的 getAttribute 按精确键查 → 大小写不敏感地扫一遍(标签名不受影响,解析时已统一小写)。
|
||
function domAttr(node, name) {
|
||
const a = node.attribs || {};
|
||
if (a[name] != null) return a[name];
|
||
for (const k in a) { if (k.toLowerCase() === name) return a[k]; }
|
||
return '';
|
||
}
|
||
|
||
// 每次抓取新建实例:链接绝对化要把本次重定向后的终址闭进规则,共享单例会被并发抓取互踩;
|
||
// 构造成本可忽略,解析才是大头。
|
||
function makeTurndown(baseUrl) {
|
||
const td = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced', hr: '---', bulletListMarker: '-' });
|
||
td.remove((node) => {
|
||
if (!node || node.nodeType !== 1) return false;
|
||
const tag = String(node.nodeName).toLowerCase();
|
||
if (HTML_CHROME_TAGS.has(tag)) return true;
|
||
if (!HTML_CHROME_CONTAINERS.has(tag)) return false;
|
||
return HTML_CHROME_CLASS_ID.test(domAttr(node, 'class') + ' ' + domAttr(node, 'id'));
|
||
});
|
||
// <title> → 首行标题(对齐旧版“剥 head 前先取 title”的意图:一行标题是性价比最高的页面身份)。
|
||
td.addRule('pageTitle', {
|
||
filter: 'title',
|
||
replacement: (content) => (content.trim() ? '\n\n# ' + content.trim() + '\n\n' : ''),
|
||
});
|
||
// 相对 href/src 绝对化(对重定向后的终址):相对路径对模型是死链,抓回的 Markdown 里链接
|
||
// 能直接当下一次 fetch 的参数,是换解析器白拿的最大收益。带 scheme 的(含 mailto/data)原样留。
|
||
const abs = (raw) => {
|
||
if (!raw) return '';
|
||
if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) return raw;
|
||
try { return new URL(raw, baseUrl).href; } catch (_) { return raw; }
|
||
};
|
||
td.addRule('absLink', {
|
||
filter: (node) => node.nodeType === 1 && String(node.nodeName).toLowerCase() === 'a' && !!domAttr(node, 'href'),
|
||
replacement: (content, node) => '[' + content + '](' + abs(domAttr(node, 'href')) + ')',
|
||
});
|
||
td.addRule('absImage', {
|
||
filter: (node) => node.nodeType === 1 && String(node.nodeName).toLowerCase() === 'img',
|
||
replacement: (content, node) => {
|
||
const src = domAttr(node, 'src');
|
||
if (!src || /^data:/i.test(src)) return ''; // base64 内联图对模型是纯噪音
|
||
const alt = domAttr(node, 'alt').replace(/[[\]]/g, ' '); // ] 会提前闭合 markdown 链接
|
||
return ' + ')';
|
||
},
|
||
});
|
||
return td;
|
||
}
|
||
|
||
function htmlToMarkdown(html, baseUrl) {
|
||
try {
|
||
return makeTurndown(baseUrl).turndown(html).replace(/\n{3,}/g, '\n\n').trim();
|
||
} catch (_) {
|
||
return fallbackStripHtml(html); // 容错解析是概率性描述不是保证:极端脏数据下宁可脏也不能空
|
||
}
|
||
}
|
||
|
||
// 降级路径(解析抛异常/超解析硬帽):不建 DOM 的轻量剥标签。截断的 script/style 连行尾($)
|
||
// 一起吞,防 JS 体漏成正文;实体不处理,降级产物本就声明了不可靠。
|
||
function fallbackStripHtml(html) {
|
||
return html
|
||
.replace(/<(script|style)[\s\S]*?(?:<\/\1>|$)/gi, '')
|
||
.replace(/<[^>]*>/g, ' ')
|
||
.replace(/[ \t]{2,}/g, ' ')
|
||
.replace(/\n{3,}/g, '\n\n')
|
||
.trim();
|
||
}
|
||
|
||
function recordFile(ctx, abs) {
|
||
try {
|
||
const st = fs.statSync(abs);
|
||
if (!st.isFile()) return;
|
||
// 宽根模式(本地)下写在会话目录之外的文件不进附件表:表里的 filename 是会话相对路径,
|
||
// 存个 '../x' 会让前端按会话去取,最终只能拿到 400。
|
||
const rel = relOf(ctx.taskDir, abs);
|
||
if (rel === '..' || rel.startsWith('..' + path.sep)) return;
|
||
ctx.db.prepare(
|
||
'INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)'
|
||
).run(ctx.sessionId, rel, st.size, Date.now());
|
||
} catch (_) { /* 文件表仅用于展示,失败不影响主流程 */ }
|
||
}
|
||
|
||
// mint_public_link:把当前会话目录里的文件签成一条短命公网链接(由 GET /p/<id> 取用)。
|
||
// 这是唯一的签发入口:与 core 同进程,直接调 publicFiles.mint,不必绕任何 HTTP;
|
||
// 而 ctx.taskDir 就是会话目录,relOf 的结果正是取用侧(routes/public-files.js)要的 rel。
|
||
async function toolMintPublicLink(ctx, args) {
|
||
const pl = (ctx.cfg && ctx.cfg.public_link) || {};
|
||
// 本地桌面形态没有公网前缀,但用户就在这台机器上:回环地址签出来的链接照样点得开。
|
||
// 与 visit_url 的回落同源(都不写配置,靠 HOST 判断形态);容器/服务器形态 HOST 为空
|
||
// → localOrigin 返回 '' → 仍是原来那句报错,行为不变。
|
||
const base = String(pl.base_url || '').replace(/\/+$/, '') || localOrigin(ctx.cfg);
|
||
if (!base) throw new Error('public_link.base_url 未配置,无法签发公网链接');
|
||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||
const rel = relOf(ctx.taskDir, abs);
|
||
if (rel === '.') throw new Error('path 要指向一个文件,不能是任务目录本身');
|
||
let st;
|
||
try { st = fs.statSync(abs); } catch (_) { throw new Error('文件不存在:' + rel); }
|
||
if (!st.isFile()) throw new Error('不是文件:' + rel);
|
||
// 符号链接外泄防护:签出去的链接是公网可拉的,realpath 必须仍在任务目录内。
|
||
const real = fs.realpathSync(abs);
|
||
const rootReal = fs.realpathSync(ctx.taskDir);
|
||
if (!real.startsWith(rootReal + path.sep)) {
|
||
throw new Error('path 经符号链接指向了任务目录之外,拒绝签发');
|
||
}
|
||
const id = publicFiles.mint({ sessionId: ctx.sessionId, rel, ttlMs: pl.ttl_ms });
|
||
return base + '/p/' + id;
|
||
}
|
||
|
||
// schedule:用户全部定时任务的生命周期(op 分派,规范见 docs/tool-design.md)。
|
||
// 任务住会话(表主键 session_id → 每会话至多一条),「哪个任务」就用所属会话 id 指认:
|
||
// id 省略/'0' = 本会话(兼容旧调用);跨会话操作带 op=list 里看到的 id,同用户校验——
|
||
// 用户不切会话,AI 代办一切。create 只落当前会话(定时即下班,建完本会话收口退位成专柜)。
|
||
// 回执只给事实,零教学(怎么做写在 schema description 里,不每次复读):
|
||
// list 紧凑索引/get 全量详情(编号条目 + key=value 分行,时间 ISO+08:00);写操单一行短确认。
|
||
// list 紧凑索引:认任务、看状态够用(name/last_note/prompt 等细节归 get)
|
||
function schedEntry(t, idx) {
|
||
return [
|
||
idx + '. ' + (t.brief || t.title || t.session_id),
|
||
'id=' + t.session_id + (t.current ? '(本会话)' : ''),
|
||
'cron="' + t.cron_expr + '"',
|
||
'next=' + scheduler.fmtIso(t.next_run_at),
|
||
t.last_run_at ? 'last=' + scheduler.fmtIso(t.last_run_at) + ' last_status=' + (t.last_status || '-') : 'last=尚未执行',
|
||
].join('\n');
|
||
}
|
||
// get 详情:索引之上补 name(会话标题)、last_note、prompt(原样全量、fence 包裹为引用数据——
|
||
// 写入侧已有 2 万字硬帽,读取侧再截就废了 get 的存在意义)——详情字段只在这出现
|
||
function schedDetail(t) {
|
||
const clip = s => { s = String(s || '').replace(/\s+/g, ' ').trim(); return s.length > 160 ? s.slice(0, 160) + '…' : s; };
|
||
const lines = ['id=' + t.session_id + (t.current ? '(本会话)' : '')];
|
||
if (t.title) lines.push('name=' + t.title);
|
||
if (t.brief) lines.push('brief=' + t.brief);
|
||
if (t.script) lines.push('script=' + t.script);
|
||
lines.push('cron="' + t.cron_expr + '"');
|
||
lines.push('next=' + scheduler.fmtIso(t.next_run_at));
|
||
if (t.last_run_at) lines.push('last=' + scheduler.fmtIso(t.last_run_at) + ' last_status=' + (t.last_status || '-'));
|
||
else lines.push('last=尚未执行');
|
||
if (t.last_note) lines.push('last_note=' + clip(t.last_note));
|
||
if (t.prompt) {
|
||
// fence 包裹:prompt 本体是指令句式,裸贴会被当成对当前模型的命令;`` 标记把它隔成引用数据。
|
||
// 动态加长防碰撞:AI 写的 prompt 自身常含 ```(代码样例),固定三反引号会被内容提前闭合并逃逸。
|
||
let fence = '```';
|
||
while (t.prompt.includes(fence)) fence += '`';
|
||
lines.push('prompt=' + fence, t.prompt, fence);
|
||
}
|
||
return lines.join('\n');
|
||
}
|
||
function toolScheduleTask(ctx, args) {
|
||
const op = String(args.op || '').trim().toLowerCase();
|
||
const cronExpr = String(args.cron_expr || '').trim();
|
||
const prompt = String(args.prompt || '').trim();
|
||
const db = ctx.db;
|
||
const curUser = () => String((db.prepare('SELECT user FROM sessions WHERE id = ?').get(ctx.sessionId) || {}).user || '');
|
||
// 目标会话解析:无 id → 本会话;有 id → 存在 + 同用户,否则报错(不静默降级,防 AI 拿错目标静默误删)。
|
||
const target = () => {
|
||
const raw = String(args.id == null ? '' : args.id).trim();
|
||
if (!raw || raw === ctx.sessionId) return ctx.sessionId;
|
||
const s = db.prepare('SELECT user FROM sessions WHERE id = ?').get(raw);
|
||
if (!s) throw new Error('id 指向的会话不存在:' + raw + '(op=list 可看各任务所属会话 id)');
|
||
if (String(s.user || '') !== curUser()) throw new Error('无权操作其他用户的会话任务');
|
||
return raw;
|
||
};
|
||
switch (op) {
|
||
case 'get': {
|
||
const sid = target();
|
||
const t = scheduler.getTask(db, sid);
|
||
if (!t) return sid === ctx.sessionId ? '本会话没有定时任务。' : '会话 ' + sid + ' 没有定时任务。';
|
||
const srow = db.prepare('SELECT title FROM sessions WHERE id = ?').get(sid);
|
||
return schedDetail(Object.assign({ session_id: sid, current: sid === ctx.sessionId, title: srow && srow.title }, t));
|
||
}
|
||
case 'create': {
|
||
const raw = String(args.id == null ? '' : args.id).trim();
|
||
if (raw && raw !== ctx.sessionId) throw new Error('op=create 只作用于当前会话:新任务住进本会话并于本回合收尾后收口退位成专柜(定时即下班),无需也不能指定其它会话 id');
|
||
if (!cronExpr) throw new Error('op=create 缺少必填参数 cron_expr');
|
||
if (!prompt) throw new Error('op=create 缺少必填参数 prompt');
|
||
const brief = String(args.brief || '').replace(/\s+/g, ' ').trim().slice(0, 40);
|
||
// script 纯标记:存在即暗示模型把流程沉淀成脚本(怎么写、用什么跑、prompt 怎么引用由它自定);
|
||
// 创建与触发均不校验——缺脚本时 prompt 自身的指示就是回退面。
|
||
const script = String(args.script || '').replace(/\s+/g, ' ').trim().slice(0, 80);
|
||
// 谁设的闹钟通知谁:本会话当前的微信绑定落进任务行(专柜退位后 channel_sessions 就没了,就地捕获)。
|
||
const chRow = db.prepare("SELECT channel FROM channel_sessions WHERE session_id = ? AND channel LIKE 'wx:%'").get(ctx.sessionId);
|
||
const t = scheduler.createTask(db, ctx.sessionId, cronExpr, prompt, brief, script, chRow ? chRow.channel : '');
|
||
// 定时即下班:标记本回合收尾时由 engine 收口(brief 碎片 + 归档 + 通道解绑,见 engine.taskClockOut)。
|
||
if (ctx.onTaskCreated) ctx.onTaskCreated();
|
||
return '已创建 id=' + ctx.sessionId + '\ncron="' + t.cron_expr + '"\nnext=' + scheduler.fmtIso(t.next_run_at)
|
||
+ (script ? '\nscript=' + script : '')
|
||
+ '\n本会话即收口为该任务专柜(用户无感知,下条消息自动进新会话)。'
|
||
+ (chRow ? '\n完成/失败结果自动通知微信。' : '');
|
||
}
|
||
case 'update': {
|
||
if (!cronExpr && !prompt) throw new Error('op=update 需要 cron_expr 和 prompt 至少提供一个');
|
||
const sid = target();
|
||
const t = scheduler.updateTask(db, sid, {
|
||
cronExpr: cronExpr || null,
|
||
prompt: prompt || null,
|
||
});
|
||
return '已更新 id=' + sid + '\ncron="' + t.cron_expr + '"\nnext=' + scheduler.fmtIso(t.next_run_at);
|
||
}
|
||
case 'list': {
|
||
// 跨会话全览:编号条目 + key=value 行,id 即行动把手(无任何教学/切会话引导)。
|
||
const rows = scheduler.listUserTasks(db, curUser());
|
||
if (!rows.length) return '当前没有任何定时任务。';
|
||
return '定时任务×' + rows.length + '\n\n'
|
||
+ rows.map((t, i) => schedEntry(Object.assign({}, t, { current: t.session_id === ctx.sessionId }), i + 1)).join('\n\n');
|
||
}
|
||
case 'delete': {
|
||
const sid = target();
|
||
const old = scheduler.deleteTask(db, sid);
|
||
return '已删除 id=' + sid + '(原定 cron="' + old + '")';
|
||
}
|
||
default:
|
||
throw new Error('未知的 op:"' + op + '"。可用:get / list(跨会话全览,每行带 id)/ create(仅当前会话;需 cron_expr、prompt、brief)/ update(需 cron_expr、prompt 至少一个,可选 id)/ delete(可选 id)');
|
||
}
|
||
}
|
||
|
||
// 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 兼容
|
||
// terminal/技能里 sqlite3 CLI 的并发访问。
|
||
// 读写分离硬校验:stmt.reader 为真(纯读)拒走 exec,写语句拒走 query;
|
||
// prepare 天然拒绝多语句,堆叠注入在入口即挡下。错误不返 {"error"} JSON 而是抛出,
|
||
// 由 engine 统一包成 "Error: ..." 并置 is_error(本库工具约定,见 engine 调用处)。
|
||
// 结构化 insert 与 exec 同义但免手写 SQL/数占位符(批量行是手写 VALUES 数 ? 的重灾区):
|
||
// 列名先对 sqlite_master 真实列校验再 quoteIdent 转义,值全部走 ? 绑定。
|
||
// update/delete 不做结构化 op(单行 SQL 本身简单、错误率低,且 AND 等值 where 表达力
|
||
// 不够还要回退 exec):继续走 exec,入口不拦写语句,兑底通道保持全能力。
|
||
// runTaskSql 是本工具与 routes/data-page.js(/api/db/{task_id}/query,页面前端调)共用的
|
||
// 唯一 SQL 执行入口:prepare/读写分流/事务/DDL 判定两处同一事实源,不漂移。
|
||
const DB_MAX_ROWS = 500; // query 行数上限(docs 要求:防爆上下文)
|
||
const DB_MAX_BYTES = 100 * 1024; // query 序列化字节上限
|
||
|
||
function openTaskDbAt(taskDir) {
|
||
fs.mkdirSync(taskDir, { recursive: true });
|
||
const db = new Database(path.join(taskDir, 'data.db'));
|
||
db.pragma('busy_timeout = 5000');
|
||
return db;
|
||
}
|
||
|
||
function openTaskDb(ctx) { return openTaskDbAt(ctx.taskDir); }
|
||
|
||
// better-sqlite3 不接受 boolean/array/object 绑定;JSON 世界 true/false ↔ SQLite 0/1 是强约定。
|
||
// 所有进入绑定位的值(params / rows / set / where)统一过这里。
|
||
function dbValue(v, label) {
|
||
if (v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'bigint') return v;
|
||
if (typeof v === 'boolean') return v ? 1 : 0;
|
||
throw new Error('db: ' + label + ' 值类型不支持:' + (Array.isArray(v) ? 'array' : typeof v) + '(可用:string/number/null/boolean)');
|
||
}
|
||
|
||
function sanitizeDbParams(params) {
|
||
if (params == null) return [];
|
||
if (!Array.isArray(params)) throw new Error('db: params 必须是数组(按 ? 占位符顺序)');
|
||
return params.map((v, i) => dbValue(v, 'params[' + i + ']'));
|
||
}
|
||
|
||
// 表必须存在且取真实列名集合(仅 table,视图不可写);返回的 Set 同时充当列名白名单。
|
||
function needTaskTableColumns(db, table) {
|
||
const hit = db
|
||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
|
||
.get(table);
|
||
if (!hit) throw new Error('db: 表不存在:' + table + '(op=tables 看现有表,op=exec 建新表)');
|
||
return new Set(db.pragma('table_info(' + quoteIdent(hit.name) + ')').map(c => c.name));
|
||
}
|
||
|
||
function requireColumns(cols, keys, label) {
|
||
const bad = keys.filter(k => !cols.has(k));
|
||
if (bad.length) {
|
||
throw new Error('db: ' + label + ' 含未知列:' + bad.join(', ') + '(现有列:' + [...cols].join(', ') + ')');
|
||
}
|
||
}
|
||
|
||
function quoteIdent(name) {
|
||
return '"' + String(name).replace(/"/g, '""') + '"';
|
||
}
|
||
|
||
// BLOB 列(Buffer)直接 JSON.stringify 会展开成 {"type":"Buffer","data":[...]} 天书,换占位符。
|
||
function jsonSafeRows(rows) {
|
||
return rows.map(row => {
|
||
const out = {};
|
||
for (const k of Object.keys(row)) {
|
||
const v = row[k];
|
||
out[k] = Buffer.isBuffer(v) ? '<blob ' + v.length + ' bytes>' : v;
|
||
}
|
||
return out;
|
||
});
|
||
}
|
||
|
||
// 500 行 / 100KB 双上限:未超限返回裸数组;超限改 {rows,...} 信封并附截断说明。
|
||
// overflow 由 runTaskSql 的行数截断给出(总行数不再探得,故信封只报 returned_rows 不报 total);
|
||
// 字节线在此再收。
|
||
function renderQueryResult(rows, overflow) {
|
||
let shown = rows;
|
||
let truncated = !!overflow;
|
||
if (Buffer.byteLength(JSON.stringify(shown, null, 2)) > DB_MAX_BYTES) {
|
||
truncated = true;
|
||
let bytes = 4; // "[\n]"
|
||
const kept = [];
|
||
for (const r of shown) {
|
||
const s = JSON.stringify(r, null, 2).length + 3; // + 逗号与换行余量
|
||
if (bytes + s > DB_MAX_BYTES && kept.length) break;
|
||
kept.push(r);
|
||
bytes += s;
|
||
}
|
||
shown = kept;
|
||
}
|
||
if (!truncated) return JSON.stringify(shown, null, 2);
|
||
return JSON.stringify({
|
||
rows: shown,
|
||
returned_rows: shown.length,
|
||
truncated: true,
|
||
note: '结果已截断(上限 ' + DB_MAX_ROWS + ' 行或 ' + Math.floor(DB_MAX_BYTES / 1024) + ' KB)。用 WHERE 收窄列/行,或 LIMIT/OFFSET 分页。',
|
||
}, null, 2);
|
||
}
|
||
|
||
// 任务库单语句执行的统一入口。mode:'read' 只许读(op=query)| 'write' 只许写(op=exec)|
|
||
// 'any' 按 stmt.reader 自动分流(HTTP API,SKILL.md 契约:任意单语句)。
|
||
// maxRows>0 时读取走 iterate 到量即停(防大表 SELECT * 全量物化),overflow 处置交调用方:
|
||
// 工具截断成信封,API 直接报错引导分页。错误一律抛出,不在此层包装返回形态。
|
||
function runTaskSql(taskDir, sql, params, mode, maxRows) {
|
||
const text = String(sql || '').trim();
|
||
if (!text) throw new Error('db: sql 不能为空');
|
||
const db = openTaskDbAt(taskDir);
|
||
try {
|
||
const stmt = db.prepare(text); // 多语句在此抛错(堆叠注入入口即挡)
|
||
const bound = sanitizeDbParams(params);
|
||
if (stmt.reader) {
|
||
if (mode === 'write') throw new Error('db: op=exec 收到只读语句,读取请用 op=query');
|
||
const rows = [];
|
||
let overflow = false;
|
||
if (maxRows > 0) {
|
||
const it = stmt.iterate(...bound);
|
||
try {
|
||
for (const r of it) {
|
||
if (rows.length >= maxRows) { overflow = true; break; }
|
||
rows.push(r);
|
||
}
|
||
} finally { try { it.return(); } catch (_) {} }
|
||
} else {
|
||
for (const r of stmt.all(...bound)) rows.push(r);
|
||
}
|
||
return { kind: 'read', rows: jsonSafeRows(rows), overflow };
|
||
}
|
||
if (mode === 'read') throw new Error('db: op=query 只允许读语句(SELECT 等),写操作请用 op=exec');
|
||
db.exec('BEGIN');
|
||
try {
|
||
const info = stmt.run(...bound);
|
||
db.exec('COMMIT');
|
||
const verb = text.split(/\s+/)[0].toLowerCase();
|
||
const out = (verb === 'create' || verb === 'alter' || verb === 'drop')
|
||
? { ok: true }
|
||
: { rowsAffected: info.changes, lastInsertRowid: Number(info.lastInsertRowid) };
|
||
return { kind: 'write', out };
|
||
} catch (err) {
|
||
try { db.exec('ROLLBACK'); } catch (_) {}
|
||
throw err;
|
||
}
|
||
} finally {
|
||
try { db.close(); } catch (_) {}
|
||
}
|
||
}
|
||
|
||
function toolDb(ctx, args) {
|
||
const op = String(args.op || '').trim().toLowerCase();
|
||
const sql = String(args.sql || '').trim();
|
||
const table = String(args.table || '').trim();
|
||
|
||
let db;
|
||
try {
|
||
switch (op) {
|
||
case 'exec': {
|
||
if (!sql) throw new Error('db: op=exec 缺少必填参数 sql');
|
||
const r = runTaskSql(ctx.taskDir, sql, args.params, 'write', 0);
|
||
return JSON.stringify(r.out);
|
||
}
|
||
case 'query': {
|
||
if (!sql) throw new Error('db: op=query 缺少必填参数 sql');
|
||
const r = runTaskSql(ctx.taskDir, sql, args.params, 'read', DB_MAX_ROWS);
|
||
return renderQueryResult(r.rows, r.overflow);
|
||
}
|
||
case 'insert': {
|
||
if (!table) throw new Error('db: op=insert 缺少必填参数 table');
|
||
const list = args.rows;
|
||
if (!Array.isArray(list)) throw new Error('db: op=insert 缺少必填参数 rows(行对象数组,单行也要包成数组)');
|
||
if (!list.length) throw new Error('db: op=insert rows 是空数组,无事可做');
|
||
for (let i = 0; i < list.length; i++) {
|
||
const r = list[i];
|
||
if (!r || typeof r !== 'object' || Array.isArray(r) || !Object.keys(r).length) {
|
||
throw new Error('db: op=insert rows[' + i + '] 必须是非空对象 {列名: 值}');
|
||
}
|
||
}
|
||
// 各行 key 必须一致:静默补 NULL 会掩盖模型笔误,宁可点名报错。
|
||
const cols = Object.keys(list[0]);
|
||
for (let i = 1; i < list.length; i++) {
|
||
const ks = Object.keys(list[i]);
|
||
if (ks.join('\u0000') !== cols.join('\u0000')) {
|
||
throw new Error('db: op=insert 各行 key 必须一致:rows[0]=' + JSON.stringify(cols) +
|
||
',rows[' + i + ']=' + JSON.stringify(ks));
|
||
}
|
||
}
|
||
db = openTaskDb(ctx);
|
||
requireColumns(needTaskTableColumns(db, table), cols, 'rows');
|
||
const sqlIns = 'INSERT INTO ' + quoteIdent(table) + ' (' + cols.map(quoteIdent).join(', ') +
|
||
') VALUES (' + cols.map(() => '?').join(', ') + ')';
|
||
const stmtIns = db.prepare(sqlIns);
|
||
db.exec('BEGIN');
|
||
try {
|
||
let firstId = null;
|
||
for (const r of list) {
|
||
const info = stmtIns.run(...cols.map(c => dbValue(r[c], 'rows.' + c)));
|
||
if (firstId === null) firstId = Number(info.lastInsertRowid);
|
||
}
|
||
db.exec('COMMIT');
|
||
return JSON.stringify({ inserted: list.length, firstInsertRowid: firstId });
|
||
} catch (err) {
|
||
try { db.exec('ROLLBACK'); } catch (_) {}
|
||
throw err;
|
||
}
|
||
}
|
||
case 'tables': {
|
||
db = openTaskDb(ctx);
|
||
const names = db
|
||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
|
||
.all().map(r => r.name);
|
||
// 空库直返 [] 易被读成「工具坏了」:补一句事实定性(首次使用属正常,建表走 op=exec)。
|
||
if (!names.length) return '[](尚无表:空库首次使用属正常,用 op=exec 建表后即可 insert)';
|
||
const out = names.map(n => ({ name: n, rows: db.prepare('SELECT COUNT(*) AS c FROM ' + quoteIdent(n)).get().c }));
|
||
return JSON.stringify(out, null, 2);
|
||
}
|
||
case 'schema': {
|
||
if (!table) throw new Error('db: op=schema 缺少必填参数 table');
|
||
db = openTaskDb(ctx);
|
||
// PRAGMA 不支持 ? 绑定:先参数化确认表存在,再用转义标识符拼入(不存在即报错,拼入的必是真实名)。
|
||
const hit = db
|
||
.prepare("SELECT name FROM sqlite_master WHERE type IN ('table', 'view') AND name = ?")
|
||
.get(table);
|
||
if (!hit) throw new Error('db: 表不存在:' + table);
|
||
const cols = db.pragma('table_info(' + quoteIdent(hit.name) + ')');
|
||
return JSON.stringify(cols.map(c => ({
|
||
name: c.name, type: c.type, notnull: !!c.notnull, dflt_value: c.dflt_value, pk: !!c.pk,
|
||
})), null, 2);
|
||
}
|
||
default:
|
||
throw new Error('db: 未知的 op:"' + op + '"。可用:exec(需 sql,params 可选)/ query(需 sql,params 可选)/ insert(需 table、rows)/ tables / schema(需 table)');
|
||
}
|
||
} finally {
|
||
if (db) try { db.close(); } catch (_) {}
|
||
}
|
||
}
|
||
|
||
// skill:技能三件套(list/get/run)合并后的单工具(依据 docs/tool-design.md §一/§二/§三)。
|
||
// 扁平参数:op 是唯一必填的开关,name 供 get/run 指认技能,args 仅 run 用;条件必填写不进
|
||
// schema,由 toolSkill 校验并在报错里点名(§四/§五)。
|
||
// 旧字段名 input_args 在入口归一化成 args(存量技能文档里仍写着它),之后只走一条分派路径——
|
||
// 曾有两条执行路径,其中一条只读 input_args,{op:"run", args:{...}} 的参数会被静默丢弃。
|
||
// 上一版「动词作键」不再兼容:schema 的 required:["op"] 会在 checkToolArgs 阶段先拦下,
|
||
// 留着分支只会是死代码(lab 直调除外,不值得为它多一条路径)。
|
||
// op=list 的清单取 listCallableSkills:目录技能 + mode=skill 的 MCP 工具;get/run 对两者一视同仁。
|
||
// visit_url(front matter 可选):页面产物类技能声明访问路径模板,run 成功后在本层拼
|
||
// public_link.base_url(与 mint_public_link 同源)追加完整「访问地址」——技能进程跑在
|
||
// executor 隔离视图里不知道公网前缀,AI 拿到相对路径就会原样转给用户,而相对路径打不开。
|
||
// 本地桌面形态的对外前缀:只有监听在回环地址(local/start.sh 注入 HOST=127.0.0.1)才认。
|
||
// 容器/服务器形态 HOST 为空(= 0.0.0.0),不能凭空造一个 127.0.0.1 给远端用户,照旧只给站内路径。
|
||
function localOrigin(cfg) {
|
||
const host = String(process.env.HOST || '').trim().toLowerCase();
|
||
if (host !== '127.0.0.1' && host !== 'localhost' && host !== '::1') return '';
|
||
const port = String(process.env.PORT || (cfg && cfg.port) || '').trim();
|
||
return port ? 'http://127.0.0.1:' + port : '';
|
||
}
|
||
|
||
async function runSkillWithVisit(ctx, name, inputArgs) {
|
||
const out = await skills.runSkill(ctx, name, inputArgs);
|
||
let fm;
|
||
try {
|
||
fm = skills.parseFrontMatter(await skills.getSkillInfo(ctx, name));
|
||
} catch (_) {
|
||
return out; // 描述文件异常不该废掉一次成功的 run
|
||
}
|
||
const tpl = fm && fm.visit_url ? String(fm.visit_url).trim() : '';
|
||
if (!tpl) return out;
|
||
const rel = tpl.replace(/\{task_id\}/g, ctx.sessionId || path.basename(path.resolve(ctx.taskDir || '')));
|
||
const pl = (ctx.cfg && ctx.cfg.public_link) || {};
|
||
const base = String(pl.base_url || '').trim().replace(/\/+$/, '');
|
||
if (base) return out + '\n访问地址:' + base + rel;
|
||
// 没有公网前缀时别只给站内路径:本地形态用户就在这台机器上,回环地址就是能直接点开的地址。
|
||
const origin = localOrigin(ctx.cfg);
|
||
if (origin) return out + '\n访问地址:' + origin + rel;
|
||
return out + '\n访问地址:' + rel + '(站内路径:public_link.base_url 未配置,拼不出公网前缀)';
|
||
}
|
||
|
||
const SKILL_USAGE = 'skill 用法:{"op":"list"} / {"op":"get","name":"<技能名>"} / {"op":"run","name":"<技能名>","args":{...}}';
|
||
|
||
// list/get 带非空 args 一律报错而不是静默丢弃:否则模型会以为参数生效了。
|
||
function rejectSkillArgs(skillArgs, op) {
|
||
if (!skillArgs || typeof skillArgs !== 'object' || !Object.keys(skillArgs).length) return;
|
||
throw new Error('op=' + op + ' 不接受 args,只有 op=run 才带参数。' + SKILL_USAGE);
|
||
}
|
||
|
||
// 旧字段名 input_args 在这里归一化成 args,再走同一条分派(见上方注释)。
|
||
async function toolSkill(ctx, args) {
|
||
const a = args || {};
|
||
const op = String(a.op == null ? '' : a.op).trim().toLowerCase();
|
||
const name = String(a.name == null ? '' : a.name).trim();
|
||
const skillArgs = a.args !== undefined ? a.args : a.input_args;
|
||
if (!op) throw new Error('skill 缺少必填参数 op(list / get / run)。' + SKILL_USAGE);
|
||
switch (op) {
|
||
case 'list':
|
||
rejectSkillArgs(skillArgs, 'list');
|
||
return JSON.stringify(await skills.listCallableSkills(ctx), null, 2);
|
||
case 'get': {
|
||
if (!name) throw new Error('op=get 缺少必填参数 name。' + SKILL_USAGE);
|
||
rejectSkillArgs(skillArgs, 'get');
|
||
const info = await skills.getSkillInfo(ctx, name);
|
||
if (ctx.run && !ctx.run.deepThink && skills.parseFrontMatter(info).thinking === true) {
|
||
ctx.run.deepThink = true;
|
||
if (!ctx.run.thinkAuto) {
|
||
ctx.run.thinkAuto = true;
|
||
if (typeof ctx.onDeepThink === 'function') ctx.onDeepThink({ skill: name });
|
||
}
|
||
}
|
||
return info;
|
||
}
|
||
case 'run':
|
||
if (!name) throw new Error('op=run 缺少必填参数 name。' + SKILL_USAGE);
|
||
return runSkillWithVisit(ctx, name, skillArgs);
|
||
default:
|
||
throw new Error('未知的 op:' + JSON.stringify(op) + '。' + SKILL_USAGE);
|
||
}
|
||
}
|
||
|
||
// lab:全工具统一入口(元工具,tools 数组收缩到 1 个仍可达内置 + MCP 全部能力)。
|
||
// args 为自由对象——目标 schema 定义期不可知(docs/tool-design.md §三 的合法例外),
|
||
// 条件校验归内层 handler;错误冒泡不包装(只有一层)。help 是伪工具:不进 HANDLERS,
|
||
// 只在本函数早退。默认被全局 tools_deny 屏蔽,仅 lab profile 显式清空 deny 后下发。
|
||
async function toolLab(ctx, args) {
|
||
const name = String(args.tool || '').trim();
|
||
if (!name) throw new Error('lab: 缺少参数 tool。可用:' + listCallableTools().join(', '));
|
||
if (name === 'lab') throw new Error('lab: 不允许嵌套调用 lab。');
|
||
if (name === 'help') return runLabHelp(args.args);
|
||
const inner = args.args;
|
||
if (inner != null && (typeof inner !== 'object' || Array.isArray(inner))) {
|
||
throw new Error('lab: args 必须是对象(目标工具的键值参数),收到:' + JSON.stringify(inner).slice(0, 80));
|
||
}
|
||
// 先自查再转发:未知名要带全清单回显(§五 报错回显),executeTool 的兑底文案没这个待遇。
|
||
if (!HANDLERS[name] && !mcp.hasTool(name)) {
|
||
throw new Error('未知工具 "' + name + '"。可用:' + listCallableTools().join(', '));
|
||
}
|
||
return executeTool(ctx, name, inner || {});
|
||
}
|
||
|
||
function listCallableTools() {
|
||
// help 不在 HANDLERS(伪工具);lab 自身不列(嵌套已被拒,列了只会诱导模型绕圈)。
|
||
// MCP 侧用 toolDefinitions() 现成取名——含冲突重命名的 server__ 前缀,与实际可调用名严格一致。
|
||
return Object.keys(HANDLERS).filter(n => n !== 'lab')
|
||
.concat(mcp.toolDefinitions().map(t => t.function.name));
|
||
}
|
||
|
||
function runLabHelp(args) {
|
||
const all = BUILTIN_TOOL_DEFS.concat(mcp.toolDefinitions())
|
||
.filter(t => t && t.function && t.function.name !== 'lab');
|
||
const target = args && String(args.tool || '').trim();
|
||
if (!target) {
|
||
return all.map(t => t.function.name + ' — ' + String(t.function.description || '').split('\n')[0].trim()).join('\n');
|
||
}
|
||
const def = all.find(t => t.function.name === target);
|
||
if (!def) throw new Error('未知工具 "' + target + '"。可用:' + all.map(t => t.function.name).join(', '));
|
||
return JSON.stringify(def.function, null, 2);
|
||
}
|
||
|
||
// recall:长期记忆(工作日记)的回忆入口——纯记忆三 op。
|
||
// 日记按会话收口持久存储(memory.js),开场只注入最近 N 条;更早的条目由本工具按需取。
|
||
// 历史成果文件不再归日记管:浏览/导入走 list_directory / copy_path 的 @<会话id>/<路径> 记号
|
||
// (校验单点 resolvePastPath),导入后就是本会话普通文件,read_file/mint 照常处理。
|
||
// 旧 files/link 两 op 是 ls/mint 的沙箱外克隆,已整删(克隆必漂移:link 漏抄 mint 的 realpath 防线)。
|
||
// op=day 的 date 容错:模型可能把头部「date=YYYY-MM-DD HH:MM:SS」原样抄回。
|
||
// 只取开头的日期部分并补零/校验;不扫描全文找日期。
|
||
const RECALL_DAY_RE = /^(\d{4})[-/.年](\d{1,2})[-/.月](\d{1,2})(?!\d)/;
|
||
function normalizeRecallDay(v) {
|
||
const m = RECALL_DAY_RE.exec(String(v || '').trim());
|
||
if (!m) return '';
|
||
const y = Number(m[1]), mo = Number(m[2]), d = Number(m[3]);
|
||
const dt = new Date(Date.UTC(y, mo - 1, d));
|
||
if (dt.getUTCFullYear() !== y || dt.getUTCMonth() !== mo - 1 || dt.getUTCDate() !== d) return '';
|
||
return y + '-' + String(mo).padStart(2, '0') + '-' + String(d).padStart(2, '0');
|
||
}
|
||
|
||
function toolRecall(ctx, args) {
|
||
const op = String(args.op || '').trim().toLowerCase();
|
||
const db = ctx.db;
|
||
const me = db.prepare('SELECT user FROM sessions WHERE id = ?').get(ctx.sessionId);
|
||
const user = String((me && me.user) || '');
|
||
switch (op) {
|
||
case 'search': {
|
||
const q = String(args.query || '').trim();
|
||
if (!q) throw new Error('op=search 需要 query(关键词;空格分隔多个词更好,如「身份证 水印」)');
|
||
const txt = memory.searchFragments(db, user, q, args.count, ctx.sessionId);
|
||
return txt || '日记中无「' + q + '」相关记录。';
|
||
}
|
||
case 'days': {
|
||
const list = memory.daysIndex(db, user);
|
||
if (!list.length) return '日记库为空(尚无收口碎片)。';
|
||
return '【日记索引】共 ' + list.length + ' 天(新在前):\n' + list.join('\n');
|
||
}
|
||
case 'day': {
|
||
const date = normalizeRecallDay(args.date);
|
||
if (!date) throw new Error('op=day 需要 date(YYYY-MM-DD,先用 op=days 查有哪些天)');
|
||
const txt = memory.dayEntry(db, user, date);
|
||
return txt ? date + ' 的日记:\n' + txt : date + ' 无日记。';
|
||
}
|
||
default:
|
||
throw new Error('未知的 op: "' + op + '", 可用: search / days / day');
|
||
}
|
||
}
|
||
|
||
const HANDLERS = {
|
||
read_file: toolReadFile,
|
||
list_directory: toolListDirectory,
|
||
copy_path: toolCopyPath,
|
||
write_file: toolWriteFile,
|
||
edit_file: toolEditFile,
|
||
mint_public_link: toolMintPublicLink,
|
||
terminal: toolTerminal,
|
||
fetch: toolFetch,
|
||
schedule: toolScheduleTask,
|
||
profile: toolProfile,
|
||
recall: toolRecall,
|
||
db: toolDb,
|
||
skill: toolSkill,
|
||
lab: toolLab,
|
||
};
|
||
|
||
// ctx: {sessionId, taskDir, run, cfg, db, vision}
|
||
// 返回值一般为字符串;read_file 读图时返回 {text, image_rel},text 是结构化 JSON 回执
|
||
// (见 imageReceipt),image_rel 缺省表示本次不投递像素。
|
||
// 内置工具优先;未命中时交给 MCP 注册表(启动时发现的服务工具)。
|
||
async function executeTool(baseCtx, name, args) {
|
||
// 会话目录懒建:会话创建时不再占坑,第一次真用到工具才建(纯文本对话不留空目录)。
|
||
try { if (baseCtx && baseCtx.taskDir) fs.mkdirSync(baseCtx.taskDir, { recursive: true }); } catch (_) {}
|
||
const handler = HANDLERS[name];
|
||
if (handler) return handler(baseCtx, args || {});
|
||
if (mcp.hasTool(name)) return mcp.callTool(name, args || {}, baseCtx); // baseCtx.taskDir → X-Session-Dir 头下发给 MCP 服务
|
||
return 'Error: 未知工具 ' + name;
|
||
}
|
||
|
||
module.exports = { executeTool, resolveInTask, recordFile, runTaskSql };
|