diff --git a/app/package.json b/app/package.json index 5761a34..afbb0dd 100644 --- a/app/package.json +++ b/app/package.json @@ -1,6 +1,6 @@ { "name": "agent-app", - "version": "2.2.0", + "version": "2.3.0", "description": "自用通用 Agent 系统:多模型调度 + 任务目录 + 工具调用 + H5 Web UI", "main": "server/server.js", "scripts": { diff --git a/app/server/config.js b/app/server/config.js index 48c7fba..12a9208 100644 --- a/app/server/config.js +++ b/app/server/config.js @@ -113,12 +113,13 @@ const DEFAULTS = { // 模型 profile(prompt + tools 名单组合):platforms 里的模型用 profile: <名> 引用。 model_profiles: { // advising:顾问阶段(sessions.phase)专用组合——不由模型配置引用,而是 resolveProfileName 在 - // advising 时强制命中:顾问只聊和读、不写(write_file 已移除,批内幻觉调用另由引擎挡下), + // advising 时强制命中:顾问只聊和读、不写(write_file/edit_file/copy_path 不在名单,批内幻觉调用另由引擎挡下; + // list_directory 入选——翻阅历史目录是顾问高频刚需), // 例外是 profile(画像元信息,不碰任务目录;顾问问答恰是收集称谓/偏好密度最高的时刻) // 与 recall(日记只读翻阅;用户和顾问聊「上次那个事」恰是回忆查询的高峰场景); // 唯一出口是 handoff;tools_deny 必须显式清空:不配 = 继承全局 ['lab','handoff'], // allow 滤完再叠 deny 会把 handoff 自己禁掉(同 lab 组合的教训)。 - advising: { tools_allow: ['read_file', 'fetch', 'handoff', 'profile', 'recall'], tools_deny: [], system_prompt_file: 'advising-system.txt' }, + advising: { tools_allow: ['read_file', 'list_directory', 'fetch', 'handoff', 'profile', 'recall'], tools_deny: [], system_prompt_file: 'advising-system.txt' }, // lab:统一入口元工具自测组合——tools 收缩到 1 个,其余能力经 lab(help) 现场发现。 // tools_deny 必须显式清空:不配 = 继承全局 ['lab'],deny 后叠加会把 lab 自己禁掉 → 零工具。 lab: { tools_allow: ['lab'], tools_deny: [], system_prompt_file: 'lab-system.txt' }, diff --git a/app/server/engine.js b/app/server/engine.js index 0ad1b97..19f8cdf 100644 --- a/app/server/engine.js +++ b/app/server/engine.js @@ -345,7 +345,8 @@ function effectiveTools(profileName) { // ---------- 阶段(sessions.phase:advising 顾问 / executing 执行) ---------- // advising:新建会话与「清空」的落点。profile 被 resolveProfileName 强制为 'advising', -// 只聊和读不写(write_file/edit_file 不在其 schema,批内幻觉调用也在 runLoopInner 挡下); +// 只聊和读不写(write_file/edit_file/copy_path 不在其 schema,批内幻觉调用也在 runLoopInner 挡下; +// list_directory 在白名单里——顾问翻阅历史目录正当其用); // 唯一出口 = handoff 工具成功返回(brief 由 handler 落盘任务目录根 task.md,见 tools/executor.js)。 // executing:一路走到底,只有清空才回 advising;压缩不碰 phase(压完仍回原模式)。 @@ -783,7 +784,7 @@ async function runLoopInner(sessionId, run) { output = chk.error; isError = true; } else if (session.phase === 'advising' - && (tc.function.name === 'write_file' || tc.function.name === 'edit_file')) { + && (tc.function.name === 'write_file' || tc.function.name === 'edit_file' || tc.function.name === 'copy_path')) { // 顾问单入口硬约束:写类工具不在其 schema,但「名单外照跑」是全局策略(executeTool 全表), // 幻觉调用会真写文件、绕过出口制造假承诺——阶段契约优先,挡下并指向 handoff。 output = 'Error: 顾问阶段不能写文件。任务书请通过 handoff 工具的 brief 参数提交。'; diff --git a/app/server/tools/definitions.json b/app/server/tools/definitions.json index e7f358b..466eac6 100644 --- a/app/server/tools/definitions.json +++ b/app/server/tools/definitions.json @@ -1,4 +1,28 @@ [ + { + "type": "function", + "function": { + "name": "copy_path", + "description": "Copies a file or directory, preserving the original; directories are copied recursively. More efficient than reading then writing contents. Returns confirmation with the destination path.\n\nImport past work: source_path accepts '@/' to copy from your OWN past session (id from a diary fragment's 【…】 heading; use recall to find it, list_directory to browse it). destination_path never accepts '@' — past stays read-only, imports land in the current session directory. The destination must not exist yet; nothing is overwritten (pick a new name, or delete yours first via terminal).\n\nAfter import the file is fully local: read_file (including images via vision), terminal, mint_public_link all work on it.\n\nLimits per call: ≤200 MB total, ≤200 files for a directory tree; symlinks are refused (as a source or inside a copied tree) to prevent escaping the directory.", + "parameters": { + "type": "object", + "required": [ + "source_path", + "destination_path" + ], + "properties": { + "source_path": { + "type": "string", + "description": "File or directory to copy, relative to the session working directory (absolute paths inside it accepted). '@/' imports from a same-user past session." + }, + "destination_path": { + "type": "string", + "description": "Where to place the copy inside the CURRENT session directory (relative, or absolute inside it). '@' paths are rejected here. Must not already exist." + } + } + } + } + }, { "type": "function", "function": { @@ -173,6 +197,22 @@ } } }, + { + "type": "function", + "function": { + "name": "list_directory", + "description": "Lists the entries directly inside one directory (one level, like `ls`): folders and files, sorted; hidden entries (starting with '.') omitted; max 200 per call — go deeper by passing a deeper path.\n\npath is relative to the session working directory (absolute paths inside it accepted); empty/omitted lists the current task directory.\n\nPast sessions: '@/' lists a PAST session's own directory, same user only (read-only view). The id is the 【…】 heading of a diary fragment — find it with recall op=search. In '@' mode entries are printed as complete '@/...' paths — copy them straight into copy_path's source_path.", + "parameters": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Directory to list, relative to the session working directory. Absolute paths accepted. '@/' lists that past session's directory (same user only; id from a diary fragment's 【…】 heading)." + } + } + } + } + }, { "type": "function", "function": { @@ -246,7 +286,7 @@ "type": "function", "function": { "name": "recall", - "description": "Access your long-term memory: the work diary. Each finished session leaves one short fragment (a few dozen characters, headed by the source session id), stored permanently; only the newest fragments were injected at session start. When the user vaguely recalls something from the past, search is your primary entry — you cannot know what you have forgotten. Read-only.\n\nop=search Requires query (keywords; space-separated words rank better, e.g. '身份证 水印'). Fuzzy fragment-level match across ALL dates (Chinese tolerant to partial phrases), best matches first. Optional count (default 10, max 30).\nop=days No arguments. Index of diary days (date + fragment count) — use when the user remembers roughly WHEN but not what; then op=day.\nop=day Requires date (YYYY-MM-DD, as listed by op=days). Full fragments of that day.\nop=files Requires id (the session id from a diary fragment's 【…】 heading). Files of that past session that still exist on disk right now.\nop=link Requires id and path (a name from op=files). Mint a temporary download link.", + "description": "Access your long-term memory: the work diary. Each finished session leaves one short fragment (a few dozen chars) there, headed by its source session id in 【…】; fragments are kept permanently, but only the newest were injected at session start — recall reads the whole archive on demand. Read-only.\n\nop=search Fuzzy keyword match over ALL fragments, best first. Primary entry when the user vaguely recalls something — you cannot know what you have forgotten.\nop=days Index of days that have entries (newest first) — when the user remembers roughly WHEN but not what.\nop=day Full fragments of one day.\n\nReturns are plain text: search hits print '--- date (match%) ---' followed by 【id】 and the fragment; days list '- date(n 条)'; day lists fragments. A miss comes back as a short 'no records / no diary' line — a normal answer, not an error.", "parameters": { "type": "object", "required": [ @@ -258,31 +298,24 @@ "enum": [ "search", "days", - "day", - "files", - "link" + "day" ], - "description": "What to recall: search = keyword fuzzy over all diary fragments (primary); days = which dates have entries; day = one date's full diary; files = a past session's current artifacts; link = a download link for one of them." + "description": "Recall operation; what each op does is in the tool description." }, "query": { "type": "string", - "description": "op=search: keywords to look for (space-separated words rank best, e.g. '身份证 水印'). Chinese and English both supported, case-insensitive." + "description": "op=search: keywords; space-separated words rank best (e.g. '身份证 水印'). Chinese and English, case-insensitive; Chinese tolerates partial phrases." }, "count": { "type": "integer", + "minimum": 1, + "maximum": 30, + "default": 10, "description": "op=search: max fragments to return (default 10, max 30)." }, "date": { "type": "string", "description": "op=day: the day to open, YYYY-MM-DD exactly as shown by op=days." - }, - "id": { - "type": "string", - "description": "op=files / op=link: the source session id as written inside a diary fragment's 【…】 heading (e.g. 'task-20260929-003')." - }, - "path": { - "type": "string", - "description": "op=link: file name inside that session's task directory, exactly as listed by op=files." } } } diff --git a/app/server/tools/executor.js b/app/server/tools/executor.js index d952685..2f238a7 100644 --- a/app/server/tools/executor.js +++ b/app/server/tools/executor.js @@ -37,6 +37,57 @@ function relOf(taskDir, abs) { return path.relative(path.resolve(taskDir), abs) || '.'; } +// ---------- 跨会话路径:@<会话id>/(历史只读,数据过墙只走 copy_path 一道门) ---------- +// 背景:terminal 在远端 executor 容器里跑(compose:wrapper 启动即 unmount host-tasks), +// 别的会话目录在 shell 物理视图里根本不存在;core 进程内的文件工具又被 resolveInTask +// 锁死本会话。跨会话取旧成果只剩这一个口子,同用户校验单点在此(承自 recall 旧 files/link, +// 那两个 op 是 ls/mint 的沙箱外克隆,已整删——克隆会漂移:link 漏抄 mint 的 realpath 防线)。 +const PAST_RE = /^@([^\s/]+)(?:\/([\s\S]*))?$/; +function resolvePastPath(ctx, p) { + const m = PAST_RE.exec(p); + if (!m) throw new Error('@ 路径格式:@<会话id>/<相对路径>,如 @task-20260929-003/out/a.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 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('无权访问该会话(非当前用户)'); + const root = String((ctx.cfg && ctx.cfg.workspace_root) || ''); + if (!root) throw new Error('workspace_root 未配置'); + const dir = path.join(root, sid); + 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);先用 list_directory 看清结构,分批挑'); + } + } + } + } + return { files: n, bytes: bytes }; +} + function isProbablyBinary(abs) { let fd; try { @@ -163,7 +214,7 @@ async function toolReadFile(ctx, args) { let st; try { st = await fsp.stat(abs); } catch (_) { throw new Error('文件不存在:' + args.path); } - if (st.isDirectory()) throw new Error(args.path + ' 是目录不是文件,请用 terminal 执行 ls 查看目录内容。'); + if (st.isDirectory()) throw new Error(args.path + ' 是目录不是文件,请用 list_directory 查看(历史会话传 @<会话id>/<路径>)。'); if (IMAGE_EXTS.has(path.extname(abs).toLowerCase())) { const rel = relOf(ctx.taskDir, abs); if (!ctx.vision) { @@ -202,6 +253,98 @@ async function toolReadFile(ctx, args) { return lines.map((l, i) => String(startLine + i).padStart(6, ' ') + '\t' + l).join('\n'); } +// 对齐 Zed list_directory 的输出格式: +// # Folders: +// / +// +// # Files: +// / +// 本会话路径:条目相对任务目录(同旧版)。'@/' 历史模式:条目带 '@/' 全形前缀, +// 可直接抄进 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; let title = ''; + if (p.startsWith('@')) { + const past = resolvePastPath(ctx, p); + abs = past.abs; + const inner = relOf(past.dir, abs); + prefix = '@' + past.sid + (inner === '.' ? '/' : '/' + inner + '/'); + title = '「' + past.title + '」(历史会话,只读;条目可直接作为 copy_path 的 source_path 导入)\n'; + } else { + abs = resolveInTask(ctx.taskDir, p || '.'); + 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 + (p.startsWith('@') ? '(先用 list_directory 逐层确认该历史会话的文件结构)' : '')); + 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 title + '目录为空'; + 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 = title + sections.join('\n\n'); + if (shownDirs.length + shownFiles.length < total) out += '\n\n...(共 ' + total + ' 项,本层只展示前 ' + LIST_MAX_ENTRIES + ' 项;传更深路径下钻)'; + return out; +} + +// copy_path:普通复制 + 历史成果的唯一进口。源可 '@/'(同用户校验在 resolvePastPath); +// 目标永不接受 @——历史只读、写只进本会话,「导入后文件即本地」让 read_file/vision/mint 全量生效, +// 不必给它们开跨墙特例。撞名拒绝覆盖(保用户现作)。 +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 dst = resolveInTask(ctx.taskDir, dp); + if (path.resolve(dst) === path.resolve(ctx.taskDir)) throw new Error('destination_path 不能是本任务目录本身'); + let src; let srcTitle = ''; + if (sp.startsWith('@')) { + const past = resolvePastPath(ctx, sp); + src = past.abs; + srcTitle = '(来自「' + past.title + '」)'; + } else { + src = resolveInTask(ctx.taskDir, sp); + } + if (path.resolve(src) === path.resolve(dst)) throw new Error('源与目标是同一个路径'); + let lst; + try { + lst = await fsp.lstat(src); + } catch (_) { + throw new Error('源不存在:' + sp + (sp.startsWith('@') ? '(历史会话目录以 list_directory 实际列举为准)' : '')); + } + 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('目标已存在,拒绝覆盖:' + relOf(ctx.taskDir, dst) + '(换个目标名,或先 terminal 删除本会话的同名旧物)'); + await fsp.mkdir(path.dirname(dst), { recursive: true }); + await fsp.cp(src, dst, { recursive: true }); + recordFile(ctx, dst); // 文件表只记普通文件(目录自然跳过),供前端/微信附件展示 + const sizeNote = budget ? '(' + budget.files + ' 个文件,' + Math.round(budget.bytes / 1024) + ' KB)' : ''; + return '已复制 ' + sp + srcTitle + ' → ' + relOf(ctx.taskDir, dst) + sizeNote; +} + async function toolWriteFile(ctx, args) { const abs = resolveInTask(ctx.taskDir, args.path); // 纵深防御:引擎 checkToolArgs 已把 null 判缺,但直调 executor(测试等)不经过它; @@ -1382,25 +1525,16 @@ async function toolHandoff(ctx, args) { return '已接收交接(reason: ' + reason + '),本批工具跑完后系统将切换到执行阶段。'; } -// recall:长期记忆(工作日记)的回忆入口(定稿 B 方案:极简三 op,描述短不挤占工具位)。 -// 日记按会话收口持久存储(memory.js),开场只注入最近 N 条;更早的条目与某次工作的成果文件由本工具按需取。 -// 只读数据面:仅能碰本用户的日记与会话(id 同用户校验防互探);link 产出的外链与 mint_public_link 同机制同时效。 +// recall:长期记忆(工作日记)的回忆入口——纯记忆三 op。 +// 日记按会话收口持久存储(memory.js),开场只注入最近 N 条;更早的条目由本工具按需取。 +// 历史成果文件不再归日记管:浏览/导入走 list_directory / copy_path 的 @<会话id>/<路径> 记号 +// (校验单点 resolvePastPath),导入后就是本会话普通文件,read_file/mint 照常处理。 +// 旧 files/link 两 op 是 ls/mint 的沙箱外克隆,已整删(克隆必漂移:link 漏抄 mint 的 realpath 防线)。 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) || ''); - // files/link 共用:解析并校验目标会话(存在 + 同用户 + id 形态),返回 {sid, title, dir} - const resolveSession = () => { - const sid = String(args.id || '').trim(); - if (!/^task-[0-9A-Za-z_\-]+$/.test(sid)) throw new Error('需要 id:日记碎片【编号】里的会话 id(形如 task-YYYYMMDD-NNN)'); - const s = db.prepare('SELECT id, user, title FROM sessions WHERE id = ?').get(sid); - if (!s) throw new Error('会话 ' + sid + ' 不存在(可能已删除)'); - if (String(s.user || '') !== user) throw new Error('无权访问该会话(非当前用户)'); - const root = String((ctx.cfg && ctx.cfg.workspace_root) || ''); - if (!root) throw new Error('workspace_root 未配置'); - return { sid: sid, title: s.title || sid, dir: path.join(root, sid) }; - }; switch (op) { case 'search': { const q = String(args.query || '').trim(); @@ -1419,41 +1553,15 @@ function toolRecall(ctx, args) { const txt = memory.dayEntry(db, user, date); return txt ? date + ' 的日记:\n' + txt : date + ' 无日记。'; } - case 'files': { - const t = resolveSession(); - let names = []; - try { - names = fs.readdirSync(t.dir, { withFileTypes: true }) - .filter(d => d.isFile() && !d.name.startsWith('.')) - .map(d => d.name) - .sort(); - } catch (_) { - return '「' + t.title + '」任务目录不存在,无成果文件。'; - } - if (!names.length) return '「' + t.title + '」无成果文件。'; - const shown = names.slice(0, 80); - return '「' + t.title + '」现存文件(顶层 ' + shown.length + (names.length > shown.length ? '/共 ' + names.length : '') + ' 个):\n' - + shown.map(n => '- ' + n).join('\n'); - } - case 'link': { - const t = resolveSession(); - const rel = String(args.path || '').trim(); - if (!rel) throw new Error('op=link 需要 path(op=files 清单里的文件名)'); - const abs = resolveInTask(t.dir, rel); // 路径沙箱:只允许该会话任务目录内 - let st; - try { st = fs.statSync(abs); } catch (_) { throw new Error('文件不存在:' + rel + '(先 op=files 看现存清单)'); } - if (!st.isFile()) throw new Error('不是普通文件:' + rel); - const pl = ctx.cfg && ctx.cfg.public_link; - if (!pl || !pl.base_url) throw new Error('public_link 未配置,无法生成外链'); - return pl.base_url + '/p/' + publicFiles.mint({ sessionId: t.sid, rel: rel, ttlMs: pl.ttl_ms }); - } default: - throw new Error('未知的 op:"' + op + '"。可用:search(需 query,可选 count)/ days(日期索引)/ day(需 date)/ files(需 id)/ link(需 id+path)'); + throw new Error('未知的 op:"' + op + '"。可用:search(需 query,可选 count)/ days(日期索引)/ day(需 date)。历史会话文件请用 list_directory / copy_path 的 @<会话id>/<路径> 记号'); } } const HANDLERS = { read_file: toolReadFile, + list_directory: toolListDirectory, + copy_path: toolCopyPath, handoff: toolHandoff, write_file: toolWriteFile, edit_file: toolEditFile, diff --git a/app/server/wechat.js b/app/server/wechat.js index 16611f1..9d5cead 100644 --- a/app/server/wechat.js +++ b/app/server/wechat.js @@ -694,7 +694,8 @@ async function deliverConclusion(bid, m, sessionId) { } // 扫回复文本里的 /p/<22位id> 链 → 可卡片化的本地附件({filename, b64},最多 5 个,单文件限 20MB)。 -// 归属校验按「同用户」放行(B 案定稿):recall op=link 合法取旧会话文件,原「同会话」规矩会打断 +// 归属校验按「同用户」放行(B 案定稿:当年 recall op=link 合法取旧会话文件——该 op 现已退役, +// 链接只剩 mint_public_link 从本会话签发;同用户放宽保留,兼容存量会话里已签出的旧形条目),原「同会话」规矩会打断 // 记忆链最后一公里;pid 是 22 位随机不可猜的 bearer 能力,真正要防的是跨用户外流——签发会话查不到 // 主人(已删)也拒。过期(resolve 空)、文件已删、跳出任务目录、超限全部静默跳过——链接文字留在正文可点。 const ATTACH_MAX_BYTES = 20 * 1024 * 1024; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0e1f3a6..8465f12 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -336,7 +336,7 @@ stateDiagram-v2 |---|---| | `read_file` | 走 `resolveInTask` 防路径穿越;图像(PNG/JPEG/WebP/GIF/BMP/TIFF)按 vision 能力走 `sharp` 压缩后落盘 `.imgcache/` 并回传 `image_rel`(长边 ≤ 2000px,JPEG q=80;文件名带源文件 mtime+size 指纹,重读复用不增殖;重编码无收益时不落盘、直指原文件),发送前由 `llm.buildMessages` 现签成公网外链(engine 侧 mint 前 realpath 复核);大文本/二进制给 outline,超 32MB 拒读并引导 terminal;行号前缀格式 "`<6位右对齐行号>\\t<原文>`"(`edit_file` 用) | | `write_file` / `edit_file` | `edit_file` 用模糊定位(Zed 风格):先精确匹配,失败后用 Levenshtein DP 找最相似行;超 32MB 拒绝整文件读写(OOM 防护);DP 候选区间不连续(中间跳过无关 buffer 行)即弃用,防静默吞行;空 `new_text` = 整行干净删除(精确/模糊两层统一,对齐 `"".lines()` 零行语义);`old_text`/`new_text` 协议见 `definitions.json` | -| 已移除的工具 | `list_directory` / `create_directory` / `delete_path` / `move_path` / `copy_path` / `find_path` / `grep`:环境固定,文件操作与检索统一走 `terminal`(ls / mkdir / rm / mv / cp / find / rg),内置工具 17 → 10;技能三件套又并为 `skill` 后为 8;再增元工具 `lab` 为 9(默认被全局 `tools_deny` 屏蔽);后续增 `db`、`profile` 各一 → 现 12 项 | +| 已移除的工具(部分复活) | `list_directory` / `copy_path` 于 2026-09 复活并加 `@/` 只读记号:当年删除理由是「环境固定,统一走 terminal」,但生产 terminal 在远端 executor 容器(compose:wrapper 启动即 unmount host-tasks),其他会话目录在 shell 物理视图里不存在——跨会话取旧成果只剩 core 进程一个口子。校验单点 `resolvePastPath`(形状+存在+同用户,承自 recall 旧 files/link);list_directory 单层 ls(≤200 条、隐藏项不列,@ 模式条目带 '@/' 全形前缀可直接抄进 copy_path);copy_path 源可 @、目标拒 @(历史只读,导入落本会话后 read_file/vision/mint 全量生效,不给存量工具开跨墙特例),预算 200 文件/200MB,符号链接拒收防逃逸(mint 同款防线)。同批拆除 recall 的 files/link 两 op(沙箱外克隆必漂移:link 漏抄 mint 的 realpath 防线),recall 收敛为纯记忆 search/days/day。仍移除:`create_directory` / `delete_path` / `move_path` / `find_path` / `grep`(写删检索继续走 terminal);17→10 大盘不变,复活两件+后续 db/profile → 现 15 项 | | `terminal` | **唯一一个走 executor 的内置工具**(当 `rexec.isRemote(cfg)`);本地分支用 `spawn` + `detached` + 进程组 kill;远端分支 `rexec.run` SSE 收流,结果套上超时/截断/取消注解后 `truncate(text, cfg.terminal.max_output_chars)` 返回 | | `fetch` | `AbortController` 覆盖全生命周期(响应头之后的 body 读流同样被超时/取消打断,取消用与 terminal 同款的 200ms 轮询);content-type 先行,非文本只回状态/类型/尺寸不读 body;**下载/返回双上限解耦**:流式读到 `cfg.fetch.max_bytes`(默认 1MB)即断开(下载不占上下文可宽松),返回窗默认 `max_chars`(12000)字符,模型显式传 `max_chars` 夹在 `max_chars_hard`(64000)硬帽内;超窗尾部拼 `offset` 续读提示,转换后全文缓在 `ctx.run.fetchCache`(回合级 LRU 3 条),续读纯本地切片不重抓;**SSRF 防护**:主机名解析结果含回环/私有/链路本地地址即拒(`allow_private: true` 才放行),`redirect:'manual'` 逐跳复查至多 5 次(残余风险:undici 建连时二次解析,DNS 重绑定不可根治);按响应 charset 解码(full-icu 支持 gbk/gb18030 等,未知编码退回 UTF-8);HTML 用 `htmlToMarkdown` 转(剥 script/style/head 及 nav/header/footer/aside/form 整块,class/id 样板词启发式丢块,`` 提成首行);HTML 实体单遍解码(常见命名实体+数字实体通吃,修 `&` 双重解码);字节截断切在多字节字符中时尾 U+FFFD 去噪;网络错误解包 `err.cause` 直述 ENOTFOUND/TLS 等真因,SSRF/重定向类错误带 `fetchUserError` 标记直接冒泡;engine 不截工具结果,返回值末尾另有 `truncate` 1MB 字符兜底护栏 | | `mint_public_link` | **唯一的 mint 入口**:与 core 同进程,直接 `publicFiles.mint()`,不绕任何 HTTP;`ctx.taskDir` 就是会话目录,`relOf` 的结果正是取用侧要的 `rel`。校验:`public_link.base_url` 已配 + `resolveInTask` 沙箱 + 确认是文件 + `realpath` 未沿符号链接跳出任务目录;返回单行 URL |