/** * ============================================================ * src/tools/download/download.ts —— Download 工具(URL → 文件) * ------------------------------------------------------------ * 通用基础能力:把一个 URL 的字节流下载落盘。填补 WebFetch(HTML→markdown, * 读文本用)与 Bash 之间的原始资源下载能力,供任意任务和工作流复用。 * * 输入: * url 必填,http(s) 资源地址 * path 必填,落盘路径(相对 getWorkingDir 锚定;绝对路径原样) * headers 可选,自定义请求头(如 Referer/User-Agent,绕部分防盗链) * timeout 可选,毫秒,默认 60000(请求和响应体读取的总时限) * max_bytes 可选,体积上限(默认 25MB;超限不写、报错,防失控) * * 输出:成功 = { ok, content: "DOWNLOADED: → ()" }; * 失败 = { ok:false, error } —— 不抛异常,error 喂回 LLM(同全项目工具约定)。 * * 可测:fetch 经 deps 注入(不连真网);落盘走真实 fs(测试用 tmp 目录)。 * ============================================================ */ import { z } from 'zod'; import { randomUUID } from 'node:crypto'; import { existsSync } from 'node:fs'; import { mkdir, realpath, link, rm, writeFile } from 'node:fs/promises'; import { basename, dirname, join, resolve } from 'node:path'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { fileActivityMetadata } from '../shared/fileActivity.js'; import { atomicWriteFile, resolveToolPath } from '../shared/fileUtils.js'; import { emitFileMutation } from '../shared/fileMutationBus.js'; import { readHttpBody } from '../shared/httpBody.js'; import { mustSettleBackgroundTasks } from '../../runtime/invocationPolicy.js'; import { startBackgroundOperation } from '../tasks/backgroundTaskService.js'; const DEFAULT_TIMEOUT_MS = 60_000; const DEFAULT_MAX_BYTES = 25 * 1024 * 1024; // ---------------- 1. Zod 输入 schema ---------------- const inputSchema = z.object({ run_in_background: z .boolean() .optional() .describe( 'Run as a session-owned background task; only new destination files are allowed. Use TaskOutput/TaskStop. Hosts without continuation support may wait instead.', ), url: z .string() .url() .regex(/^https?:\/\//i) .describe('http(s) resource URL to download'), path: z .string() .min(1) .describe( 'Destination file path (relative paths anchor to the working dir)', ), headers: z .record(z.string()) .optional() .describe( 'Optional request headers for the resource (e.g. Referer or User-Agent)', ), timeout: z .number() .int() .positive() .optional() .describe('Timeout in milliseconds (default: 60000)'), max_bytes: z .number() .int() .positive() .optional() .describe( 'Max size in bytes; over this the download is rejected (default: 25MB)', ), }); type DownloadInput = z.infer; const parameters = toToolParameters(inputSchema); const description = '下载 HTTP(S) 原始字节到指定路径;相对路径基于工作目录。前台会覆盖已有文件;run_in_background 仅允许新目标文件,返回 task_id,用 TaskOutput/TaskStop 查询或取消。只有声明自动接续的宿主才会完成后唤醒。取消不等于撤销已完成的写入。'; const activeDestinations = new Set(); /** Resolve aliases even when the destination's parent does not exist yet. */ async function resolveDestination(path: string): Promise { const parent = dirname(path); const physical = await realpath(path).catch( async (error: NodeJS.ErrnoException) => { if (error.code !== 'ENOENT') throw error; if (parent === path) throw error; return resolve(await resolveDestination(parent), basename(path)); }, ); return physical; } /** Publish a fully written new file without replacing a racing writer's file. */ async function publishNewFile( path: string, bytes: Uint8Array, signal: AbortSignal, ): Promise { await mkdir(dirname(path), { recursive: true }); const temp = join(dirname(path), `.${randomUUID()}.download.tmp`); let published = false; try { await writeFile(temp, bytes, { flag: 'wx' }); signal.throwIfAborted(); try { await link(temp, path); // Atomic create-if-absent; EEXIST never overwrites. } catch (error) { if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new Error(`目标已被其他操作创建,未覆盖:${path}`); throw new Error( `无法安全发布新文件(需要支持硬链接的文件系统),未覆盖目标:${path};${(error as Error).message}`, ); } published = true; } finally { try { await rm(temp, { force: true, maxRetries: 3, retryDelay: 50 }); } catch (error) { throw new Error( `${published ? '目标文件已发布,不能当作未写入重试' : '临时文件未清理'}:${temp};${(error as Error).message}`, ); } } } // ---------------- 2. 依赖注入(仅测试) ---------------- interface FetchResponseLike { body?: ReadableStream | null; ok: boolean; status: number; statusText: string; headers: { get(name: string): string | null }; arrayBuffer(): Promise; } type FetchLike = ( url: string, init?: { headers?: Record; signal?: AbortSignal }, ) => Promise; export interface DownloadDeps { fetchImpl: FetchLike; } const defaultDeps: DownloadDeps = { fetchImpl: globalThis.fetch as unknown as FetchLike, }; // ---------------- 3. call() ---------------- async function call( input: DownloadInput, signal?: AbortSignal, deps: DownloadDeps = defaultDeps, cwd = getWorkingDir(), context?: ToolCallContext, ): Promise { const destination = resolveToolPath(input.path, cwd); if (!destination.ok) return destination; if (signal?.aborted) return { ok: false, error: '[Download] 已取消,未启动' }; let physical: string; try { physical = await resolveDestination(destination.resolvedPath); } catch (error) { return { ok: false, error: `[Download] ${(error as Error).message}` }; } const key = process.platform === 'win32' ? physical.toLowerCase() : physical; if (activeDestinations.has(key)) return { ok: false, error: '[Download] 该目标已有下载任务,拒绝并发覆盖;请先等待或取消原任务。', }; if (input.run_in_background && existsSync(physical)) return { ok: false, error: '[Download] 后台下载只允许新目标,文件已存在;请另选路径。', }; activeDestinations.add(key); const execute = async (jobSignal?: AbortSignal) => { try { return await performDownload( { ...input, path: physical }, jobSignal, deps, cwd, ); } finally { activeDestinations.delete(key); } }; if ( input.run_in_background && !mustSettleBackgroundTasks(context?.executionServices?.invocationPolicy) ) { if (!context?.sessionState) { activeDestinations.delete(key); return { ok: false, error: '[Download] 后台下载需要会话宿主;请使用前台模式。', }; } try { signal?.throwIfAborted(); const task = await startBackgroundOperation( { command: `Download → ${destination.resolvedPath}`, cwd, signal, workspaceId: context.workspaceId, sessionId: context.sessionId, deliveryId: context.deliveryId, request: context.backgroundRequest ?? context.currentUserInput, }, execute, context.sessionState.backgroundTasks, ); return { ok: true, content: `后台下载已启动。task_id=${task.id}\n目标:${destination.resolvedPath}\n使用 TaskOutput 查询结果,TaskStop 停止任务;尚未完成下载。`, }; } catch (error) { activeDestinations.delete(key); return { ok: false, error: `[Download] 后台启动失败:${(error as Error).message}`, }; } } return execute(signal); } async function performDownload( input: DownloadInput, signal: AbortSignal | undefined, deps: DownloadDeps, cwd: string, ): Promise { const { url, path } = input; const timeout = input.timeout ?? DEFAULT_TIMEOUT_MS; const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES; if (!/^https?:\/\//i.test(url)) return { ok: false, error: '[Download] 仅支持 HTTP(S) URL' }; let origin: string; try { const target = new URL(url); if (target.username || target.password) return { ok: false, error: '[Download] URL 中不能包含用户名或密码' }; origin = target.origin; } catch { return { ok: false, error: '[Download] URL 格式无效' }; } const destination = resolveToolPath(path, cwd); if (!destination.ok) return destination; const abs = destination.resolvedPath; // 合并外部 signal 与超时 const ctrl = new AbortController(); let committed = false; const timer = setTimeout(() => ctrl.abort(), timeout); const onAbort = () => ctrl.abort(); if (signal) { if (signal.aborted) ctrl.abort(); else signal.addEventListener('abort', onAbort, { once: true }); } try { ctrl.signal.throwIfAborted(); let res: FetchResponseLike; try { res = await deps.fetchImpl(url, { headers: input.headers, signal: ctrl.signal, }); } catch (e) { const msg = ctrl.signal.aborted ? `下载超时(${timeout}ms)或被中断` : e instanceof Error ? e.message : String(e); return { ok: false, error: `[Download] 请求失败:${msg.replaceAll(url, origin)}(${origin})`, }; } if (!res.ok) { void res.body?.cancel().catch(() => undefined); return { ok: false, error: `[Download] HTTP ${res.status}(${origin})`, }; } // content-length 预检(有则提前拒绝超大文件,省下载) const declared = Number(res.headers.get('content-length') ?? ''); if (Number.isFinite(declared) && declared > maxBytes) { void res.body?.cancel().catch(() => undefined); return { ok: false, error: `[Download] 体积 ${declared} 字节超过上限 ${maxBytes}(${origin})`, }; } const buf = await readHttpBody(res, maxBytes, ctrl.signal); if (buf.byteLength > maxBytes) { return { ok: false, error: `[Download] 下载 ${buf.byteLength} 字节超过上限 ${maxBytes}(${origin})`, }; } ctrl.signal.throwIfAborted(); if (input.run_in_background) await publishNewFile(abs, buf, ctrl.signal); else await atomicWriteFile(abs, buf); committed = true; emitFileMutation(abs); const ctype = res.headers.get('content-type') ?? 'unknown'; return { ok: true, content: `DOWNLOADED: ${buf.byteLength} 字节 → ${abs}(${ctype})`, metadata: await fileActivityMetadata( abs, 'generated', 'not_run', 'support', cwd, ), }; } catch (error) { return { ok: false, error: `[Download] ${committed ? `文件已写入 ${abs},后处理失败,禁止当作未写入盲目重试。` : ''}${ctrl.signal.aborted ? '下载超时或被中断;' : ''}${(error instanceof Error ? error.message : String(error)).replaceAll(url, origin)}(${origin})`, }; } finally { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); } } // ---------------- 4. 导出 ---------------- export const downloadTool: Tool = { name: 'Download', description, inputSchema, parameters, isReadOnly: false, // Admission is path-locked across sessions; foreground writes still stay serialized. isConcurrencySafe: false, call, callWithContext: (input, signal, context: ToolCallContext) => call(input, signal, defaultDeps, context.cwd, context), }; // 供单测:直接调 call 注入 deps。 export const _downloadCall = call;