Files
dxdesigner-part-replacement/integration/dsh/task-plugin/files.mjs
T
阿白叔 705c15eb93
Core regression / Python core and release configuration (push) Successful in 20s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 15s
Core regression / JavaScript syntax (pull_request) Successful in 3s
fix(dsh): restore native file tools and official loading UI
2026-11-04 19:05:21 +08:00

81 lines
4.8 KiB
JavaScript

import {mkdir,mkdtemp,writeFile,realpath,rm} from 'node:fs/promises';
import path from 'node:path';
import {unzip} from 'fflate';
import {defineTool} from '@deepseek-ai/dsh-tools';
import {crc32} from 'node:zlib';
export const fileToolNames=['read','read_image','glob','grep','working_directory','extract_zip'];
function zipChecksums(bytes){
const data=Buffer.from(bytes.buffer,bytes.byteOffset,bytes.byteLength);
let end=data.length-22;
for(;end>=Math.max(0,data.length-65557);end--)
if(data.readUInt32LE(end)===0x06054b50&&end+22+data.readUInt16LE(end+20)===data.length)break;
if(end<0||data.readUInt32LE(end)!==0x06054b50)throw Error('Invalid ZIP central directory');
if(data.readUInt16LE(end+4)||data.readUInt16LE(end+6))throw Error('Multi-volume ZIP is unsupported');
const count=data.readUInt16LE(end+10),entries=[];
if(count===65535||count>10000)throw Error('ZIP exceeds 10000 entries');
let offset=data.readUInt32LE(end+16);
for(let i=0;i<count;i++){
if(offset+46>end||data.readUInt32LE(offset)!==0x02014b50)throw Error('Invalid ZIP entry');
if(data.readUInt16LE(offset+8)&1)throw Error('Encrypted ZIP is unsupported');
const size=data.readUInt32LE(offset+24);
if(size===0xffffffff)throw Error('ZIP64 entries are unsupported');
entries.push({crc:data.readUInt32LE(offset+16),size});
offset+=46+data.readUInt16LE(offset+28)+data.readUInt16LE(offset+30)+data.readUInt16LE(offset+32);
if(offset>end)throw Error('Invalid ZIP entry length');
}
return entries;
}
export function registerFileTools(ctx){
ctx.tools.register(defineTool({name:'extract_zip',
description:'Extract a local or uploaded ZIP archive into a new folder, returning its absolute path and file names. Relative paths use the conversation working directory. output_directory optionally selects an existing parent folder; defaults to the conversation working directory. Never overwrites existing files. Read the returned paths to inspect extracted content. ZIP only; encrypted archives are unsupported.',
parameters:{file_path:{type:'string',required:true},output_directory:{type:'string'}},
output:{schema:{type:'object',additionalProperties:true},render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]},
execute:async(args,exec)=>{
if(typeof args.file_path!=='string'||!args.file_path.trim())throw Error('file_path is required');
const cwd=exec.agent?ctx.workingDirectory.get(exec.agent.session):process.env.DX_DSH_WORKSPACE;
const target=await ctx.fs.resolve(args.file_path,{cwd,signal:exec.signal});
const bytes=await ctx.fs.readBytes(target,exec.signal,64*1024*1024);
const checksums=zipChecksums(bytes),expected=new Map();
let expanded=0,count=0;
const files=await new Promise((resolve,reject)=>unzip(bytes,{filter:entry=>{
const name=entry.name.replaceAll('\\','/');
if(name.startsWith('/')||name.split('/').some(part=>part==='..'||/[\x00-\x1f:]/.test(part)))
throw Error('Unsafe ZIP entry path');
if(expected.has(entry.name))throw Error('Duplicate ZIP entry');
const checksum=checksums[count];
if(!checksum||checksum.size!==entry.originalSize)throw Error('Invalid ZIP entry size');
expected.set(entry.name,checksum);
expanded+=entry.originalSize;
if(++count>10000||expanded>256*1024*1024)throw Error('ZIP exceeds 10000 entries or 256 MiB expanded size');
return true;
}},(error,value)=>error?reject(error):resolve(value)));
if(count!==checksums.length)throw Error('Invalid ZIP entry count');
for(const [name,data] of Object.entries(files)){
const checksum=expected.get(name);
if(data.length!==checksum.size||crc32(data)!==checksum.crc)throw Error('ZIP checksum mismatch: '+name);
}
exec.signal.throwIfAborted();
const parent=await realpath(path.resolve(cwd,args.output_directory||'.'));
const directory=await mkdtemp(path.join(parent,'dsh-extracted-'));
try{
for(const [name,data] of Object.entries(files)){
exec.signal.throwIfAborted();
const output=path.resolve(directory,name.replaceAll('\\','/'));
const relative=path.relative(directory,output);
if(relative.startsWith('..')||path.isAbsolute(relative))throw Error('Unsafe ZIP entry path');
if(name.endsWith('/'))await mkdir(output,{recursive:true});
else{await mkdir(path.dirname(output),{recursive:true});await writeFile(output,data,{flag:'wx'});}
}
return {directory,files:Object.keys(files).slice(0,200),total_entries:count,truncated:count>200};
}catch(error){
// Only this invocation's newly created temporary output is removed.
if(path.dirname(directory)===parent&&path.basename(directory).startsWith('dsh-extracted-'))
await rm(directory,{recursive:true,force:true});
throw error;
}
}}));
}