import { execFile } from 'node:child_process'; import { createHash, randomUUID } from 'node:crypto'; import { createReadStream } from 'node:fs'; import { cp, lstat, mkdir, readdir, readlink, rename, rm, realpath, } from 'node:fs/promises'; import { homedir } from 'node:os'; import { basename, dirname, isAbsolute, join, relative, resolve, sep, } from 'node:path'; import { promisify } from 'node:util'; import { z } from 'zod'; import { runBoundedProcess } from '../../runtime/boundedProcess.js'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; const exec = promisify(execFile); const pathsField = z.array(z.string().min(1)).min(1).max(200) .describe('仅 action=move:明确列出要移入回收站的路径,不用于限制 git-clean 范围'); const ignoredField = z.boolean().describe('仅 action=git-clean:显式包含 Git 忽略的文件;默认 false'); const schema = z.discriminatedUnion('action', [ z.object({ action: z.literal('move'), paths: pathsField, }).strict(), z.object({ action: z.literal('git-clean'), include_ignored: ignoredField.optional(), }).strict(), ]); const providerSchema = z.object({ action: z.enum(['move', 'git-clean']).describe('move 仅处理 paths;git-clean 枚举当前工作目录下的未跟踪文件,禁止传 paths'), paths: pathsField.optional(), include_ignored: ignoredField.optional(), }).strict(); type Input = z.infer; function inside(root: string, path: string): boolean { const rel = relative(root, path); return ( rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel)) ); } async function gitRoot(cwd: string): Promise { try { return await realpath( ( await exec('git', ['-C', cwd, 'rev-parse', '--show-toplevel']) ).stdout.trim(), ); } catch { return undefined; } } async function validate(path: string, cwd: string): Promise { const lexical = resolve(cwd, path); const target = await realpath(lexical).catch(async (error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT' && (await lstat(lexical)).isSymbolicLink()) return join(await realpath(dirname(lexical)), basename(lexical)); throw error; }); const root = await gitRoot(cwd); if ([target, lexical].some(p => p.split(sep).some(part => part.toLowerCase() === '.git'))) { throw new Error(`拒绝移动 Git 仓库根目录、其祖先或 .git:${target}`); } if ((await lstat(lexical)).isDirectory()) { const marker = await lstat(join(lexical, '.git')).catch((error: NodeJS.ErrnoException) => { if (error.code !== 'ENOENT') throw error; return undefined; }); if (marker) throw new Error(`拒绝移动 Git 仓库根目录:${target}`); } if (root) { const git = join(root, '.git'); if ( target === root || inside(target, root) || lexical === git || inside(git, lexical) || inside(git, target) ) throw new Error(`拒绝移动 Git 仓库根目录、其祖先或 .git:${target}`); } await lstat(lexical); return lexical; } async function fallbackTrash(source: string): Promise { const files = process.platform === 'linux' ? join(homedir(), '.local/share/Trash/files') : join(homedir(), '.Trash'); const info = join(homedir(), '.local/share/Trash/info'); await mkdir(files, { recursive: true, mode: 0o700 }); if (process.platform === 'linux') await mkdir(info, { recursive: true, mode: 0o700 }); const name = `${basename(source)}.${new Date().toISOString().replace(/[:.]/g, '-')}.${randomUUID().slice(0, 8)}`; const target = join(files, name); try { await rename(source, target); } catch { await cp(source, target, { recursive: true, errorOnExist: true, preserveTimestamps: true, verbatimSymlinks: true, }); if ((await treeFingerprint(source)) !== (await treeFingerprint(target))) throw new Error('跨卷复制内容校验失败,来源已保留'); await rm(source, { recursive: true }); } if (process.platform === 'linux') { const encoded = encodeURI(source).replace(/#/g, '%23'); await import('node:fs/promises').then((fs) => fs.writeFile( join(info, `${name}.trashinfo`), `[Trash Info]\nPath=${encoded}\nDeletionDate=${new Date().toISOString().slice(0, 19)}\n`, { mode: 0o600 }, ), ); } return target; } async function treeFingerprint(path: string): Promise { const hash = createHash('sha256'); const visit = async ( current: string, relativePath: string, ): Promise => { const info = await lstat(current); if (info.isSymbolicLink()) { hash.update(`link\0${relativePath}\0${await readlink(current)}\0`); return; } if (info.isDirectory()) { hash.update(`dir\0${relativePath}\0`); const entries = await readdir(current); entries.sort(); for (const entry of entries) await visit(join(current, entry), join(relativePath, entry)); return; } hash.update(`file\0${relativePath}\0${info.size}\0`); for await (const chunk of createReadStream(current)) hash.update(chunk); }; await visit(path, '.'); return hash.digest('hex'); } async function missing(path: string): Promise { return lstat(path) .then(() => false) .catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return true; throw error; }); } async function moveMany(sources: string[], signal?: AbortSignal): Promise { const native = async (command: string, args: string[]) => { const result = await runBoundedProcess(command, args, { timeoutMs: 60_000, signal }); if (result.exitCode !== 0) throw new Error(result.stderr); }; if (process.platform === 'darwin') { try { await native('osascript', [ '-e', 'on run argv', '-e', 'tell application "Finder"', '-e', 'repeat with sourcePath in argv', '-e', 'delete POSIX file (sourcePath as text)', '-e', 'end repeat', '-e', 'end tell', '-e', 'end run', ...sources, ]); if ((await Promise.all(sources.map(missing))).every(Boolean)) return 'macOS Trash'; } catch {} } if (process.platform === 'win32') { const encodedPaths = Buffer.from(JSON.stringify(sources)).toString('base64'); const script = `$paths = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPaths}'))); Add-Type -AssemblyName Microsoft.VisualBasic; foreach ($path in $paths) { if ([IO.Directory]::Exists($path)) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($path,'OnlyErrorDialogs','SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($path,'OnlyErrorDialogs','SendToRecycleBin') } }`; try { await native('powershell.exe', [ '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64'), ]); if ((await Promise.all(sources.map(missing))).every(Boolean)) return 'Windows Recycle Bin'; } catch {} } if (process.platform === 'linux') { try { await native('gio', ['trash', '--', ...sources]); if ((await Promise.all(sources.map(missing))).every(Boolean)) return 'FreeDesktop Trash'; } catch {} } signal?.throwIfAborted(); const destinations: string[] = []; for (const source of sources) { signal?.throwIfAborted(); if (!(await missing(source))) destinations.push(await fallbackTrash(source)); } return destinations.length ? `恢复位置:${destinations.join(';')}` : '系统回收站'; } export async function gitCleanCandidates( cwd: string, ignored: boolean, ): Promise { const root = await gitRoot(cwd); if (!root) throw new Error('当前目录不在 Git 仓库中'); const read = async (extra: string[]) => { const out = ( await exec( 'git', [ '-C', cwd, 'ls-files', '-z', '--others', '--exclude-standard', ...extra, '--', '.', ], { encoding: 'buffer', maxBuffer: 64 * 1024 * 1024 } as any, ) ).stdout as unknown as Buffer; return out.toString('utf8').split('\0').filter(Boolean); }; const names = [ ...(await read([])), ...(ignored ? await read(['--ignored']) : []), ]; // Git lists an embedded repository as a single directory. Do not move its // entire repository (or any directory with ignored contents) as one file. return [...new Set(names)].filter((p) => !p.endsWith('/')).map((p) => resolve(cwd, p)); } async function call( input: Input, context: ToolCallContext, signal?: AbortSignal, ): Promise { const cwd = context.cwd ?? process.cwd(); try { signal?.throwIfAborted(); const raw = input.action === 'move' ? input.paths : await gitCleanCandidates(cwd, input.include_ignored ?? false); const paths = []; for (const item of [...new Set(raw)]) paths.push(await validate(item, cwd)); const moved = []; const destination = paths.length ? await moveMany(paths, signal) : ''; for (const path of paths) { try { await lstat(path); throw new Error(`回收站操作后来源仍存在:${path}`); } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e; } moved.push(`${path} → ${destination}`); } return { ok: true, content: moved.length ? `已可恢复移除;系统回收站或恢复位置如下:\n${moved.join('\n')}` : '没有匹配的未跟踪文件。', }; } catch (e) { return { ok: false, error: `Trash 失败(可能已有部分移动,请核实来源及回收站):${(e as Error).message}` }; } } export const trashTool: Tool = { name: 'Trash', description: '可恢复移动文件到系统回收站或本地恢复目录,结果注明位置。git-clean 仅处理当前目录树下的未跟踪文件,默认跳过 Git 忽略项;显式传 include_ignored=true 才包含忽略项。拒绝仓库根与 .git。失败可能已有部分完成,先核实再重试。', inputSchema: schema, parameters: toToolParameters(providerSchema), isReadOnly: false, isConcurrencySafe: false, call: async () => ({ ok: false, error: 'Trash requires runtime context' }), callWithContext: (input, signal, ctx) => call(input, ctx, signal), };