/** * ============================================================ * src/tools/bash/attachImage.ts —— Bash 的「让模型看一眼这张图」协议 * ------------------------------------------------------------ * 背景(为什么需要这个口子): * Read 工具明确拒绝二进制/图片(read.ts 的黑名单),Bash 只能回文本, * 全仓库唯一会产 `ToolResult.visionImages` 的是 WebBrowser。于是任何 * 「skill 脚本生成/截取了一张图,想让模型亲眼看看」的场景都物理上做不到 —— * computer-use(截屏)、生图核验、图表渲染核验全卡在这一处。 * * 方案:约定一个 stdout sentinel。脚本自己打一行 * <<>> * Bash 解析出来填进 visionImages,并把该行**从给模型看的 content 里剥掉** * (协议是给宿主看的,不是给模型读的噪声)。 * * 为什么是 Bash 的 sentinel 而不是新工具: * 工具 schema 已占稳定系统提示词前缀的绝大头,新增一个多 action 的工具 * 等于让**所有用户的每次请求**都为它付 token。sentinel 是零新增 schema * 字节的加性改动,而且天然通用 —— 任何脚本都能用,不绑任何具体 skill。 * * 安全边界(重要): * `multimodal.ts::imageToContentPart` 对路径**没有任何沙箱**,它会老实读 * 任何给它的绝对路径并 base64 进请求体。既然现在允许「命令输出决定读哪个 * 文件」,防线就必须建在这里: * ① 路径必须落在 cwd 或系统临时目录之下(realpath 之后比较,防软链逃逸) * ② 数量上限(图很贵,一次回 20 张能直接打爆上下文) * ③ 单图与总字节上限 * 越界的一律拒绝,并**如实写进 content 告诉模型哪张被拒、为什么** —— * 静默丢弃会让脚本作者以为图发出去了,debug 时无从下手。 * ============================================================ */ import { open, realpath, stat } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { basename, dirname, join, resolve } from 'node:path'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { pathContains } from '../../utils/pathContains.js'; import { MAX_IMAGE_BYTES, sniffImageMime } from '../../multimodal.js'; import type { ImageDetail, ImageInputSpec } from '../../types.js'; /** 一次 Bash 调用最多附多少张图。图是上下文里最贵的东西,宁少勿多。 */ export const MAX_ATTACH_IMAGES = 4; /** * 一次 Bash 调用附图的总字节上限。取单图上限的 2 倍而非 4 倍: * base64 会把体积撑到约 4/3,且 provider 侧有请求体上限(Claude 32MB), * 留足余量给同一请求里的文本与历史。 */ export const MAX_ATTACH_TOTAL_BYTES = MAX_IMAGE_BYTES * 2; /** 整行 sentinel(必须独占一行;行首尾允许空白)。 */ const SENTINEL_LINE = /^[ \t]*<<>>[ \t]*$/; /** 已知的可选段,从 payload 尾部往前剥;剩下的(可能含 `|`)才是路径。 */ const OPTION_SEGMENT = /^(detail|maxLongSide)=(.*)$/; const VALID_DETAILS: ReadonlySet = new Set(['low', 'default', 'high']); /** 解析出来但还没经过 fs / 边界校验的一条指令。 */ export interface AttachImageDirective { /** sentinel 里写的原始路径(可能是相对路径) */ rawPath: string; detail?: ImageDetail; maxLongSidePixel?: number; } export interface ExtractResult { /** 剥掉全部 sentinel 行之后的 stdout */ text: string; directives: AttachImageDirective[]; } /** * 纯函数:从 stdout 里摘出 sentinel 行并剥除。不碰文件系统,便于单测。 * * 无法识别的 payload(如空路径、只有选项没有路径)当作**普通输出行保留** —— * 宁可让模型看到一行奇怪的文本,也不要把用户真实的输出悄悄吃掉。 */ export function extractAttachImageDirectives(stdout: string): ExtractResult { if (!stdout.includes('<< 1) { const tail = segments[segments.length - 1]!; const option = OPTION_SEGMENT.exec(tail.trim()); if (!option) break; const [, key, rawValue] = option; const value = (rawValue ?? '').trim(); if (key === 'detail') { if (!VALID_DETAILS.has(value)) return null; // 写错了就整条不认,别猜 detail = value as ImageDetail; } else { const n = Number(value); if (!Number.isFinite(n) || n <= 0) return null; maxLongSidePixel = Math.floor(n); } segments.pop(); } const rawPath = segments.join('|').trim(); if (!rawPath) return null; return { rawPath, ...(detail ? { detail } : {}), ...(maxLongSidePixel !== undefined ? { maxLongSidePixel } : {}), }; } export interface ResolveResult { images: ImageInputSpec[]; /** 被拒绝的条目说明;调用方须把它拼进 content,让模型知道图没发出去。 */ rejections: string[]; } export interface ResolveOptions { /** 允许的根目录(默认 cwd + 系统临时目录)。测试可注入。 */ allowedRoots?: string[]; maxImages?: number; maxTotalBytes?: number; } /** * 校验并解析成 `ImageInputSpec`。逐条独立判定 —— 一张被拒不影响其它张。 */ export async function resolveAttachImages( directives: AttachImageDirective[], options: ResolveOptions = {}, ): Promise { if (directives.length === 0) return { images: [], rejections: [] }; const maxImages = options.maxImages ?? MAX_ATTACH_IMAGES; const maxTotalBytes = options.maxTotalBytes ?? MAX_ATTACH_TOTAL_BYTES; const roots = await canonicalRoots(options.allowedRoots ?? [getWorkingDir(), tmpdir()]); const images: ImageInputSpec[] = []; const rejections: string[] = []; let totalBytes = 0; for (const directive of directives) { if (images.length >= maxImages) { rejections.push(`${directive.rawPath}:一次最多附 ${maxImages} 张图,已超出`); continue; } const absolute = resolve(getWorkingDir(), directive.rawPath); const canonical = await canonicalize(absolute); if (!roots.some((root) => isInside(root, canonical))) { rejections.push( `${directive.rawPath}:路径不在当前工作目录或系统临时目录之下,已拒绝`, ); continue; } const st = await stat(canonical).catch(() => null); if (!st) { rejections.push(`${directive.rawPath}:文件不存在或不可读`); continue; } if (!st.isFile()) { rejections.push(`${directive.rawPath}:不是普通文件`); continue; } if (st.size > MAX_IMAGE_BYTES) { rejections.push( `${directive.rawPath}:单图 ${(st.size / 1024 / 1024).toFixed(1)}MB 超过 ${MAX_IMAGE_BYTES / 1024 / 1024}MB 上限`, ); continue; } if (totalBytes + st.size > maxTotalBytes) { rejections.push( `${directive.rawPath}:累计体积超过 ${maxTotalBytes / 1024 / 1024}MB 上限,已跳过`, ); continue; } const mime = await sniffFileImageMime(canonical); if (!mime) { rejections.push( `${directive.rawPath}:文件内容不是受支持的 JPEG/PNG/GIF/WEBP 图片,已跳过`, ); continue; } totalBytes += st.size; images.push({ source: canonical, ...(directive.detail ? { detail: directive.detail } : {}), ...(directive.maxLongSidePixel !== undefined ? { maxLongSidePixel: directive.maxLongSidePixel } : {}), }); } return { images, rejections }; } /** * 在接受 sentinel 时验魔数,不依赖扩展名。只读取头部,避免为拒绝一张大文件 * 再做一次完整读取。逐条返回 null,由调用方记录 rejection,不抛到整个回合。 */ async function sniffFileImageMime(path: string): Promise { let handle; try { handle = await open(path, 'r'); const header = Buffer.alloc(16); const { bytesRead } = await handle.read(header, 0, header.length, 0); return sniffImageMime(header.subarray(0, bytesRead)); } catch { return null; } finally { await handle?.close().catch(() => {}); } } /** * realpath 之后再比较 —— 否则一条指向 /etc 的软链就能绕过根目录白名单。 * * 目标不存在时不能简单退回 `resolve()`:macOS 的 `os.tmpdir()` 是 * `/var/folders/…`(软链到 `/private/var/folders/…`),根目录已归一化而目标没有, * 于是「临时目录下一个还没生成的文件」会被判成**越界**而不是**不存在** —— * 报错指向错误的原因,脚本作者会去查权限而不是去查文件名。 * 因此回退到「归一化最近的存在祖先,再接回剩余段」。 */ async function canonicalize(path: string): Promise { const absolute = resolve(path); try { return await realpath(absolute); } catch { const parent = dirname(absolute); if (parent === absolute) return absolute; // 已到根,停止递归 return join(await canonicalize(parent), basename(absolute)); } } /** * 根目录也必须 realpath:macOS 的 `os.tmpdir()` 返回 `/var/folders/...`, * 而它其实是 `/private/var/folders/...` 的软链 —— 不归一化的话临时目录里的 * 图会被自己的边界检查误杀。 */ async function canonicalRoots(roots: string[]): Promise { const out: string[] = []; for (const root of roots) { const canonical = await canonicalize(resolve(root)); if (!out.includes(canonical)) out.push(canonical); } return out; } /** target 是否落在 root 之内(含 root 自身)。判据实现见 `utils/pathContains.ts`(全仓唯一一份)。 */ const isInside = pathContains;